40 lines
994 B
JavaScript
40 lines
994 B
JavaScript
import { createContext, useContext, useState } from 'react';
|
|
|
|
const USERS = [
|
|
{ username: 'admin', password: 'admin', role: 'admin' },
|
|
{ username: 'alice', password: 'bob', role: 'user' },
|
|
];
|
|
|
|
const AuthContext = createContext(null);
|
|
|
|
export function AuthProvider({ children }) {
|
|
const [user, setUser] = useState(() => {
|
|
const saved = localStorage.getItem('auth');
|
|
return saved ? JSON.parse(saved) : null;
|
|
});
|
|
|
|
function login(username, password) {
|
|
const found = USERS.find(u => u.username === username && u.password === password);
|
|
if (!found) return false;
|
|
const { password: _, ...safe } = found;
|
|
setUser(safe);
|
|
localStorage.setItem('auth', JSON.stringify(safe));
|
|
return true;
|
|
}
|
|
|
|
function logout() {
|
|
setUser(null);
|
|
localStorage.removeItem('auth');
|
|
}
|
|
|
|
return (
|
|
<AuthContext.Provider value={{ user, login, logout }}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useAuth() {
|
|
return useContext(AuthContext);
|
|
}
|