-
Notifications
You must be signed in to change notification settings - Fork 0
/
frontend-auth.js
44 lines (37 loc) · 1.19 KB
/
frontend-auth.js
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
// frontend/src/auth/AuthContext.js
import React, { createContext, useState, useContext } from 'react';
const AuthContext = createContext(null);
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const login = async (username, password) => {
try {
const response = await fetch('/api/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (response.ok) {
const data = await response.json();
setUser({ username, token: data.access_token });
localStorage.setItem('user', JSON.stringify({ username, token: data.access_token }));
return true;
}
} catch (error) {
console.error('Login error:', error);
}
return false;
};
const logout = () => {
setUser(null);
localStorage.removeItem('user');
};
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
// Usage in components:
// import { useAuth } from '../auth/AuthContext';
// const { user, login, logout } = useAuth();