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

190 lines
5.4 KiB
TypeScript
Raw Normal View History

2025-07-22 13:46:05 +02:00
// frontend/src/contexts/AuthContext.tsx - UPDATED TO USE NEW REGISTRATION FLOW
2025-07-22 07:37:51 +02:00
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
2025-07-22 13:46:05 +02:00
import { authService, UserProfile, RegisterData } from '../api/services/authService';
2025-07-22 07:37:51 +02:00
import { tokenManager } from '../api/auth/tokenManager';
2025-07-17 13:54:51 +02:00
interface AuthContextType {
2025-07-22 07:37:51 +02:00
user: UserProfile | null;
isAuthenticated: boolean;
isLoading: boolean;
2025-07-17 13:54:51 +02:00
login: (email: string, password: string) => Promise<void>;
2025-07-22 13:46:05 +02:00
register: (data: RegisterData) => Promise<void>; // SIMPLIFIED - no longer needs auto-login
2025-07-22 07:37:51 +02:00
logout: () => Promise<void>;
updateProfile: (updates: Partial<UserProfile>) => Promise<void>;
refreshUser: () => Promise<void>;
2025-07-17 13:54:51 +02:00
}
2025-07-22 07:37:51 +02:00
const AuthContext = createContext<AuthContextType | null>(null);
2025-07-17 13:54:51 +02:00
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 }) => {
2025-07-22 07:37:51 +02:00
const [user, setUser] = useState<UserProfile | null>(null);
const [isLoading, setIsLoading] = useState(true);
2025-07-17 13:54:51 +02:00
2025-07-22 07:37:51 +02:00
// Initialize auth state
2025-07-17 13:54:51 +02:00
useEffect(() => {
2025-07-22 07:37:51 +02:00
const initAuth = async () => {
try {
await tokenManager.initialize();
2025-07-22 09:38:31 +02:00
2025-07-22 07:37:51 +02:00
if (authService.isAuthenticated()) {
2025-07-22 13:46:05 +02:00
// Get user from token first (faster), then validate with API
const tokenUser = tokenManager.getUserFromToken();
if (tokenUser) {
setUser({
id: tokenUser.user_id,
email: tokenUser.email,
full_name: tokenUser.full_name,
is_active: true,
is_verified: tokenUser.is_verified,
created_at: '', // Will be filled by API call
});
}
// Validate with API and get complete profile
try {
const profile = await authService.getCurrentUser();
setUser(profile);
} catch (error) {
console.error('Failed to fetch user profile:', error);
// Keep token-based user data if API fails
}
2025-07-22 07:37:51 +02:00
}
} catch (error) {
console.error('Auth initialization failed:', error);
2025-07-22 13:46:05 +02:00
// Clear potentially corrupted tokens
tokenManager.clearTokens();
2025-07-22 07:37:51 +02:00
} finally {
setIsLoading(false);
}
};
initAuth();
2025-07-17 13:54:51 +02:00
}, []);
2025-07-22 07:37:51 +02:00
const login = useCallback(async (email: string, password: string) => {
2025-07-22 13:46:05 +02:00
setIsLoading(true);
try {
const profile = await authService.login({ email, password });
setUser(profile);
} catch (error) {
setIsLoading(false);
throw error; // Re-throw to let components handle the error
} finally {
setIsLoading(false);
}
2025-07-22 07:37:51 +02:00
}, []);
2025-07-22 13:46:05 +02:00
const register = useCallback(async (data: RegisterData) => {
setIsLoading(true);
try {
// NEW: Registration now handles tokens internally - no auto-login needed!
const profile = await authService.register(data);
setUser(profile);
} catch (error) {
setIsLoading(false);
throw error; // Re-throw to let components handle the error
} finally {
setIsLoading(false);
}
}, []);
2025-07-17 13:54:51 +02:00
2025-07-22 07:37:51 +02:00
const logout = useCallback(async () => {
2025-07-22 13:46:05 +02:00
setIsLoading(true);
try {
await authService.logout();
setUser(null);
} catch (error) {
console.error('Logout error:', error);
// Clear local state even if API call fails
setUser(null);
tokenManager.clearTokens();
} finally {
setIsLoading(false);
}
2025-07-22 07:37:51 +02:00
}, []);
2025-07-17 13:54:51 +02:00
2025-07-22 07:37:51 +02:00
const updateProfile = useCallback(async (updates: Partial<UserProfile>) => {
2025-07-22 13:46:05 +02:00
if (!user) return;
try {
const updated = await authService.updateProfile(updates);
setUser(updated);
} catch (error) {
console.error('Profile update error:', error);
throw error;
}
}, [user]);
2025-07-22 07:37:51 +02:00
const refreshUser = useCallback(async () => {
2025-07-22 13:46:05 +02:00
if (!authService.isAuthenticated()) return;
try {
2025-07-22 07:37:51 +02:00
const profile = await authService.getCurrentUser();
setUser(profile);
2025-07-22 13:46:05 +02:00
} catch (error) {
console.error('User refresh error:', error);
// If refresh fails with 401, user might need to re-login
if (error.status === 401) {
await logout();
}
2025-07-17 13:54:51 +02:00
}
2025-07-22 13:46:05 +02:00
}, [logout]);
2025-07-17 13:54:51 +02:00
2025-07-22 07:37:51 +02:00
// Set up token refresh interval
useEffect(() => {
if (!user) return;
const interval = setInterval(async () => {
try {
2025-07-22 13:46:05 +02:00
await tokenManager.refreshAccessToken();
2025-07-22 07:37:51 +02:00
} catch (error) {
2025-07-22 13:46:05 +02:00
console.error('Scheduled token refresh failed:', error);
// If token refresh fails, user needs to re-login
2025-07-22 07:37:51 +02:00
await logout();
}
2025-07-22 13:46:05 +02:00
}, 60000); // Check every 1 minute
2025-07-22 07:37:51 +02:00
return () => clearInterval(interval);
}, [user, logout]);
2025-07-17 13:54:51 +02:00
2025-07-22 13:46:05 +02:00
// Monitor token expiration
useEffect(() => {
if (!user) return;
const checkTokenValidity = () => {
if (!authService.isAuthenticated()) {
console.warn('Token became invalid, logging out user');
logout();
}
};
// Check token validity every 30 seconds
const interval = setInterval(checkTokenValidity, 30000);
return () => clearInterval(interval);
}, [user, logout]);
const contextValue = {
user,
isAuthenticated: !!user && authService.isAuthenticated(),
isLoading,
login,
register,
logout,
updateProfile,
refreshUser,
};
2025-07-17 13:54:51 +02:00
return (
2025-07-22 13:46:05 +02:00
<AuthContext.Provider value={contextValue}>
2025-07-17 13:54:51 +02:00
{children}
</AuthContext.Provider>
);
};