Files
BanGUI/frontend/src/providers/AuthProvider.tsx
Lukas 750785680b feat: Stage 2 — authentication and setup flow
Backend (tasks 2.1–2.6, 2.10):
- settings_repo: get/set/delete/get_all CRUD for the key-value settings table
- session_repo: create/get/delete/delete_expired for session rows
- setup_service: bcrypt password hashing, one-time-only enforcement,
  run_setup() / is_setup_complete() / get_password_hash()
- auth_service: login() with bcrypt verify + token creation,
  validate_session() with expiry check, logout()
- setup router: GET /api/setup (status), POST /api/setup (201 / 409)
- auth router: POST /api/auth/login (token + HttpOnly cookie),
               POST /api/auth/logout (clears cookie, idempotent)
- SetupRedirectMiddleware: 307 → /api/setup for all API paths until setup done
- require_auth dependency: cookie or Bearer token → Session or 401
- conftest.py: manually bootstraps app.state.db for router tests
  (ASGITransport does not trigger ASGI lifespan)
- 85 tests pass; ruff 0 errors; mypy --strict 0 errors

Frontend (tasks 2.7–2.9):
- types/auth.ts, types/setup.ts, api/auth.ts, api/setup.ts
- AuthProvider: sessionStorage-backed context (isAuthenticated, login, logout)
- RequireAuth: guard component → /login?next=<path> when unauthenticated
- SetupPage: Fluent UI form, client-side validation, inline errors
- LoginPage: single password input, ?next= redirect after success
- DashboardPage: placeholder (full impl Stage 5)
- App.tsx: full route tree (/setup, /login, /, *)
2026-02-28 21:33:30 +01:00

119 lines
3.6 KiB
TypeScript

/**
* Authentication context and provider.
*
* Manages the user's authenticated state and exposes `login`, `logout`, and
* `isAuthenticated` through `useAuth()`. The session token is persisted in
* `sessionStorage` so it survives page refreshes within the browser tab but
* is automatically cleared when the tab is closed.
*/
import {
createContext,
useCallback,
useContext,
useMemo,
useState,
} from "react";
import * as authApi from "../api/auth";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface AuthState {
token: string | null;
expiresAt: string | null;
}
interface AuthContextValue {
/** `true` when a valid session token is held in state. */
isAuthenticated: boolean;
/**
* Authenticate with the master password.
* Throws an `ApiError` on failure.
*/
login: (password: string) => Promise<void>;
/** Revoke the current session and clear local state. */
logout: () => Promise<void>;
}
// ---------------------------------------------------------------------------
// Context
// ---------------------------------------------------------------------------
const AuthContext = createContext<AuthContextValue | null>(null);
const SESSION_KEY = "bangui_token";
const SESSION_EXPIRES_KEY = "bangui_expires_at";
// ---------------------------------------------------------------------------
// Provider
// ---------------------------------------------------------------------------
/**
* Wraps the application and provides authentication state to all children.
*
* Place this inside `<FluentProvider>` and `<BrowserRouter>` so all
* descendants can call `useAuth()`.
*/
export function AuthProvider({
children,
}: {
children: React.ReactNode;
}): JSX.Element {
const [auth, setAuth] = useState<AuthState>(() => ({
token: sessionStorage.getItem(SESSION_KEY),
expiresAt: sessionStorage.getItem(SESSION_EXPIRES_KEY),
}));
const isAuthenticated = useMemo<boolean>(() => {
if (!auth.token || !auth.expiresAt) return false;
// Treat the session as expired if the expiry time has passed.
return new Date(auth.expiresAt) > new Date();
}, [auth]);
const login = useCallback(async (password: string): Promise<void> => {
const response = await authApi.login(password);
sessionStorage.setItem(SESSION_KEY, response.token);
sessionStorage.setItem(SESSION_EXPIRES_KEY, response.expires_at);
setAuth({ token: response.token, expiresAt: response.expires_at });
}, []);
const logout = useCallback(async (): Promise<void> => {
try {
await authApi.logout();
} finally {
// Always clear local state even if the API call fails (e.g. expired session).
sessionStorage.removeItem(SESSION_KEY);
sessionStorage.removeItem(SESSION_EXPIRES_KEY);
setAuth({ token: null, expiresAt: null });
}
}, []);
const value = useMemo<AuthContextValue>(
() => ({ isAuthenticated, login, logout }),
[isAuthenticated, login, logout],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
/**
* Access authentication state and actions.
*
* Must be called inside a component rendered within `<AuthProvider>`.
*
* @throws {Error} When called outside of `<AuthProvider>`.
*/
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (ctx === null) {
throw new Error("useAuth must be used within <AuthProvider>.");
}
return ctx;
}