This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
|
||||
DATABASE_URL = os.getenv(
|
||||
"DATABASE_URL",
|
||||
"postgresql+asyncpg://messenger:messenger_password@db:5432/messenger_db",
|
||||
)
|
||||
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
CODE_MAP = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
500: "internal_error",
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
from app.config import DATABASE_URL
|
||||
|
||||
engine = create_async_engine( #
|
||||
DATABASE_URL,
|
||||
pool_size=5,
|
||||
max_overflow=10,
|
||||
pool_timeout=30,
|
||||
pool_recycle=1800,
|
||||
echo=False,
|
||||
)
|
||||
|
||||
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
||||
@@ -0,0 +1,6 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.database import async_session_maker
|
||||
|
||||
async def get_session():
|
||||
async with async_session_maker() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,34 @@
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from app.config import CODE_MAP
|
||||
|
||||
|
||||
def error_response(request: Request, status_code: int, code: str, message: str, extra_headers: dict = None):
|
||||
request_id = getattr(request.state, "request_id", "unknown")
|
||||
|
||||
|
||||
headers = {"X-Request-Id": request_id}
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
code = CODE_MAP.get(exc.status_code, "internal_error")
|
||||
return error_response(request, exc.status_code, code, str(exc.detail), extra_headers=exc.headers)
|
||||
|
||||
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "Ошибка валидации данных")
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.middleware import RequestIdMiddleware
|
||||
from app.exceptions import http_exception_handler, validation_exception_handler
|
||||
from app.routers import health, users, chats, messages, auth
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger",
|
||||
version="1.1.0",
|
||||
)
|
||||
|
||||
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
|
||||
app.add_exception_handler(HTTPException, http_exception_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(auth.router)
|
||||
@@ -0,0 +1,11 @@
|
||||
import uuid as uuid_lib
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request, call_next):
|
||||
request_id = str(uuid_lib.uuid4())
|
||||
request.state.request_id = request_id
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
@@ -0,0 +1,4 @@
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
@@ -0,0 +1,35 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import String, DateTime, ForeignKey, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||
)
|
||||
title: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("chats.id", ondelete="CASCADE"),
|
||||
primary_key=True,
|
||||
)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("users.id", ondelete="CASCADE"),
|
||||
primary_key=True,
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Text, DateTime, ForeignKey, Index, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||
)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("chats.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
sender_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("users.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
text: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import String, DateTime, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||
)
|
||||
username: Mapped[str] = mapped_column(
|
||||
String(32), unique=True, nullable=False, index=True
|
||||
)
|
||||
display_name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
def paginate(items: list, limit: int, cursor: str | None):
|
||||
start = 0
|
||||
if cursor is not None:
|
||||
try:
|
||||
start = int(cursor)
|
||||
except ValueError:
|
||||
start = 0
|
||||
|
||||
if start < 0:
|
||||
start = 0
|
||||
|
||||
page = items[start : start + limit]
|
||||
next_index = start + limit
|
||||
|
||||
if next_index < len(items):
|
||||
next_cursor = str(next_index)
|
||||
else:
|
||||
next_cursor = None
|
||||
|
||||
return page, next_cursor
|
||||
@@ -0,0 +1,4 @@
|
||||
import redis.asyncio as redis
|
||||
from app.config import REDIS_URL
|
||||
|
||||
redis_client = redis.from_url(REDIS_URL, decode_responses=True)
|
||||
@@ -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
|
||||
@@ -0,0 +1,139 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field, field_validator, ConfigDict, field_serializer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.models.chat import Chat, ChatMember
|
||||
from app.models.user import User
|
||||
from app.security import get_current_user
|
||||
from app.dependencies import get_session
|
||||
from app.pagination import paginate
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def unique_members(cls, v):
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("member_ids должны быть уникальными")
|
||||
return v
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
title: str
|
||||
member_ids: list[uuid.UUID]
|
||||
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")
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_chat(
|
||||
payload: CreateChat,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if str(user.id) not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="Пользователь должен быть участником чата")
|
||||
|
||||
for member_id in payload.member_ids:
|
||||
result = await session.execute(select(User).where(User.id == member_id))
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=400, detail=f"несуществующий пользователь: {member_id}")
|
||||
|
||||
chat = Chat(title=payload.title)
|
||||
session.add(chat)
|
||||
await session.flush()
|
||||
|
||||
for member_id in payload.member_ids:
|
||||
session.add(ChatMember(chat_id=chat.id, user_id=member_id))
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(chat)
|
||||
|
||||
return {
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": payload.member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{chat_id}")
|
||||
async def get_chat(
|
||||
chat_id: str,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
result = await session.execute(select(Chat).where(Chat.id == chat_id))
|
||||
chat = result.scalar_one_or_none()
|
||||
|
||||
if not chat:
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user.id)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))
|
||||
member_ids = []
|
||||
for row in result.all():
|
||||
user_id = row[0]
|
||||
member_ids.append(str(user_id))
|
||||
|
||||
return {
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_chats(
|
||||
limit: int = 20,
|
||||
cursor: str | None = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100")
|
||||
|
||||
result = await session.execute(
|
||||
select(Chat)
|
||||
.join(ChatMember, Chat.id == ChatMember.chat_id)
|
||||
.where(ChatMember.user_id == user.id)
|
||||
.order_by(Chat.created_at, Chat.id)
|
||||
)
|
||||
chats = result.scalars().all()
|
||||
|
||||
my_chats = []
|
||||
for chat in chats:
|
||||
result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))
|
||||
member_ids = []
|
||||
for row in result.all():
|
||||
user_id = row[0]
|
||||
member_ids.append(str(user_id))
|
||||
|
||||
my_chats.append({
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
})
|
||||
|
||||
page, next_cursor = paginate(my_chats, limit, cursor)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,23 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
def ready():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
def home():
|
||||
return {
|
||||
"service": "MTUSI Messenger",
|
||||
"version": "1.1.0",
|
||||
"docs": "/docs",
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field, ConfigDict, field_serializer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.models.message import Message
|
||||
from app.models.chat import Chat, ChatMember
|
||||
from app.models.user import User
|
||||
from app.security import get_current_user
|
||||
from app.dependencies import get_session
|
||||
from app.pagination import paginate
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
text: 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")
|
||||
|
||||
|
||||
async def check_chat_access(chat_id: str, user_id: uuid.UUID, session: AsyncSession):
|
||||
chat = await session.get(Chat, chat_id)
|
||||
if not chat:
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user_id)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
return chat
|
||||
|
||||
|
||||
@router.post("", status_code=201, response_model=MessageResponse)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
payload: CreateMessage,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
await check_chat_access(chat_id, user.id, session)
|
||||
|
||||
message = Message(
|
||||
chat_id=chat_id,
|
||||
sender_id=user.id,
|
||||
text=payload.text
|
||||
)
|
||||
session.add(message)
|
||||
await session.commit()
|
||||
await session.refresh(message)
|
||||
return message
|
||||
|
||||
@router.get("")
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100")
|
||||
|
||||
await check_chat_access(chat_id, user.id, session)
|
||||
|
||||
result = await session.execute(
|
||||
select(Message)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id)
|
||||
)
|
||||
msgs = result.scalars().all()
|
||||
|
||||
my_messages = [
|
||||
{
|
||||
"id": m.id,
|
||||
"chat_id": m.chat_id,
|
||||
"sender_id": m.sender_id,
|
||||
"text": m.text,
|
||||
"created_at": m.created_at.isoformat().replace("+00:00", "Z"),
|
||||
} for m in msgs
|
||||
]
|
||||
|
||||
page, next_cursor = paginate(my_messages, limit, cursor)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,49 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field, ConfigDict, field_serializer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.models.user import User
|
||||
from app.security import get_password_hash, get_current_user
|
||||
from app.dependencies import get_session
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=5, max_length=128)
|
||||
|
||||
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")
|
||||
|
||||
@router.post("", status_code=201, response_model=UserResponse)
|
||||
async def register_user(payload: CreateUser, session: AsyncSession = Depends(get_session)):
|
||||
result = await session.execute(select(User).where(User.username == payload.username))
|
||||
if result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=409, detail="Имя пользователя уже существует")
|
||||
|
||||
user = User(
|
||||
username=payload.username,
|
||||
display_name=payload.display_name,
|
||||
password_hash=get_password_hash(payload.password)
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
await session.refresh(user)
|
||||
return user
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
async def current_user(user: User = Depends(get_current_user)):
|
||||
return user
|
||||
@@ -0,0 +1,73 @@
|
||||
import secrets
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from passlib.context import CryptContext
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy import select
|
||||
from app.database import async_session_maker
|
||||
from app.models.user import User
|
||||
from app.redis_client import redis_client
|
||||
from app.config import SESSION_TTL_SECONDS
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
async def create_session(user_id: str) -> dict:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
|
||||
await redis_client.setex(
|
||||
name=f"session:{token}",
|
||||
time=SESSION_TTL_SECONDS,
|
||||
value=str(user_id),
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at.isoformat().replace( "+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
async def delete_session(token: str) -> None:
|
||||
await redis_client.delete(f"session:{token}")
|
||||
|
||||
async def get_current_user(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"'},
|
||||
)
|
||||
|
||||
async with async_session_maker() as session:
|
||||
result = await session.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
return user
|
||||
@@ -0,0 +1,9 @@
|
||||
import threading
|
||||
|
||||
users_lock = threading.Lock()
|
||||
messages_lock = threading.Lock()
|
||||
|
||||
users_by_id: dict[str, dict] = {}
|
||||
users_by_username: dict[str, dict] = {}
|
||||
chats_by_id: dict[str, dict] = {}
|
||||
messages_by_chat: dict[str, list[dict]] = {}
|
||||
Reference in New Issue
Block a user