Files
mtusi2026lab2/src/api/routes/auth/auth.py
T
2026-11-05 21:56:37 +03:00

89 lines
4.0 KiB
Python

from datetime import datetime, timezone
from typing import Annotated
import base64
from fastapi import APIRouter, HTTPException, Request, Response, status, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from src.api.dependencies import DbSession, CurrentUser
from src.pydantic_valid.session import SessionUser, SessionCreateResponse
from src.api.repositories.main_repo import Repository
from src.auth.password import verify_password
from src.auth.tokens import generate_token, hash_token, calculate_expires_at
from src.config import settings
router = APIRouter(prefix="/v1/auth")
@router.post("/sessions", response_model=SessionCreateResponse, status_code=status.HTTP_201_CREATED)
async def create_session(request: Request, session: DbSession):
repo = Repository(session)
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Basic "):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="missing or invalid Basic auth header",
headers={"WWW-Authenticate": "Basic"},
)
try:
encoded_credentials = auth_header[6:]
decoded = base64.b64decode(encoded_credentials).decode("utf-8")
username, password = decoded.split(":", 1)
except Exception:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid credentials format",
headers={"WWW-Authenticate": "Basic"})
user = await repo.users.get_by_username(username)
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid username or password",
headers={"WWW-Authenticate": "Basic"})
if not verify_password(password, user.password_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid username or password",
headers={"WWW-Authenticate": "Basic"})
raw_token, token_hash = generate_token()
expires_at = calculate_expires_at(settings.SESSION_TTL_SECONDS)
await repo.sessions.create(token_hash=token_hash, user_id=user.id, expires_at=expires_at)
return SessionCreateResponse(token=raw_token,
expires_at=expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
user=SessionUser(
id=str(user.id),
username=user.username,
display_name=user.display_name,
created_at=user.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
),
)
@router.delete("/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
async def delete_current_session(request: Request, session: DbSession, current_user: CurrentUser):
repo = Repository(session)
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid or missing Bearer token")
raw_token = auth_header[7:]
token_hash = hash_token(raw_token)
user_session = await repo.sessions.get_by_token_hash(token_hash)
if not user_session:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid token")
if not user_session.user_id == current_user.id:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="token in request doesn't align with current_user")
deleted = await repo.sessions.delete_by_token_hash(token_hash)
if not deleted:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid or expired token")
return Response(status_code=status.HTTP_204_NO_CONTENT)