добавлена аутентификация и сессии в redis

This commit is contained in:
2026-10-07 23:18:23 +03:00
parent 789bea2f1e
commit 7f8bcfd234
9 changed files with 389 additions and 114 deletions
+142 -110
View File
@@ -1,18 +1,80 @@
from uuid import UUID, uuid4
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from fastapi import Depends, FastAPI, Header, Request
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.security import (
HTTPAuthorizationCredentials,
HTTPBasic,
HTTPBasicCredentials,
HTTPBearer,
)
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.exceptions import HTTPException as StarletteHTTPException
from src.database import get_db_session
from src.errors import APIError
from src.models import Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Message, MessagePage, User
from src.store import Store, UsernameAlreadyExistsError
from src.models import CreateUser, SessionResponse, User
from src.repositories import (
create_user as create_user_in_db,
get_user_by_id,
get_user_credentials_by_username,
)
from src.security import verify_password
from src.sessions import (
create_session,
delete_session,
get_session_user_id,
)
app = FastAPI()
store = Store()
basic_security = HTTPBasic(auto_error=False)
bearer_security = HTTPBearer(auto_error=False)
async def get_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security),
session: AsyncSession = Depends(get_db_session),
) -> User:
if credentials is None or credentials.scheme.lower() != "bearer":
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": "Bearer",
},
)
user_id = await get_session_user_id(credentials.credentials)
if user_id is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": "Bearer",
},
)
user = await get_user_by_id(session, user_id)
if user is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": "Bearer",
},
)
return user
@app.middleware("http")
@@ -80,6 +142,7 @@ async def api_error_handler(request: Request, exc: APIError):
"request_id": request_id,
}
},
headers=exc.headers,
)
@@ -129,37 +192,6 @@ async def unexpected_exception_handler(
)
async def get_current_user(
x_user_id: str | None = Header(default=None),
) -> User:
if x_user_id is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
)
try:
user_id = UUID(x_user_id)
except ValueError:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
)
user = await store.get_user(user_id)
if user is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
)
return user
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@@ -171,15 +203,20 @@ async def health_ready():
@app.post("/api/v1/users", response_model=User, status_code=201)
async def create_user(data: CreateUser):
async def create_user(
data: CreateUser,
session: AsyncSession = Depends(get_db_session),
):
try:
return await store.create_user(data)
except UsernameAlreadyExistsError:
async with session.begin():
return await create_user_in_db(session, data)
except IntegrityError as exc:
raise APIError(
status_code=409,
code="conflict",
message="Username already exists",
)
) from exc
@app.get("/api/v1/users/me", response_model=User)
@@ -189,83 +226,78 @@ async def get_me(
return current_user
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(
data: CreateChat,
current_user: User = Depends(get_current_user),
):
return await store.create_chat(
data=data,
current_user_id=current_user.id,
)
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
async def get_chat(
chat_id: UUID,
current_user: User = Depends(get_current_user),
):
return await store.get_chat(
chat_id=chat_id,
current_user_id=current_user.id,
)
@app.get("/api/v1/chats", response_model=ChatPage)
async def get_chats(
limit: int = 50,
current_user: User = Depends(get_current_user),
):
if limit < 1 or limit > 100:
raise APIError(
status_code=400,
code="invalid_request",
message="Limit must be between 1 and 100",
)
return await store.get_chats(
current_user_id=current_user.id,
limit=limit,
)
@app.post(
"/api/v1/chats/{chat_id}/messages",
response_model=Message,
"/api/v1/auth/sessions",
response_model=SessionResponse,
status_code=201,
)
async def create_message(
chat_id: UUID,
data: CreateMessage,
current_user: User = Depends(get_current_user),
async def create_auth_session(
credentials: HTTPBasicCredentials | None = Depends(basic_security),
session: AsyncSession = Depends(get_db_session),
):
return await store.create_message(
chat_id=chat_id,
current_user_id=current_user.id,
data=data,
if credentials is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": 'Basic realm="messenger"',
},
)
user_credentials = await get_user_credentials_by_username(
session,
credentials.username,
)
if user_credentials is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": 'Basic realm="messenger"',
},
)
if not verify_password(
user_credentials.password_hash,
credentials.password,
):
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": 'Basic realm="messenger"',
},
)
user = User(
id=user_credentials.id,
username=user_credentials.username,
display_name=user_credentials.display_name,
created_at=user_credentials.created_at,
)
token, ttl = await create_session(user.id)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl)
return SessionResponse(
token=token,
token_type="bearer",
expires_at=expires_at,
user=user,
)
@app.get(
"/api/v1/chats/{chat_id}/messages",
response_model=MessagePage,
@app.delete(
"/api/v1/auth/sessions/current",
status_code=204,
)
async def get_messages(
chat_id: UUID,
limit: int = 50,
cursor: str | None = None,
async def delete_current_session(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security),
current_user: User = Depends(get_current_user),
):
if limit < 1 or limit > 100:
raise APIError(
status_code=400,
code="invalid_request",
message="Limit must be between 1 and 100",
)
return await store.get_messages(
chat_id=chat_id,
current_user_id=current_user.id,
limit=limit,
cursor=cursor,
)
await delete_session(credentials.credentials)