| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
- import { api } from './api'
- import type { User } from './types'
- type AuthContextType = {
- user: User | null
- loading: boolean
- authenticate: (mode: 'login' | 'register', phone: string, password: string, contactName?: string, inviteToken?: string) => Promise<void>
- adminLogin: (phone: string, password: string) => Promise<User>
- logout: () => Promise<void>
- setUser: (u: User) => void
- }
- const AuthContext = createContext<AuthContextType>(null!)
- export function AuthProvider({ children }: { children: ReactNode }) {
- const [user, setUser] = useState<User | null>(null)
- const [loading, setLoading] = useState(true)
- useEffect(() => {
- const load = () =>
- localStorage.getItem('xinghen_token')
- ? api
- .me()
- .then((r) => setUser(r.user))
- .catch(() => setUser(null))
- .finally(() => setLoading(false))
- : setLoading(false)
- load()
- addEventListener('auth-expired', load)
- return () => removeEventListener('auth-expired', load)
- }, [])
- async function authenticate(mode: 'login' | 'register', phone: string, password: string, contactName?: string, inviteToken?: string) {
- const r = mode === 'register' ? await api.register(phone, password, contactName || '', inviteToken) : await api.login(phone, password)
- localStorage.setItem('xinghen_token', r.token)
- setUser(r.user)
- }
- async function adminLogin(phone: string, password: string) {
- const r = await api.admin.login(phone, password)
- localStorage.setItem('xinghen_token', r.token)
- setUser(r.user)
- return r.user
- }
- async function logout() {
- await api.logout().catch(() => {})
- localStorage.removeItem('xinghen_token')
- setUser(null)
- }
- return (
- <AuthContext.Provider value={{ user, loading, authenticate, adminLogin, logout, setUser }}>
- {children}
- </AuthContext.Provider>
- )
- }
- export const useAuth = () => useContext(AuthContext)
|