Few fixes

This commit is contained in:
Urtzi Alfaro
2025-07-17 14:34:24 +02:00
parent 5bb3e93da4
commit cb80a93c4b
36 changed files with 1512 additions and 141 deletions

View File

@@ -0,0 +1,103 @@
// frontend/dashboard/src/api/hooks/useAuth.ts
/**
* Authentication hook with state management
*/
import { useState, useEffect, useContext, createContext, ReactNode } from 'react';
import { UserProfile, LoginRequest, RegisterRequest } from '../../types/api';
import { authApi } from '../index';
import { useAsyncAction } from './useApi';
interface AuthContextType {
user: UserProfile | null;
isAuthenticated: boolean;
isLoading: boolean;
login: (credentials: LoginRequest) => Promise<void>;
register: (userData: RegisterRequest) => Promise<void>;
logout: () => Promise<void>;
updateProfile: (updates: Partial<UserProfile>) => Promise<void>;
refreshUser: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<UserProfile | null>(null);
const [isLoading, setIsLoading] = useState(true);
const { execute: executeLogin } = useAsyncAction(authApi.login.bind(authApi));
const { execute: executeRegister } = useAsyncAction(authApi.register.bind(authApi));
const { execute: executeLogout } = useAsyncAction(authApi.logout.bind(authApi));
// Initialize auth state
useEffect(() => {
const initAuth = async () => {
try {
if (authApi.isAuthenticated()) {
const profile = await authApi.getCurrentUser();
setUser(profile);
}
} catch (error) {
// Token might be expired, clear storage
authApi.logout();
} finally {
setIsLoading(false);
}
};
initAuth();
}, []);
const login = async (credentials: LoginRequest) => {
await executeLogin(credentials);
const profile = await authApi.getCurrentUser();
setUser(profile);
};
const register = async (userData: RegisterRequest) => {
const profile = await executeRegister(userData);
setUser(profile);
};
const logout = async () => {
await executeLogout();
setUser(null);
};
const updateProfile = async (updates: Partial<UserProfile>) => {
const updatedProfile = await authApi.updateProfile(updates);
setUser(updatedProfile);
};
const refreshUser = async () => {
if (authApi.isAuthenticated()) {
const profile = await authApi.getCurrentUser();
setUser(profile);
}
};
return (
<AuthContext.Provider
value={{
user,
isAuthenticated: !!user,
isLoading,
login,
register,
logout,
updateProfile,
refreshUser,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthContextType {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}