2025-10-18 05:50:43 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import aiosqlite
|
2025-10-19 09:24:23 +00:00
|
|
|
from fastapi import APIRouter, Depends, Request, Response
|
2025-10-18 05:50:43 +00:00
|
|
|
|
|
|
|
|
import persons
|
2025-10-19 09:24:23 +00:00
|
|
|
from api.deps import cookie_person, error_response, get_db
|
|
|
|
|
from common import ApiModel, ProblemDetails
|
2025-10-18 05:50:43 +00:00
|
|
|
|
|
|
|
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
|
|
|
|
|
|
|
|
|
|
2025-10-18 06:05:48 +00:00
|
|
|
class LoginBody(ApiModel):
|
|
|
|
|
username: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post(
|
|
|
|
|
"/login",
|
2025-10-19 09:24:23 +00:00
|
|
|
response_model=persons.Person,
|
2025-10-18 06:05:48 +00:00
|
|
|
operation_id="login",
|
|
|
|
|
summary="Login and set user_id cookie",
|
|
|
|
|
responses={
|
2025-10-19 09:24:23 +00:00
|
|
|
200: {"model": persons.Person, "description": "Successful Response"},
|
2025-10-19 13:12:16 +00:00
|
|
|
404: {
|
|
|
|
|
"model": ProblemDetails,
|
|
|
|
|
"description": "Person not found",
|
|
|
|
|
"content": {"application/problem+json": {}},
|
|
|
|
|
},
|
2025-10-18 06:05:48 +00:00
|
|
|
},
|
|
|
|
|
)
|
2025-10-19 09:24:23 +00:00
|
|
|
async def login(
|
|
|
|
|
request: Request,
|
|
|
|
|
data: LoginBody,
|
|
|
|
|
response: Response,
|
|
|
|
|
conn: aiosqlite.Connection = Depends(get_db),
|
2025-10-19 13:12:16 +00:00
|
|
|
) -> persons.Person | Response:
|
2025-10-18 06:05:48 +00:00
|
|
|
person = await persons.get_by_name(conn, data.username)
|
|
|
|
|
if not person:
|
|
|
|
|
return error_response(request, 404, "Person not found")
|
|
|
|
|
|
2025-10-19 09:24:23 +00:00
|
|
|
# When using response_model, return the Pydantic model and set the cookie on the Response
|
2025-10-18 06:05:48 +00:00
|
|
|
response.set_cookie(key="user_id", value=str(person.id))
|
2025-10-19 09:24:23 +00:00
|
|
|
return person
|
2025-10-18 05:50:43 +00:00
|
|
|
|
|
|
|
|
|
2025-10-18 06:05:48 +00:00
|
|
|
@router.post(
|
|
|
|
|
"/refresh",
|
2025-10-19 09:24:23 +00:00
|
|
|
response_model=persons.Person,
|
2025-10-18 06:05:48 +00:00
|
|
|
operation_id="refresh",
|
|
|
|
|
summary="Refresh current user from cookie",
|
|
|
|
|
)
|
2025-10-18 05:50:43 +00:00
|
|
|
async def current_user(user: persons.Person = Depends(cookie_person)) -> persons.Person:
|
2025-10-18 06:05:48 +00:00
|
|
|
return user
|