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

97 lines
3.0 KiB
TypeScript
Raw Normal View History

2025-09-19 11:44:38 +02:00
import React, { createContext, useContext, useEffect, ReactNode, useState } from 'react';
2025-08-28 10:41:04 +02:00
import { useAuthStore, User } from '../stores/auth.store';
2025-09-19 11:44:38 +02:00
import { authService } from '../api/services/auth';
2025-08-28 10:41:04 +02:00
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();
2025-09-19 11:44:38 +02:00
const [isInitializing, setIsInitializing] = useState(true);
2025-08-28 10:41:04 +02:00
// Initialize auth on mount
useEffect(() => {
const initializeAuth = async () => {
2025-09-19 11:44:38 +02:00
setIsInitializing(true);
// Wait a bit for zustand persist to rehydrate
await new Promise(resolve => setTimeout(resolve, 100));
2025-08-28 10:41:04 +02:00
// Check if we have stored auth data
2025-09-19 11:44:38 +02:00
if (authStore.token && authStore.refreshToken) {
2025-08-28 10:41:04 +02:00
try {
2025-09-19 11:44:38 +02:00
// Validate current token by trying to verify it
await authService.verifyToken();
console.log('Token is valid, user authenticated');
2025-08-28 10:41:04 +02:00
} catch (error) {
2025-09-19 11:44:38 +02:00
console.log('Token expired, attempting refresh...');
// Token is invalid, try to refresh
try {
await authStore.refreshAuth();
console.log('Token refreshed successfully');
} catch (refreshError) {
console.log('Token refresh failed, logging out:', refreshError);
// Refresh failed, clear auth
authStore.logout();
}
2025-08-28 10:41:04 +02:00
}
2025-09-19 11:44:38 +02:00
} else if (authStore.isAuthenticated) {
// User is marked as authenticated but no tokens, logout
console.log('No tokens found but user marked as authenticated, logging out');
authStore.logout();
} else {
console.log('No stored auth data found');
2025-08-28 10:41:04 +02:00
}
2025-09-19 11:44:38 +02:00
setIsInitializing(false);
2025-08-28 10:41:04 +02:00
};
initializeAuth();
}, []);
const contextValue: AuthContextType = {
user: authStore.user,
isAuthenticated: authStore.isAuthenticated,
2025-09-19 11:44:38 +02:00
isLoading: authStore.isLoading || isInitializing,
2025-08-28 10:41:04 +02:00
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>
);
};