98 lines
2.3 KiB
TypeScript
98 lines
2.3 KiB
TypeScript
|
|
'use client';
|
||
|
|
|
||
|
|
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||
|
|
import { useRouter } from 'next/navigation';
|
||
|
|
import { api, type LoginResponse } from '@/lib/api';
|
||
|
|
|
||
|
|
interface User {
|
||
|
|
id: string;
|
||
|
|
email: string;
|
||
|
|
role: string;
|
||
|
|
firstName: string;
|
||
|
|
lastName: string;
|
||
|
|
avatar: string | null;
|
||
|
|
}
|
||
|
|
|
||
|
|
interface AuthContextType {
|
||
|
|
user: User | null;
|
||
|
|
isLoading: boolean;
|
||
|
|
isAuthenticated: boolean;
|
||
|
|
login: (email: string, password: string) => Promise<void>;
|
||
|
|
logout: () => Promise<void>;
|
||
|
|
}
|
||
|
|
|
||
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||
|
|
|
||
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||
|
|
const [user, setUser] = useState<User | null>(null);
|
||
|
|
const [isLoading, setIsLoading] = useState(true);
|
||
|
|
const router = useRouter();
|
||
|
|
|
||
|
|
const checkAuth = useCallback(() => {
|
||
|
|
try {
|
||
|
|
const token = localStorage.getItem('accessToken');
|
||
|
|
const storedUser = localStorage.getItem('user');
|
||
|
|
|
||
|
|
if (token && storedUser) {
|
||
|
|
const parsedUser = JSON.parse(storedUser);
|
||
|
|
if (parsedUser.role === 'ADMIN') {
|
||
|
|
setUser(parsedUser);
|
||
|
|
} else {
|
||
|
|
// Not admin, clear storage
|
||
|
|
localStorage.removeItem('accessToken');
|
||
|
|
localStorage.removeItem('refreshToken');
|
||
|
|
localStorage.removeItem('user');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
} catch {
|
||
|
|
// Invalid stored data
|
||
|
|
localStorage.removeItem('accessToken');
|
||
|
|
localStorage.removeItem('refreshToken');
|
||
|
|
localStorage.removeItem('user');
|
||
|
|
} finally {
|
||
|
|
setIsLoading(false);
|
||
|
|
}
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
checkAuth();
|
||
|
|
}, [checkAuth]);
|
||
|
|
|
||
|
|
const login = async (email: string, password: string) => {
|
||
|
|
const response: LoginResponse = await api.login(email, password);
|
||
|
|
setUser(response.user);
|
||
|
|
router.push('/dashboard');
|
||
|
|
};
|
||
|
|
|
||
|
|
const logout = async () => {
|
||
|
|
try {
|
||
|
|
await api.logout();
|
||
|
|
} finally {
|
||
|
|
setUser(null);
|
||
|
|
router.push('/login');
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
return (
|
||
|
|
<AuthContext.Provider
|
||
|
|
value={{
|
||
|
|
user,
|
||
|
|
isLoading,
|
||
|
|
isAuthenticated: !!user,
|
||
|
|
login,
|
||
|
|
logout,
|
||
|
|
}}
|
||
|
|
>
|
||
|
|
{children}
|
||
|
|
</AuthContext.Provider>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useAuth() {
|
||
|
|
const context = useContext(AuthContext);
|
||
|
|
if (context === undefined) {
|
||
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
||
|
|
}
|
||
|
|
return context;
|
||
|
|
}
|