50 lines
1.5 KiB
Python
50 lines
1.5 KiB
Python
import secrets
|
|
|
|
from fastapi import APIRouter, Form, Request, status
|
|
from fastapi.responses import FileResponse, RedirectResponse
|
|
|
|
from app.analytics import capture
|
|
from app.auth import create_session_token, is_authenticated
|
|
from app.config import AUTH_PASSWORD, COOKIE_SECURE, SESSION_MAX_AGE, WEB_DIR
|
|
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
|
|
@router.get("/")
|
|
def index(request: Request):
|
|
if not is_authenticated(request):
|
|
return RedirectResponse("/login", status_code=status.HTTP_303_SEE_OTHER)
|
|
return FileResponse(WEB_DIR / "index.html")
|
|
|
|
|
|
@router.get("/login")
|
|
def login_page(request: Request):
|
|
if is_authenticated(request):
|
|
return RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER)
|
|
return FileResponse(WEB_DIR / "login.html")
|
|
|
|
|
|
@router.post("/login")
|
|
def login(password: str = Form(...)):
|
|
if not secrets.compare_digest(password, AUTH_PASSWORD):
|
|
return RedirectResponse("/login?error=1", status_code=status.HTTP_303_SEE_OTHER)
|
|
|
|
token, session_id = create_session_token()
|
|
capture(session_id, "user_logged_in")
|
|
resp = RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER)
|
|
resp.set_cookie(
|
|
"session",
|
|
token,
|
|
httponly=True,
|
|
samesite="lax",
|
|
secure=COOKIE_SECURE,
|
|
max_age=SESSION_MAX_AGE,
|
|
)
|
|
return resp
|
|
|
|
|
|
@router.get("/logout")
|
|
def logout():
|
|
resp = RedirectResponse("/login", status_code=status.HTTP_303_SEE_OTHER)
|
|
resp.delete_cookie("session")
|
|
return resp
|