82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
import { createContext, useContext, useState, useEffect } from "react";
|
|
import api from "../services/api";
|
|
import { PerfilUsuario } from "../types/usuario";
|
|
|
|
interface AuthContextData {
|
|
isAuthenticated: boolean;
|
|
isLoading: boolean;
|
|
user: {
|
|
id: string;
|
|
nome: string;
|
|
email: string;
|
|
perfil: PerfilUsuario;
|
|
} | null;
|
|
login: (email: string, password: string) => Promise<void>;
|
|
logout: () => void;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextData>({} as AuthContextData);
|
|
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
const [user, setUser] = useState(null);
|
|
|
|
useEffect(() => {
|
|
const checkAuth = async () => {
|
|
try {
|
|
const token = localStorage.getItem("@AdvX:token");
|
|
if (token) {
|
|
api.defaults.headers.authorization = `Bearer ${token}`;
|
|
const response = await api.get("/auth/me");
|
|
setUser(response.data);
|
|
setIsAuthenticated(true);
|
|
}
|
|
} catch (error) {
|
|
console.error("Erro na autenticação:", error);
|
|
localStorage.removeItem("@AdvX:token");
|
|
api.defaults.headers.authorization = "";
|
|
setUser(null);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
checkAuth();
|
|
}, []);
|
|
|
|
const login = async (email: string, password: string) => {
|
|
try {
|
|
const response = await api.post("/auth/login", { email, password });
|
|
const { token, user: userData } = response.data;
|
|
|
|
console.log("Login - User data:", userData); // Debug log
|
|
|
|
localStorage.setItem("@AdvX:token", token);
|
|
api.defaults.headers.authorization = `Bearer ${token}`;
|
|
setUser(userData);
|
|
setIsAuthenticated(true);
|
|
} catch (error) {
|
|
console.error("Erro ao fazer login:", error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
const logout = () => {
|
|
localStorage.removeItem("@AdvX:token");
|
|
api.defaults.headers.authorization = "";
|
|
setIsAuthenticated(false);
|
|
setUser(null);
|
|
};
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{ isAuthenticated, isLoading, user, login, logout }}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
export const useAuth = () => useContext(AuthContext);
|