87 lines
1.9 KiB
TypeScript
87 lines
1.9 KiB
TypeScript
import {
|
|
createContext,
|
|
useContext,
|
|
useState,
|
|
useEffect,
|
|
type ReactNode,
|
|
} from "react";
|
|
|
|
interface User {
|
|
name?: string;
|
|
email?: string;
|
|
avatar?: string;
|
|
}
|
|
|
|
interface AuthContextType {
|
|
user: User | null;
|
|
isLoading: boolean;
|
|
checkAuth: () => Promise<void>;
|
|
logout: () => void;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
|
|
const checkAuth = async () => {
|
|
setIsLoading(true);
|
|
try {
|
|
const token = localStorage.getItem("auth_token");
|
|
|
|
if (!token) {
|
|
setUser(null);
|
|
setIsLoading(false);
|
|
return;
|
|
}
|
|
|
|
const response = await fetch("/api/v1/session", {
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
});
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
setUser(data.user);
|
|
console.log("User loaded:", data.user);
|
|
} else {
|
|
console.error("Token invalid, removing");
|
|
localStorage.removeItem("auth_token");
|
|
setUser(null);
|
|
}
|
|
} catch (error) {
|
|
console.error("Auth check failed:", error);
|
|
localStorage.removeItem("auth_token");
|
|
setUser(null);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const logout = () => {
|
|
localStorage.removeItem("auth_token");
|
|
setUser(null);
|
|
};
|
|
|
|
useEffect(() => {
|
|
checkAuth();
|
|
}, []);
|
|
|
|
return (
|
|
<AuthContext.Provider value={{ user, isLoading, checkAuth, logout }}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
// eslint-disable-next-line react-refresh/only-export-components
|
|
export function useAuth() {
|
|
const context = useContext(AuthContext);
|
|
if (!context) {
|
|
throw new Error("useAuth must be used within AuthProvider");
|
|
}
|
|
return context;
|
|
}
|