114 lines
3.1 KiB
TypeScript
114 lines
3.1 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect, useCallback } from "react";
|
|
import { Usuario } from "../types/entities";
|
|
import api from "../services/api";
|
|
import axios from "axios"; // Adicionar importação do axios
|
|
import { AuthResponse } from "../types/auth";
|
|
|
|
interface AuthContextData {
|
|
user: Partial<Usuario> | null;
|
|
signIn: (email: string, senha: string) => Promise<void>;
|
|
signOut: () => void;
|
|
isAuthenticated: boolean;
|
|
getToken: () => string | null; // Nova função
|
|
}
|
|
|
|
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<{
|
|
id: string;
|
|
nome: string;
|
|
email: string;
|
|
perfil: PerfilUsuario;
|
|
} | null>(null);
|
|
|
|
useEffect(() => {
|
|
const token = localStorage.getItem("@AdvX:token");
|
|
if (token) {
|
|
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
|
api.get("/auth/me")
|
|
.then(response => {
|
|
setUser(response.data);
|
|
setIsAuthenticated(true);
|
|
})
|
|
.catch(() => {
|
|
localStorage.removeItem("@AdvX:token");
|
|
api.defaults.headers.common['Authorization'] = undefined;
|
|
setUser(null);
|
|
setIsAuthenticated(false);
|
|
})
|
|
.finally(() => {
|
|
setIsLoading(false);
|
|
});
|
|
} else {
|
|
setIsLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
const login = async (email: string, senha: string) => {
|
|
try {
|
|
const response = await api.post<AuthResponse>("/auth/login", {
|
|
email,
|
|
senha,
|
|
});
|
|
const { token, user } = response.data;
|
|
|
|
localStorage.setItem("@AdvX:token", token);
|
|
api.defaults.headers.authorization = `Bearer ${token}`;
|
|
setUser(user);
|
|
setIsAuthenticated(true);
|
|
|
|
console.log("Login bem sucedido:", { user });
|
|
} catch (error) {
|
|
console.error("Erro no login:", error);
|
|
setIsAuthenticated(false);
|
|
setUser(null);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
const signOut = useCallback(() => {
|
|
localStorage.removeItem("@AdvX:token");
|
|
api.defaults.headers.common['Authorization'] = undefined;
|
|
setUser(null);
|
|
setIsAuthenticated(false);
|
|
}, []);
|
|
|
|
// Adicionar uma função explícita para obter o token
|
|
const getToken = () => {
|
|
return localStorage.getItem("@AdvX:token");
|
|
};
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center">
|
|
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{
|
|
user,
|
|
signIn: login,
|
|
signOut,
|
|
isAuthenticated,
|
|
getToken, // Nova função
|
|
}}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
export const useAuth = () => {
|
|
const context = useContext(AuthContext);
|
|
if (!context) {
|
|
throw new Error("useAuth deve ser usado dentro de um AuthProvider");
|
|
}
|
|
return context;
|
|
};
|