feat: migrate authentication to Logto and clear PWA cache
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
import type { AppUser } from '../types';
|
||||
import { setApiToken, setApiOrganizationId, getBaseUrl } from '../services/api';
|
||||
import { useLogto } from '@logto/react';
|
||||
|
||||
const API_URL = getBaseUrl();
|
||||
|
||||
@@ -23,40 +24,55 @@ export interface AuthContextType {
|
||||
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const { isAuthenticated, getAccessToken, signOut, isLoading: isLogtoLoading } = useLogto();
|
||||
const [appUser, setAppUser] = useState<AppUser | null>(null);
|
||||
const [token, setToken] = useState<string | null>(localStorage.getItem('jwt_token'));
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchTokenAndUser = async () => {
|
||||
if (isAuthenticated) {
|
||||
try {
|
||||
const accessToken = await getAccessToken();
|
||||
if (accessToken) {
|
||||
setToken(accessToken);
|
||||
setApiToken(accessToken);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
} else if (!isLogtoLoading) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchTokenAndUser();
|
||||
}, [isAuthenticated, isLogtoLoading, getAccessToken]);
|
||||
|
||||
// Initial load: se tem token, setar no interceptor e buscar dados do usuário
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
setApiToken(token);
|
||||
refetchUser();
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const login = useCallback((newToken: string, user: AppUser) => {
|
||||
localStorage.setItem('jwt_token', newToken);
|
||||
setToken(newToken);
|
||||
setAppUser(user);
|
||||
setApiToken(newToken);
|
||||
|
||||
// Se a organização existir, setar o header
|
||||
if (user.organizationId) {
|
||||
setApiOrganizationId(user.organizationId);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
localStorage.removeItem('jwt_token');
|
||||
setToken(null);
|
||||
setAppUser(null);
|
||||
setApiToken(null);
|
||||
setApiOrganizationId(null);
|
||||
}, []);
|
||||
signOut(window.location.origin);
|
||||
}, [signOut]);
|
||||
|
||||
const refetchUser = useCallback(async () => {
|
||||
if (!token) return;
|
||||
|
||||
Reference in New Issue
Block a user