Files
bakery-ia/frontend/src/contexts/AuthContext.tsx

97 lines
2.8 KiB
TypeScript
Raw Normal View History

2025-08-28 10:41:04 +02:00
import React, { createContext, useContext, useEffect, ReactNode } from 'react';
import { useAuthStore, User } from '../stores/auth.store';
interface AuthContextType {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
refreshAuth: () => Promise<void>;
clearError: () => void;
hasPermission: (permission: string) => boolean;
hasRole: (role: string) => boolean;
canAccess: (resource: string, action: string) => boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
interface AuthProviderProps {
children: ReactNode;
}
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const authStore = useAuthStore();
// Initialize auth on mount
useEffect(() => {
const initializeAuth = async () => {
// Check if we have stored auth data
const storedAuth = localStorage.getItem('auth-storage');
if (storedAuth) {
try {
const { state } = JSON.parse(storedAuth);
if (state.token && state.user) {
// Validate token by attempting to refresh
try {
await authStore.refreshAuth();
} catch (error) {
// Token is invalid, clear auth
authStore.logout();
}
}
} catch (error) {
console.error('Error parsing stored auth:', error);
authStore.logout();
}
}
};
initializeAuth();
}, []);
// Set up token refresh interval
useEffect(() => {
if (authStore.isAuthenticated && authStore.token) {
const refreshInterval = setInterval(() => {
if (authStore.refreshToken) {
authStore.refreshAuth().catch(() => {
// Refresh failed, logout user
authStore.logout();
});
}
}, 14 * 60 * 1000); // Refresh every 14 minutes
return () => clearInterval(refreshInterval);
}
}, [authStore.isAuthenticated, authStore.token, authStore.refreshToken]);
const contextValue: AuthContextType = {
user: authStore.user,
isAuthenticated: authStore.isAuthenticated,
isLoading: authStore.isLoading,
error: authStore.error,
login: authStore.login,
logout: authStore.logout,
refreshAuth: authStore.refreshAuth,
clearError: authStore.clearError,
hasPermission: authStore.hasPermission,
hasRole: authStore.hasRole,
canAccess: authStore.canAccess,
};
return (
<AuthContext.Provider value={contextValue}>
{children}
</AuthContext.Provider>
);
};