83 lines
2.1 KiB
TypeScript
83 lines
2.1 KiB
TypeScript
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from 'react'
|
|
import {
|
|
api,
|
|
ApiError,
|
|
clearToken,
|
|
getToken,
|
|
setToken,
|
|
setUnauthorizedHandler,
|
|
type CurrentUser,
|
|
} from '@/lib/api'
|
|
|
|
interface AuthState {
|
|
user: CurrentUser | null
|
|
authenticated: boolean
|
|
login: (username: string, password: string) => Promise<void>
|
|
logout: () => void
|
|
refresh: () => Promise<void>
|
|
}
|
|
|
|
const AuthContext = createContext<AuthState | null>(null)
|
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
const [user, setUser] = useState<CurrentUser | null>(null)
|
|
|
|
const logout = useCallback(() => {
|
|
api.auth.logout().catch(() => {}) // best effort; token is cleared regardless
|
|
clearToken()
|
|
setUser(null)
|
|
}, [])
|
|
|
|
// Any 401 from the API layer forces a logout so the login screen reappears.
|
|
useEffect(() => {
|
|
setUnauthorizedHandler(() => {
|
|
clearToken()
|
|
setUser(null)
|
|
})
|
|
}, [])
|
|
|
|
// On mount, if a token exists, load the current user; drop the token if it's stale.
|
|
useEffect(() => {
|
|
if (!getToken()) return
|
|
api.auth
|
|
.me()
|
|
.then(setUser)
|
|
.catch(() => {
|
|
clearToken()
|
|
setUser(null)
|
|
})
|
|
}, [])
|
|
|
|
const login = useCallback(async (username: string, password: string) => {
|
|
try {
|
|
const res = await api.auth.login(username, password)
|
|
setToken(res.token)
|
|
// Fetch the full profile (including id) with the fresh token.
|
|
setUser(await api.auth.me())
|
|
} catch (err) {
|
|
clearToken()
|
|
setUser(null)
|
|
if (err instanceof ApiError && err.status === 401) {
|
|
throw new Error('Invalid username or password')
|
|
}
|
|
throw err instanceof Error ? err : new Error('Could not reach the API.')
|
|
}
|
|
}, [])
|
|
|
|
const refresh = useCallback(async () => {
|
|
setUser(await api.auth.me())
|
|
}, [])
|
|
|
|
return (
|
|
<AuthContext value={{ user, authenticated: !!user, login, logout, refresh }}>
|
|
{children}
|
|
</AuthContext>
|
|
)
|
|
}
|
|
|
|
export function useAuth(): AuthState {
|
|
const ctx = useContext(AuthContext)
|
|
if (!ctx) throw new Error('useAuth must be used within AuthProvider')
|
|
return ctx
|
|
}
|