-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthContext.jsx
65 lines (59 loc) · 1.77 KB
/
AuthContext.jsx
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
import React, { createContext, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
export const AuthContext = createContext(undefined);
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const navigate = useNavigate();
const [userData, setUserData] = useState({});
const checkAuthStatus = async () => {
try {
const response = await fetch('/api/users/check-auth', {
credentials: 'include',
});
if (response.ok) {
setIsAuthenticated(true);
setUserData(await response.json());
console.log('User is authenticated', response);
} else {
setIsAuthenticated(false);
console.log('User is not authenticated', response);
// navigate('/login'); // Redirect to login page if not authenticated
}
} catch (error) {
console.error('Error checking authentication status:', error);
setIsAuthenticated(false);
// navigate('/login'); // Redirect to login page if not authenticated
}
};
useEffect(() => {
checkAuthStatus();
}, []);
const logout = async () => {
try {
const response = await fetch('/api/users/logout', {
method: 'POST',
credentials: 'include',
});
setIsAuthenticated(false);
console.log('Logout successful', response);
navigate('/login');
// Redirect to login page or perform other actions
} catch (error) {
console.error('Logout failed:', error);
}
};
// ... in AuthProvider value
return (
<AuthContext.Provider
value={{
userData,
isAuthenticated,
setIsAuthenticated,
logout,
setUserData,
}}
>
{children}
</AuthContext.Provider>
);
};