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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
'use client';
import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { useRouter } from 'next/navigation';
import { authApi, userApi } from '@/lib/api';
interface User {
ID: number;
Name: string;
Email: string;
}
interface AuthContextType {
user: User | null;
isLoading: boolean;
isAuthenticated: boolean;
login: (email: string, password: string) => Promise<void>;
signup: (name: string, email: string, password: string) => Promise<void>;
logout: () => void;
}
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const router = useRouter();
// Check if the user is already logged in
useEffect(() => {
const checkAuth = async () => {
const token = localStorage.getItem('token');
if (!token) {
setIsLoading(false);
return;
}
try {
const userData = await userApi.getProfile();
setUser(userData);
} catch (error) {
// Clear invalid token
localStorage.removeItem('token');
} finally {
setIsLoading(false);
}
};
checkAuth();
}, []);
// Login function
const login = async (email: string, password: string) => {
const response = await authApi.login(email, password);
setUser(response.user);
return response;
};
// Signup function
const signup = async (name: string, email: string, password: string) => {
return await authApi.signup(name, email, password);
};
// Logout function
const logout = () => {
authApi.logout();
setUser(null);
};
return (
<AuthContext.Provider
value={{
user,
isLoading,
isAuthenticated: !!user,
login,
signup,
logout
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
|