From d1a8c0394bb64d64cbf5fb81d330fa122a3864f2 Mon Sep 17 00:00:00 2001 From: Atelier77 Date: Thu, 5 Nov 2026 21:56:37 +0300 Subject: [PATCH] feat-(routes updating) --- src/api/dependencies.py | 47 ++++++++++----- src/api/repositories/chat_repo.py | 66 +++++++++++++++++++++ src/api/repositories/main_repo.py | 6 +- src/api/repositories/message_repo.py | 37 ++++++++++++ src/api/repositories/session_repo.py | 6 +- src/api/routes/auth/auth.py | 88 ++++++++++++++++++++++++++++ src/api/routes/chats/chat.py | 12 ++-- src/api/routes/messages/message.py | 82 +++++++++++++++----------- src/api/routes/users/user.py | 4 +- src/auth/password.py | 17 ++++++ src/auth/tokens.py | 17 ++++++ src/config.py | 2 +- src/main.py | 2 + src/models/messages.py | 6 +- src/pydantic_valid/session.py | 16 +++++ 15 files changed, 345 insertions(+), 63 deletions(-) create mode 100644 src/api/repositories/chat_repo.py create mode 100644 src/api/repositories/message_repo.py create mode 100644 src/api/routes/auth/auth.py create mode 100644 src/auth/tokens.py create mode 100644 src/pydantic_valid/session.py diff --git a/src/api/dependencies.py b/src/api/dependencies.py index 17303599..1cb68646 100644 --- a/src/api/dependencies.py +++ b/src/api/dependencies.py @@ -1,17 +1,24 @@ from datetime import datetime, timezone -from fastapi import Request, HTTPException, Depends +from fastapi import Request, HTTPException, Depends, status from fastapi.responses import JSONResponse from typing import Annotated +import uuid +from src.api.repositories.main_repo import Repository +from src.models.users import User +from src.auth.tokens import hash_token from sqlalchemy.ext.asyncio import AsyncSession from src.database import get_db -import uuid + + +type DbSession = Annotated[AsyncSession, Depends(get_db)] ##Dependency Injection def get_now_iso(): return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") -def get_current_user(request:Request) -> str: +async def get_current_user(request: Request, session: DbSession) -> User: + repo = Repository(session) path = request.url.path method = request.method @@ -20,16 +27,29 @@ def get_current_user(request:Request) -> str: if path == "/api/v1/users" and method == "POST": return None - user_id = request.headers.get("X-User-Id") - if not user_id: - raise HTTPException(status_code=401, detail="missing X-User-Id") + 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="missing or invalid Bearer token", + headers={"WWW-Authenticate": "Bearer"}, + ) - try: - user_id = uuid.UUID(user_id) - except ValueError: - raise HTTPException(status_code=401, detail="non-valid X-User-Id") - - return str(user_id) ##repo.users.user_db.get(user_id) + raw_token = auth_header[7:] + token_hash = hash_token(raw_token) + + current_session = await repo.sessions.get_by_token_hash(token_hash) + if not current_session: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid or expired token", + headers={"WWW-Authenticate": "Bearer"}) + + user = await repo.users.get_by_id(current_session.user_id) + if not user: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, + deatil="user not found", + headers={"WWW-Authenticate": "Bearer"}) + return user def generate_id() -> str: @@ -41,5 +61,4 @@ def create_error_response(message: str, code: str, status_code: int, request_id: return JSONResponse(status_code=status_code, content=body, headers={"X-Request-Id": request_id}) -type DbSession = Annotated[AsyncSession, Depends(get_db)] ##Dependency Injection -type CurrentUser = Annotated[str, Depends(get_current_user)] \ No newline at end of file +type CurrentUser = Annotated[User, Depends(get_current_user)] \ No newline at end of file diff --git a/src/api/repositories/chat_repo.py b/src/api/repositories/chat_repo.py new file mode 100644 index 00000000..eb6b2bef --- /dev/null +++ b/src/api/repositories/chat_repo.py @@ -0,0 +1,66 @@ +import uuid +from datetime import datetime +from typing import Optional, List + +from sqlalchemy import select, delete +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import selectinload + +from src.models.chats import Chat, ChatMember +from src.api.repositories.core import DatabaseManager + + +class ChatRepo(DatabaseManager): + def __init__(self, session: AsyncSession, model: Chat): + super().__init__(session, model) + + + async def create_with_members(self, title: str, member_ids: List[uuid.UUID]) -> Optional[Chat]: + try: + chat = Chat(title=title) + self.session.add(chat) + await self.session.flush() + + for user_id in member_ids: + member = ChatMember(chat_id=chat.id, user_id=user_id) + self.session.add(member) + + await self.session.commit() + + await self.session.refresh(chat) + + result = await self.session.execute(select(Chat).options(selectinload(Chat.members)).where(Chat.id == chat.id)) + return result.scalar_one() + + except Exception as e: + await self.session.rollback() + raise + + + async def get_by_id_with_members(self, chat_id: uuid.UUID) -> Optional[Chat]: + result = await self.session.execute(select(Chat).options(selectinload(Chat.members)).where(Chat.id == chat_id)) + return result.scalar_one_or_none() + + + async def get_user_chats(self, user_id: uuid.UUID) -> List[Chat]: + result = await self.session.execute(select(Chat).join(ChatMember, Chat.id == ChatMember.chat_id).options(selectinload(Chat.members)).where(ChatMember.user_id == user_id).order_by(Chat.created_at.asc(), Chat.id.asc())) + return list(result.scalars().all()) + + + async def is_user_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool: + result = await self.session.execute(select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id,)) + return result.scalar_one_or_none() is not None + + + async def delete_by_id(self, chat_id: uuid.UUID) -> bool: + try: + chat = await self.get_by_id_with_members(chat_id) + if chat: + await self.session.delete(chat) + await self.session.commit() + return True + return False + except Exception as e: + await self.session.rollback() + raise + \ No newline at end of file diff --git a/src/api/repositories/main_repo.py b/src/api/repositories/main_repo.py index 851cfd00..66386369 100644 --- a/src/api/repositories/main_repo.py +++ b/src/api/repositories/main_repo.py @@ -1,9 +1,13 @@ from src.api.repositories.user_repo import UserRepo from src.api.repositories.session_repo import SessionRepo +from src.api.repositories.chat_repo import ChatRepo +from src.api.repositories.message_repo import MessageRepo from sqlalchemy.ext.asyncio import AsyncSession class Repository(): def __init__(self, session: AsyncSession): self.users = UserRepo(session) - self.sessions = SessionRepo(session) \ No newline at end of file + self.sessions = SessionRepo(session) + self.chats = ChatRepo(session) + self.messages = MessageRepo(session) diff --git a/src/api/repositories/message_repo.py b/src/api/repositories/message_repo.py new file mode 100644 index 00000000..6d188d8f --- /dev/null +++ b/src/api/repositories/message_repo.py @@ -0,0 +1,37 @@ +import uuid +from datetime import datetime +from typing import Optional, List, Tuple + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from src.models.messages import Message +from src.api.repositories.core import DatabaseManager + + +class MessageRepo(DatabaseManager): + def __init__(self, session: AsyncSession, model: Message): + super().__init__(session, model) + + async def create(self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str) -> Message: + return await super().create(chat_id=chat_id, sender_id=sender_id, text=text) + + async def get_chat_messages(self, chat_id: uuid.UUID, limit: int = 50, cursor_created_at: Optional[datetime] = None, cursor_msg_id: Optional[uuid.UUID] = None) -> Tuple[List[Message], bool]: + query = (select(Message).where(Message.chat_id == chat_id).order_by(Message.created_at.asc(), Message.id.asc()) + ) + + if cursor_created_at is not None and cursor_msg_id is not None: + query = query.where((Message.created_at > cursor_created_at) | + ((Message.created_at == cursor_created_at) & (Message.id > cursor_msg_id)) + ) + + query = query.limit(limit + 1) + + result = await self.session.execute(query) + messages = list(result.scalars().all()) + + has_more = len(messages) > limit + if has_more: + messages = messages[:limit] + + return messages, has_more \ No newline at end of file diff --git a/src/api/repositories/session_repo.py b/src/api/repositories/session_repo.py index 8034b4ef..275c1320 100644 --- a/src/api/repositories/session_repo.py +++ b/src/api/repositories/session_repo.py @@ -17,6 +17,10 @@ class SessionRepo(DatabaseManager): result = await super().get_by_field("token_hash", token_hash) return result - async def delete_by_token_hash(self, token_hash: str) -> bool: + async def get_by_user_id(self, user_id: str) -> Optional[Session]: + result = await super().get_by_field("user_id", user_id) + return result + + async def delete_by_user_id(self, token_hash: str) -> bool: result = await super().delete_by_field("token_hash", token_hash) return result \ No newline at end of file diff --git a/src/api/routes/auth/auth.py b/src/api/routes/auth/auth.py new file mode 100644 index 00000000..3e2f16df --- /dev/null +++ b/src/api/routes/auth/auth.py @@ -0,0 +1,88 @@ +from datetime import datetime, timezone +from typing import Annotated +import base64 +from fastapi import APIRouter, HTTPException, Request, Response, status, Depends +from sqlalchemy.ext.asyncio import AsyncSession +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 + + + +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"}, + ) + 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"}) + + 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"}) + 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"}) + 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) + + return SessionCreateResponse(token=raw_token, + expires_at=expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"), + 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:%SZ"), + ), + ) + + +@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") + + 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") + + if not 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") + + 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") + + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/src/api/routes/chats/chat.py b/src/api/routes/chats/chat.py index 68f756c8..168732e3 100644 --- a/src/api/routes/chats/chat.py +++ b/src/api/routes/chats/chat.py @@ -10,8 +10,8 @@ router = APIRouter() @router.post("/v1/chats", response_model=Chat, status_code=201) -async def chat(current_user_id: CurrentUser, repo: Repo, chat_in:CreateChat) -> Chat: - if current_user_id not in chat_in.member_ids: +async def chat(current_user: CurrentUser, repo: Repo, chat_in:CreateChat) -> Chat: + if current_user.id not in chat_in.member_ids: raise HTTPException(statuc_code=400, detail="Creator of chat should be in chat member list") for usr in chat_in.member_ids: if usr not in repo.users.users_db: @@ -27,9 +27,9 @@ async def chat(current_user_id: CurrentUser, repo: Repo, chat_in:CreateChat) -> @router.get("/v1/chats", response_model=PageResponse) -async def list_chats(current_user_id: CurrentUser, repo: Repo, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)) -> PageResponse: +async def list_chats(current_user: CurrentUser, repo: Repo, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)) -> PageResponse: accessible_chats = [c for c in repo.chats.chats_db.values() - if current_user_id in c["member_ids"]] + if current_user.id in c["member_ids"]] accessible_chats.sort(key=lambda x: (x["created_at"], x["id"])) start_idx = 0 @@ -48,10 +48,10 @@ async def list_chats(current_user_id: CurrentUser, repo: Repo, limit: int = Quer @router.get("/v1/chats/{chat_id}", response_model=Chat) -async def get_chat(current_user_id: CurrentUser, repo: Repo, chat_id: UUID) -> Chat: +async def get_chat(current_user: CurrentUser, repo: Repo, chat_id: UUID) -> Chat: chat = repo.chats.chats_db.get(str(chat_id)) if not chat: raise HTTPException(status_code=404, detail="Chat not found") - if current_user_id not in chat["member_ids"]: + if current_user.id not in chat["member_ids"]: raise HTTPException(status_code=404, detail="Chat not found") return chat diff --git a/src/api/routes/messages/message.py b/src/api/routes/messages/message.py index 21e2b93d..cb60e348 100644 --- a/src/api/routes/messages/message.py +++ b/src/api/routes/messages/message.py @@ -1,10 +1,12 @@ import base64 -from fastapi import HTTPException, APIRouter, Query +from fastapi import HTTPException, APIRouter, Query, status from typing import Optional from uuid import UUID from src.pydantic_valid.message import Message, CreateMessage from src.pydantic_valid.page_response import PageResponse -from src.api.dependencies import Repo, CurrentUser, generate_id, get_now_iso +from src.api.dependencies import DbSession, CurrentUser, generate_id, get_now_iso +from src.api.repositories.main_repo import Repository +import datetime router = APIRouter() @@ -33,46 +35,56 @@ def _decode_msg_cursor(scope_chat_id: str, cursor: str) -> tuple[str, str]: @router.post("/v1/chats/{chat_id}/messages", response_model=Message, status_code=201) -async def send_message(chat_id: UUID, msg_in: CreateMessage, repo: Repo, crnt_usr_id: CurrentUser): - chat = repo.chats.chats_db.get(str(chat_id)) - if not chat: - raise HTTPException(status_code=404, detail="Chat not found") - if crnt_usr_id not in chat["member_ids"]: - raise HTTPException(status_code=404, detail="Not found") - - msg_data = Message( - id = generate_id(), - chat_id = str(chat_id), - sender_id = crnt_usr_id, - text = msg_in.text, - created_at = get_now_iso() +async def send_message(chat_id: UUID, msg_in: CreateMessage, session: DbSession, current_user: CurrentUser): + repo = Repository(session) + + if not await repo.chats.is_user_member(chat_id, current_user.id): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, + detail="chat not found") + + message = await repo.messages.create(chat_id=chat_id, + sender_id=current_user.id, + text=msg_in.text) + + return Message( + id=str(message.id), + chat_id=str(message.chat_id), + sender_id=str(message.sender_id), + text=message.text, + created_at=message.created_at.strftime("%Y-%m-%dT%H:%M:%SZ") ) - if await repo.create_message(msg_data): - return msg_data - else: - raise HTTPException(status_code=404, detail="Chat not found") @router.get("/v1/chats/{chat_id}/messages", response_model=PageResponse, status_code=200) -async def list_messages(repo: Repo, crnt_usr_id: CurrentUser, chat_id: UUID, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)): - chat = repo.chats.chats_db.get(str(chat_id)) +async def list_messages(session: DbSession, current_user: CurrentUser, chat_id: UUID, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)): + repo = Repository(session) + + chat = await repo.chats.get_by_id_with_members(chat_id) if not chat: - raise HTTPException(status_code=404, detail="Chat not found") - if crnt_usr_id not in chat["member_ids"]: - raise HTTPException(status_code=404, detail="Not found") - # all_msgs = repo.messages.message_db.get(str(chat_id), []) - # all_msgs.sort(key=lambda x: (x["created_at"], x["id"])) - all_msgs = repo.messages.get_sorted_messages(str(chat_id)) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, + detail="chat not found") + member_ids = {str(m.user_id) for m in chat.members} + + if str(current_user.id) not in member_ids: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, + detail="chat not found") + cursor_created_at = None + cursor_msg_id = None if cursor: - cursor_created_at, cursor_message_id = _decode_msg_cursor(str(chat_id), cursor) - all_msgs = [m for m in all_msgs if (m["created_at"], m["id"]) > (cursor_created_at, cursor_message_id)] + created_at_str, msg_id_str = _decode_msg_cursor(str(chat_id), cursor) + cursor_created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00")) + cursor_msg_id = UUID(msg_id_str) - page_items = all_msgs[:limit] + messages, has_more = await repo.messages.get_chat_messages(chat_id=chat_id, limit=limit, cursor_created_at=cursor_created_at, cursor_msg_id=cursor_msg_id) next_cursor = None - if len(all_msgs) > limit and page_items: - last = page_items[-1] - next_cursor = _encode_msg_cursor(str(chat_id), last["created_at"], last["id"]) - - return PageResponse(items=page_items, next_cursor=next_cursor) \ No newline at end of file + if has_more and messages: + last = messages[-1] + next_cursor = _encode_msg_cursor(chat_id=str(chat_id), created_at=last.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"), msg_id=str(last.id)) + + return PageResponse( + items=[Message(id=str(msg.id), chat_id=str(msg.chat_id), sender_id=str(msg.sender_id), text=msg.text, created_at=msg.created_at.strftime("%Y-%m-%dT%H:%M:%SZ")) + for msg in messages], + next_cursor=next_cursor, + ) diff --git a/src/api/routes/users/user.py b/src/api/routes/users/user.py index 5e9b1769..a608eb09 100644 --- a/src/api/routes/users/user.py +++ b/src/api/routes/users/user.py @@ -36,9 +36,9 @@ async def register_user(body: CreateUser, session: DbSession) -> User: @router.get("/users/me", response_model=UserSchema, status_code=200) -async def get_me(session: DbSession, current_user_id: CurrentUser) -> User: +async def get_me(session: DbSession, current_user: CurrentUser) -> User: repo = Repository(session) - user = await repo.get_user(current_user_id) + user = await repo.get_user(current_user.id) if not user: raise HTTPException(status_code=401, detail="Unknown user") return user diff --git a/src/auth/password.py b/src/auth/password.py index e69de29b..878e8e47 100644 --- a/src/auth/password.py +++ b/src/auth/password.py @@ -0,0 +1,17 @@ +from argon2 import PasswordHasher +from argon2.exceptions import VerifyMismatchError + + +ph = PasswordHasher() + + +def hash_password(password: str) -> str: + return ph.hash(password) + + +def verify_password(password: str, _hash: str) -> bool: + try: + ph.verify(_hash, password) + return True + except VerifyMismatchError: + return False \ No newline at end of file diff --git a/src/auth/tokens.py b/src/auth/tokens.py new file mode 100644 index 00000000..2843b239 --- /dev/null +++ b/src/auth/tokens.py @@ -0,0 +1,17 @@ +import secrets +import hashlib +from datetime import datetime, timezone, timedelta + + +def generate_token() -> tuple[str, str]: + raw_token = secrets.token_urlsafe(32) + token_hash = hashlib.sha256(raw_token.encode()).hexdigest() + return raw_token, token_hash + + +def hash_token(raw_token: str) -> str: + return hashlib.sha256(raw_token.encode()).hexdigest() + + +def calculate_expires_at(ttl_seconds: int) -> datetime: + return datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds) diff --git a/src/config.py b/src/config.py index 1703d193..7f5d7cb0 100644 --- a/src/config.py +++ b/src/config.py @@ -7,7 +7,7 @@ class Settings(BaseSettings): APP_NAME: str = "MTUSI Messenger" APP_DEBUG: bool = False - DATABASE_URL: str = Field(..., description="Строка подключения к PostgreSQL") + DATABASE_URL: str = Field(..., description="Строка подключения к PostgreSQL. docker_compose перезапишет поле через .env") SESSION_TTL_SECONDS: int = 3600 DB_POOL_SIZE: int = 5 diff --git a/src/main.py b/src/main.py index 66ffb069..05cfbc86 100644 --- a/src/main.py +++ b/src/main.py @@ -7,6 +7,7 @@ from src.api.routes.health import health from src.api.routes.users import user from src.api.routes.chats import chat from src.api.routes.messages import message +from src.api.routes.auth import auth from src.lifespan import lifespan application = FastAPI(title="MTUSI Messenger", version="1.0.0", lifespan=lifespan) @@ -76,3 +77,4 @@ application.include_router(health.router, prefix="/health", tags=["Health"]) application.include_router(user.router, prefix="/api", tags=["Users"]) application.include_router(chat.router, prefix="/api", tags=["Chats"]) application.include_router(message.router, prefix="/api", tags=["Messages"]) +application.include_router(auth.router, prefix="/api", tags=["Auth"]) diff --git a/src/models/messages.py b/src/models/messages.py index ce7e9072..eee3e30b 100644 --- a/src/models/messages.py +++ b/src/models/messages.py @@ -7,9 +7,9 @@ from datetime import datetime from src.database import Base -if TYPING_CHECKING: - from src.models.users import User - from src.models.chats import Chat +# if TYPING_CHECKING: +# from src.models.users import User +# from src.models.chats import Chat class Message(Base): diff --git a/src/pydantic_valid/session.py b/src/pydantic_valid/session.py new file mode 100644 index 00000000..3355f22c --- /dev/null +++ b/src/pydantic_valid/session.py @@ -0,0 +1,16 @@ +from pydantic import Field, BaseModel, ConfigDict + + +class SessionUser(BaseModel): + id: str + username: str + display_name: str + created_at: str + + +class SessionCreateResponse(BaseModel): + model_config = ConfigDict(extra="forbid") + token: str + token_type: str = Field(default="Bearer", pattern="^Bearer$") + expires_at: str + user: SessionUser