|
| 1 | +import * as Solid from 'solid-js' |
| 2 | + |
| 3 | +import { sleep } from './utils' |
| 4 | + |
| 5 | +export interface AuthContext { |
| 6 | + isAuthenticated: () => boolean |
| 7 | + login: (username: string) => Promise<void> |
| 8 | + logout: () => Promise<void> |
| 9 | + user: () => string | null |
| 10 | +} |
| 11 | + |
| 12 | +const AuthContext = Solid.createContext<AuthContext | null>(null) |
| 13 | + |
| 14 | +const key = 'tanstack.auth.user' |
| 15 | + |
| 16 | +function getStoredUser() { |
| 17 | + return localStorage.getItem(key) |
| 18 | +} |
| 19 | + |
| 20 | +function setStoredUser(user: string | null) { |
| 21 | + if (user) { |
| 22 | + localStorage.setItem(key, user) |
| 23 | + } else { |
| 24 | + localStorage.removeItem(key) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +export function AuthProvider(props: { children: Solid.JSX.Element }) { |
| 29 | + const [user, setUser] = Solid.createSignal<string | null>(getStoredUser()) |
| 30 | + const isAuthenticated = () => !!user() |
| 31 | + |
| 32 | + const logout = async () => { |
| 33 | + await sleep(250) |
| 34 | + |
| 35 | + setStoredUser(null) |
| 36 | + setUser(null) |
| 37 | + } |
| 38 | + |
| 39 | + const login = async (username: string) => { |
| 40 | + await sleep(500) |
| 41 | + |
| 42 | + setStoredUser(username) |
| 43 | + setUser(username) |
| 44 | + } |
| 45 | + |
| 46 | + Solid.createEffect(() => { |
| 47 | + setUser(getStoredUser()) |
| 48 | + }) |
| 49 | + |
| 50 | + return ( |
| 51 | + <AuthContext.Provider value={{ isAuthenticated, user, login, logout }}> |
| 52 | + {props.children} |
| 53 | + </AuthContext.Provider> |
| 54 | + ) |
| 55 | +} |
| 56 | + |
| 57 | +export function useAuth() { |
| 58 | + const context = Solid.useContext(AuthContext) |
| 59 | + if (!context) { |
| 60 | + throw new Error('useAuth must be used within an AuthProvider') |
| 61 | + } |
| 62 | + return context |
| 63 | +} |
0 commit comments