This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPAuthorizationCredentials
|
||||
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 verify_password, create_session, delete_session, bearer_scheme
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
security = HTTPBasic(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 not verify_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(f"session:{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
|
||||
Reference in New Issue
Block a user