blob: 044a6b59c5c95fe72b94243a2b9ff5d3fa01ce2e (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
'use client';
import { createContext, useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
const AuthContext = createContext();
export function AuthProvider({ children }) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
useEffect(() => {
// Check if token exists
const token = localStorage.getItem('token');
if (token) {
setIsAuthenticated(true);
} else {
router.push('/');
}
setIsLoading(false);
}, [router]);
const logout = () => {
localStorage.removeItem('token');
localStorage.removeItem('apiUrl');
setIsAuthenticated(false);
router.push('/');
};
return (
<AuthContext.Provider value={{ isAuthenticated, isLoading, logout }}>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => useContext(AuthContext);
|