Files
bakery-ia/frontend/src/contexts/AuthContext.tsx
2025-07-22 07:37:51 +02:00

111 lines
3.0 KiB
TypeScript

// src/contexts/AuthContext.tsx
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { authService, UserProfile } from '../api/auth/authService';
import { tokenManager } from '../api/auth/tokenManager';
interface AuthContextType {
user: UserProfile | null;
isAuthenticated: boolean;
isLoading: boolean;
login: (email: string, password: string) => Promise<void>;
register: (data: any) => Promise<void>;
logout: () => Promise<void>;
updateProfile: (updates: Partial<UserProfile>) => Promise<void>;
refreshUser: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | null>(null);
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<UserProfile | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Initialize auth state
useEffect(() => {
const initAuth = async () => {
try {
await tokenManager.initialize();
if (authService.isAuthenticated()) {
const profile = await authService.getCurrentUser();
setUser(profile);
}
} catch (error) {
console.error('Auth initialization failed:', error);
} finally {
setIsLoading(false);
}
};
initAuth();
}, []);
const login = useCallback(async (email: string, password: string) => {
const profile = await authService.login({ email, password });
setUser(profile);
}, []);
const register = useCallback(async (data: any) => {
const profile = await authService.register(data);
setUser(profile);
}, []);
const logout = useCallback(async () => {
await authService.logout();
setUser(null);
}, []);
const updateProfile = useCallback(async (updates: Partial<UserProfile>) => {
const updated = await authService.updateProfile(updates);
setUser(updated);
}, [updateProfile]);
const refreshUser = useCallback(async () => {
if (authService.isAuthenticated()) {
const profile = await authService.getCurrentUser();
setUser(profile);
}
}, []);
// Set up token refresh interval
useEffect(() => {
if (!user) return;
// Check token expiry every minute
const interval = setInterval(async () => {
try {
await tokenManager.getAccessToken(); // This will refresh if needed
} catch (error) {
console.error('Token refresh failed:', error);
await logout();
}
}, 60000); // 1 minute
return () => clearInterval(interval);
}, [user, logout]);
return (
<AuthContext.Provider
value={{
user,
isAuthenticated: !!user,
isLoading,
login,
register,
logout,
updateProfile,
refreshUser
}}
>
{children}
</AuthContext.Provider>
);
};