Download frontend/src/auth/AuthContext.jsx from MoBkr/dosemate: direct link, hf CLI and curl.
- Browser
- Download file 1.76 kB
-
https://huggingface.co/spaces/MoBkr/dosemate/resolve/main/frontend/src/auth/AuthContext.jsx
- Command line
-
hf download hf://spaces/MoBkr/dosemate/frontend/src/auth/AuthContext.jsx
-
curl -L -o AuthContext.jsx https://huggingface.co/spaces/MoBkr/dosemate/resolve/main/frontend/src/auth/AuthContext.jsx
1.76 kB
| import { createContext, useContext, useState, useEffect, useCallback } from "react" | |
| import * as api from "../api" | |
| const AuthContext = createContext(null) | |
| export function AuthProvider({ children }) { | |
| const [user, setUser] = useState(null) | |
| const [loading, setLoading] = useState(true) | |
| // On mount, if a token exists, try to restore the session. | |
| useEffect(() => { | |
| const token = localStorage.getItem(api.TOKEN_KEY) | |
| if (!token) { | |
| setLoading(false) | |
| return | |
| } | |
| api.getMe() | |
| .then((u) => setUser(u)) | |
| .catch(() => localStorage.removeItem(api.TOKEN_KEY)) | |
| .finally(() => setLoading(false)) | |
| }, []) | |
| const login = useCallback(async (email, password) => { | |
| const data = await api.login(email, password) | |
| localStorage.setItem(api.TOKEN_KEY, data.token) | |
| setUser(data.user) | |
| return data.user | |
| }, []) | |
| const signup = useCallback(async (name, email, password, language) => { | |
| const data = await api.signup(name, email, password, language) | |
| localStorage.setItem(api.TOKEN_KEY, data.token) | |
| setUser(data.user) | |
| return data.user | |
| }, []) | |
| const logout = useCallback(() => { | |
| localStorage.removeItem(api.TOKEN_KEY) | |
| setUser(null) | |
| window.location.href = "/login" | |
| }, []) | |
| const refreshUser = useCallback(async () => { | |
| try { | |
| const u = await api.getMe() | |
| setUser(u) | |
| return u | |
| } catch { | |
| return null | |
| } | |
| }, []) | |
| return ( | |
| <AuthContext.Provider | |
| value={{ user, loading, login, signup, logout, refreshUser, isAuthenticated: !!user }} | |
| > | |
| {children} | |
| </AuthContext.Provider> | |
| ) | |
| } | |
| export function useAuth() { | |
| const ctx = useContext(AuthContext) | |
| if (!ctx) throw new Error("useAuth must be used within AuthProvider") | |
| return ctx | |
| } | |