forked from mtusi2026/mtusi2026lab3
- X-Instance-Id в каждом ответе; обязательный Idempotency-Key, таблица idempotency_keys (миграция 0002, одна транзакция, конкурентные повторы через уникальный индекс) - graceful shutdown: SIGTERM -> ready=503 -> drain 3 с -> закрытие порта - compose: lb (HAProxy) + api x2 без портов + разовый migrate + postgres, лимиты CPU/RAM - хуки stop-one/restart/restore-replicas, scripts/experiments.py (failover, idempotency, rolling) - свои тесты: 44 (13 новых); evidence: smoke, pytest, persistence, failover, эксперименты
67 lines
3.1 KiB
Python
67 lines
3.1 KiB
Python
import base64
|
|
import binascii
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Response, Security
|
|
from sqlalchemy.orm import Session
|
|
|
|
from api.dependencies import basic_scheme, get_current_session, require_empty_body
|
|
from core.config import settings
|
|
from core.db import get_db
|
|
from core.logger import logger
|
|
from database_functions.sessions_functions import create_session, delete_session
|
|
from database_functions.users_functions import get_user_by_username
|
|
from models import AuthSession
|
|
from schemas.auth_schemas import SessionResponse
|
|
from schemas.users_schemas import UserResponse
|
|
from utils.security import create_access_token, token_hash, verify_password
|
|
|
|
roter = APIRouter(
|
|
prefix=settings.api.prefix + settings.api.v1.prefix + settings.api.v1.auth,
|
|
tags=["auth"],
|
|
)
|
|
|
|
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
|
|
|
|
|
def invalid_credentials() -> HTTPException:
|
|
# Один ответ и для неизвестного username, и для неверного пароля.
|
|
return HTTPException(status_code=401, detail="Неверное имя пользователя или пароль", headers=BASIC_CHALLENGE)
|
|
|
|
|
|
def parse_basic(authorization: str | None) -> tuple[str, str]:
|
|
scheme, _, encoded = (authorization or "").partition(" ")
|
|
if scheme.lower() != "basic" or not encoded:
|
|
raise invalid_credentials()
|
|
try:
|
|
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
|
|
except (binascii.Error, UnicodeDecodeError):
|
|
raise invalid_credentials()
|
|
# По первому двоеточию: в пароле двоеточие допустимо.
|
|
username, separator, password = decoded.partition(":")
|
|
if not separator:
|
|
raise invalid_credentials()
|
|
return username, password
|
|
|
|
|
|
# Тело проверяется до пароля: зависимости маршрута выполняются раньше параметров.
|
|
@roter.post("/sessions", status_code=201, response_model=SessionResponse, dependencies=[Depends(require_empty_body)])
|
|
def create_session_api(authorization: str | None = Security(basic_scheme), db: Session = Depends(get_db)):
|
|
username, password = parse_basic(authorization)
|
|
|
|
user = get_user_by_username(db, username)
|
|
if not verify_password(user.password_hash if user else None, password):
|
|
logger.info("Неудачная попытка входа")
|
|
raise invalid_credentials()
|
|
|
|
token, issued_at, expires_at = create_access_token(user.id)
|
|
create_session(db, token_hash(token), user.id, created_at=issued_at, expires_at=expires_at)
|
|
logger.info(f"Вход выполнен: user_id={user.id}")
|
|
return SessionResponse(token=token, expires_at=expires_at, user=UserResponse.model_validate(user))
|
|
|
|
|
|
@roter.delete("/sessions/current", status_code=204)
|
|
def delete_session_api(auth_session: AuthSession = Depends(get_current_session), db: Session = Depends(get_db)):
|
|
delete_session(db, auth_session.token_hash)
|
|
logger.info(f"Выход выполнен: user_id={auth_session.user_id}")
|
|
return Response(status_code=204)
|