103 lines
2.4 KiB
TypeScript
103 lines
2.4 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
|
import { trpc } from './trpc-client'
|
|
import { useNavigate } from '@tanstack/react-router'
|
|
|
|
interface Staff {
|
|
id: number
|
|
name: string
|
|
}
|
|
|
|
interface AuthState {
|
|
staff: Staff | null
|
|
isAuthenticated: boolean
|
|
isLoading: boolean
|
|
token: string | null
|
|
}
|
|
|
|
interface AuthContextType extends AuthState {
|
|
login: (name: string, password: string) => Promise<void>
|
|
logout: () => void
|
|
isLoggingIn: boolean
|
|
loginError: string | null
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
|
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
const [state, setState] = useState<AuthState>({
|
|
staff: null,
|
|
isAuthenticated: false,
|
|
isLoading: true,
|
|
token: null,
|
|
})
|
|
const [loginError, setLoginError] = useState<string | null>(null)
|
|
const navigate = useNavigate()
|
|
const loginMutation = trpc.admin.staffUser.login.useMutation()
|
|
|
|
useEffect(() => {
|
|
const storedToken = localStorage.getItem('auth_token')
|
|
if (storedToken) {
|
|
setState((prev) => ({
|
|
...prev,
|
|
token: storedToken,
|
|
isAuthenticated: true,
|
|
isLoading: false,
|
|
}))
|
|
} else {
|
|
setState((prev) => ({ ...prev, isLoading: false }))
|
|
}
|
|
}, [])
|
|
|
|
const login = useCallback(
|
|
async (name: string, password: string) => {
|
|
setLoginError(null)
|
|
try {
|
|
const data = await loginMutation.mutateAsync({ name, password })
|
|
localStorage.setItem('auth_token', data.token)
|
|
setState({
|
|
staff: data.staff,
|
|
token: data.token,
|
|
isAuthenticated: true,
|
|
isLoading: false,
|
|
})
|
|
} catch (error) {
|
|
setLoginError((error as Error).message || 'Login failed')
|
|
throw error
|
|
}
|
|
},
|
|
[loginMutation]
|
|
)
|
|
|
|
const logout = useCallback(() => {
|
|
localStorage.removeItem('auth_token')
|
|
setState({
|
|
staff: null,
|
|
token: null,
|
|
isAuthenticated: false,
|
|
isLoading: false,
|
|
})
|
|
navigate({ to: '/login' })
|
|
}, [navigate])
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{
|
|
...state,
|
|
login,
|
|
logout,
|
|
isLoggingIn: loginMutation.isPending,
|
|
loginError,
|
|
}}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useAuth() {
|
|
const context = useContext(AuthContext)
|
|
if (!context) {
|
|
throw new Error('useAuth must be used within AuthProvider')
|
|
}
|
|
return context
|
|
}
|