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, /, *)
129 lines
3.7 KiB
Python
129 lines
3.7 KiB
Python
"""Authentication router.
|
|
|
|
``POST /api/auth/login`` — verify master password and issue a session.
|
|
``POST /api/auth/logout`` — revoke the current session.
|
|
|
|
The session token is returned both in the JSON body (for API-first
|
|
consumers) and as an ``HttpOnly`` cookie (for the browser SPA).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import structlog
|
|
from fastapi import APIRouter, HTTPException, Request, Response, status
|
|
|
|
from app.dependencies import DbDep, SettingsDep
|
|
from app.models.auth import LoginRequest, LoginResponse, LogoutResponse
|
|
from app.services import auth_service
|
|
|
|
log: structlog.stdlib.BoundLogger = structlog.get_logger()
|
|
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
|
|
_COOKIE_NAME = "bangui_session"
|
|
|
|
|
|
@router.post(
|
|
"/login",
|
|
response_model=LoginResponse,
|
|
summary="Authenticate with the master password",
|
|
)
|
|
async def login(
|
|
body: LoginRequest,
|
|
response: Response,
|
|
db: DbDep,
|
|
settings: SettingsDep,
|
|
) -> LoginResponse:
|
|
"""Verify the master password and return a session token.
|
|
|
|
On success the token is also set as an ``HttpOnly`` ``SameSite=Lax``
|
|
cookie so the browser SPA benefits from automatic credential handling.
|
|
|
|
Args:
|
|
body: Login request validated by Pydantic.
|
|
response: FastAPI response object used to set the cookie.
|
|
db: Injected aiosqlite connection.
|
|
settings: Application settings (used for session duration).
|
|
|
|
Returns:
|
|
:class:`~app.models.auth.LoginResponse` containing the token.
|
|
|
|
Raises:
|
|
HTTPException: 401 if the password is incorrect.
|
|
"""
|
|
try:
|
|
session = await auth_service.login(
|
|
db,
|
|
password=body.password,
|
|
session_duration_minutes=settings.session_duration_minutes,
|
|
)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail=str(exc),
|
|
) from exc
|
|
|
|
response.set_cookie(
|
|
key=_COOKIE_NAME,
|
|
value=session.token,
|
|
httponly=True,
|
|
samesite="lax",
|
|
secure=False, # Set to True in production behind HTTPS
|
|
max_age=settings.session_duration_minutes * 60,
|
|
)
|
|
return LoginResponse(token=session.token, expires_at=session.expires_at)
|
|
|
|
|
|
@router.post(
|
|
"/logout",
|
|
response_model=LogoutResponse,
|
|
summary="Revoke the current session",
|
|
)
|
|
async def logout(
|
|
request: Request,
|
|
response: Response,
|
|
db: DbDep,
|
|
) -> LogoutResponse:
|
|
"""Invalidate the active session.
|
|
|
|
The session token is read from the ``bangui_session`` cookie or the
|
|
``Authorization: Bearer`` header. If no token is present the request
|
|
is silently treated as a successful logout (idempotent).
|
|
|
|
Args:
|
|
request: FastAPI request (used to extract the token).
|
|
response: FastAPI response (used to clear the cookie).
|
|
db: Injected aiosqlite connection.
|
|
|
|
Returns:
|
|
:class:`~app.models.auth.LogoutResponse`.
|
|
"""
|
|
token = _extract_token(request)
|
|
if token:
|
|
await auth_service.logout(db, token)
|
|
response.delete_cookie(key=_COOKIE_NAME)
|
|
return LogoutResponse()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _extract_token(request: Request) -> str | None:
|
|
"""Extract the session token from cookie or Authorization header.
|
|
|
|
Args:
|
|
request: The incoming FastAPI request.
|
|
|
|
Returns:
|
|
The token string, or ``None`` if absent.
|
|
"""
|
|
token: str | None = request.cookies.get(_COOKIE_NAME)
|
|
if token:
|
|
return token
|
|
auth_header: str = request.headers.get("Authorization", "")
|
|
if auth_header.startswith("Bearer "):
|
|
return auth_header[len("Bearer "):]
|
|
return None
|