Files
adminpanel/src/context/AuthContext.tsx

91 lines
2.2 KiB
TypeScript
Raw Normal View History

'use client';
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { authService, AuthUser, getErrorMessage } from '@/services';
interface AuthContextType {
user: AuthUser | null;
isLoading: boolean;
isAuthenticated: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
error: string | null;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<AuthUser | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const router = useRouter();
const checkAuth = useCallback(() => {
try {
const storedUser = authService.getStoredUser();
if (storedUser && storedUser.role === 'ADMIN') {
setUser(storedUser);
} else if (storedUser) {
// Not admin, clear storage
authService.clearAuth();
}
} catch {
// Invalid stored data
authService.clearAuth();
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
checkAuth();
}, [checkAuth]);
const login = async (email: string, password: string) => {
setError(null);
try {
const response = await authService.login({ email, password });
setUser(response.user);
router.push('/dashboard');
} catch (err) {
const errorMessage = getErrorMessage(err);
setError(errorMessage);
throw new Error(errorMessage);
}
};
const logout = async () => {
try {
await authService.logout();
} finally {
setUser(null);
router.push('/login');
}
};
return (
<AuthContext.Provider
value={{
user,
isLoading,
isAuthenticated: !!user,
login,
logout,
error,
}}
>
{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;
}