This commit is contained in:
+45
-17
@@ -2,49 +2,77 @@ import { createContext, useCallback, useContext, useEffect, useState, type React
|
||||
import {
|
||||
api,
|
||||
ApiError,
|
||||
clearApiKey,
|
||||
getApiKey,
|
||||
setApiKey,
|
||||
clearToken,
|
||||
getToken,
|
||||
setToken,
|
||||
setUnauthorizedHandler,
|
||||
type CurrentUser,
|
||||
} from '@/lib/api'
|
||||
|
||||
interface AuthState {
|
||||
user: CurrentUser | null
|
||||
authenticated: boolean
|
||||
login: (key: string) => Promise<void>
|
||||
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 [authenticated, setAuthenticated] = useState(() => !!getApiKey())
|
||||
const [user, setUser] = useState<CurrentUser | null>(null)
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearApiKey()
|
||||
setAuthenticated(false)
|
||||
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(logout)
|
||||
}, [logout])
|
||||
setUnauthorizedHandler(() => {
|
||||
clearToken()
|
||||
setUser(null)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const login = useCallback(async (key: string) => {
|
||||
setApiKey(key)
|
||||
// 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 {
|
||||
await api.ping() // validates the key; throws ApiError(401) if wrong
|
||||
setAuthenticated(true)
|
||||
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) {
|
||||
clearApiKey()
|
||||
setAuthenticated(false)
|
||||
clearToken()
|
||||
setUser(null)
|
||||
if (err instanceof ApiError && err.status === 401) {
|
||||
throw new Error('That API key was rejected.')
|
||||
throw new Error('Invalid username or password')
|
||||
}
|
||||
throw err instanceof Error ? err : new Error('Could not reach the API.')
|
||||
}
|
||||
}, [])
|
||||
|
||||
return <AuthContext value={{ authenticated, login, logout }}>{children}</AuthContext>
|
||||
const refresh = useCallback(async () => {
|
||||
setUser(await api.auth.me())
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<AuthContext value={{ user, authenticated: !!user, login, logout, refresh }}>
|
||||
{children}
|
||||
</AuthContext>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth(): AuthState {
|
||||
|
||||
Reference in New Issue
Block a user