ЛР 7: безопасность, mTLS и OpenBao на оценку 3

This commit is contained in:
2026-12-06 15:19:24 +03:00
parent 20afc2c790
commit 280c5a3300
101 changed files with 5950 additions and 63 deletions
+106
View File
@@ -0,0 +1,106 @@
from base64 import b64decode
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPAuthorizationCredentials
from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel, ConfigDict, field_serializer
from app.redis_client import redis_client
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
import uuid
from datetime import datetime
from app.database import async_session_maker
from app.models.user import User
from app.security import check_password, create_session, delete_session, bearer_scheme, session_key
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
class Utf8Basic(HTTPBasic):
async def __call__(self, request: Request) -> HTTPBasicCredentials:
scheme, parameter = get_authorization_scheme_param(request.headers.get("Authorization"))
if scheme.lower() == "basic":
try:
username, separator, password = b64decode(
parameter, validate=True
).decode("utf-8").partition(":")
if separator:
return HTTPBasicCredentials(username=username, password=password)
except ValueError:
pass
raise HTTPException(
status_code=401,
detail="Invalid Basic credentials",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
)
security = Utf8Basic(realm="messenger")
class UserResponse(BaseModel):
id: uuid.UUID
username: str
display_name: str
created_at: datetime
model_config = ConfigDict(from_attributes=True)
@field_serializer('created_at')
def serialize_dt(self, dt: datetime):
return dt.isoformat().replace("+00:00", "Z")
class SessionResponse(BaseModel):
token: str
token_type: str
expires_at: str
user: UserResponse
@field_serializer('expires_at')
def serialize_dt(self, dt_str: str):
if dt_str and dt_str.endswith("+00:00"):
return dt_str.replace("+00:00", "Z")
return dt_str
# Basic Auth в Bearer Token
@router.post("/sessions", status_code=201, response_model=SessionResponse)
async def login(credentials: HTTPBasicCredentials = Depends(security)):
async with async_session_maker() as session:
result = await session.execute(select(User).where(User.username == credentials.username))
user = result.scalar_one_or_none()
if not user or len(credentials.password) > 128 or not await check_password(credentials.password, user.password_hash):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
)
session_data = await create_session(user.id)
session_data["user"] = user
return session_data
@router.delete("/sessions/current", status_code=204)
async def logout(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
if not credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
token = credentials.credentials
user_id = await redis_client.get(session_key(token))
if not user_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
await delete_session(token)
return None