Files
2026-11-06 11:42:34 -05:00

50 lines
1.7 KiB
Python

"""The single shared dashboard password. Not user accounts: see README for
what to add before more than one family uses this."""
import secrets
import time
from typing import Annotated
from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from sqlalchemy.orm import Session
from ..config import get_settings
from ..db import get_db
from ..web import redirect, render
router = APIRouter(include_in_schema=False)
def _safe_next(url: str | None) -> str:
return url if url and url.startswith("/") and not url.startswith("//") else "/"
@router.get("/login", response_class=HTMLResponse)
def login_form(request: Request, db: Annotated[Session, Depends(get_db)], next: str = "/") -> Response:
if not get_settings().login_required:
return redirect("/")
return render(request, db, "login.html", next=_safe_next(next), error=None)
@router.post("/login", response_class=HTMLResponse)
def login(
request: Request,
db: Annotated[Session, Depends(get_db)],
password: Annotated[str, Form()],
next: Annotated[str, Form()] = "/",
) -> Response:
expected = get_settings().dashboard_password
if expected and secrets.compare_digest(password.encode(), expected.encode()):
request.session.clear()
request.session["auth"] = True
return redirect(_safe_next(next))
time.sleep(1) # slows down password guessing
return render(request, db, "login.html", status_code=401, next=_safe_next(next), error="That's not the password.")
@router.post("/logout")
def logout(request: Request) -> RedirectResponse:
request.session.clear()
return redirect("/login")