added multi user support, move api key to database
build-and-push / build (push) Failing after 35s

This commit is contained in:
2026-08-01 13:16:54 +05:00
parent a7c5fe739a
commit 66073c7891
23 changed files with 2123 additions and 103 deletions
+45 -17
View File
@@ -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 {