Files
HeXi/hexi/web/src/auth/auth.tsx
T

30 lines
1.0 KiB
TypeScript
Raw Normal View History

import { createContext, useContext, useState, type ReactNode } from 'react'
import { authLogin, clearSession, getUserName, setSession } from '../api/client'
interface AuthState {
token: string
username: string
login: (u: string, p: string) => Promise<void>
logout: () => void
}
const Ctx = createContext<AuthState>({ token: '', username: '', login: async () => {}, logout: () => {} })
export function AuthProvider({ children }: { children: ReactNode }) {
const [token, setToken] = useState(() => localStorage.getItem('hexi_web_token') || '')
const [username, setUsername] = useState(() => localStorage.getItem('hexi_web_username') || '')
const login = async (u: string, p: string) => {
const data = await authLogin(u, p)
setSession(data.token, data.username)
setToken(data.token)
setUsername(data.username)
}
const logout = () => {
clearSession()
setToken('')
setUsername('')
}
return <Ctx.Provider value={{ token, username, login, logout }}>{children}</Ctx.Provider>
}
export const useAuth = () => useContext(Ctx)