/
VVRONGG
/
backside
Обзор
Документация
Войти
/
VVRONGG
/
backside
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
1
CI/CD
Аналитика
Безопасность
master
admin/src/auth.tsx
44 строки
1 KB
VVrongg
feat(admin): React/Vite SPA for managing objectives and routes
22 май 2026, 21:13
22 май 2026, 21:13
dca9b47
Код
Авторство
О чём код?
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; import { api, AUTH_EXPIRED_EVENT, clearToken, getToken, setToken } from './api'; interface AuthContextValue { isAuthed: boolean; login: (username: string, password: string) => Promise<void>; logout: () => void; } const AuthContext = createContext<AuthContextValue | null>(null); export function AuthProvider({ children }: { children: ReactNode }) { const [token, setTok] = useState<string | null>(getToken()); // A 401 anywhere clears the stored token and fires this event; mirror that // into React state so the UI immediately falls back to the login screen. useEffect(() => { const onExpired = () => setTok(null); window.addEventListener(AUTH_EXPIRED_EVENT, onExpired); return () => window.removeEventListener(AUTH_EXPIRED_EVENT, onExpired); }, []); const login = async (username: string, password: string) => { const { token } = await api.login(username, password); setToken(token); setTok(token); }; const logout = () => { clearToken(); setTok(null); }; return ( <AuthContext.Provider value={{ isAuthed: token !== null, login, logout }}> {children} </AuthContext.Provider> ); } export function useAuth(): AuthContextValue { const ctx = useContext(AuthContext); if (!ctx) throw new Error('useAuth must be used within an AuthProvider'); return ctx; }