Files
2026-DEV-BUT3/my-library/src/context/AuthContext.js
T

40 lines
994 B
JavaScript
Raw Normal View History

2026-06-11 22:23:39 +02:00
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);
}