Files
mtusi2026lab3/src/api/routes/auth/auth.py
T

104 lines
4.2 KiB
Python

import base64
from fastapi import APIRouter, HTTPException, Request, Response, status
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
from src.services.session_cache import cache_session, invalidate_session
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 realm="messenger", charset="UTF-8"'},
)
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 realm="messenger", charset="UTF-8"'},
)
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 realm="messenger", charset="UTF-8"'},
)
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 realm="messenger", charset="UTF-8"'},
)
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)
await cache_session(token_hash, user.id)
return SessionCreateResponse(
token=raw_token,
expires_at=expires_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z",
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:%S.%f") + "Z",
),
)
@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",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
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",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
if 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",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
await invalidate_session(token_hash)
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",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
return Response(status_code=status.HTTP_204_NO_CONTENT)