ЛР 2: мессенджер на PostgreSQL и сессии в Redis
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
from . import auth, chats, health, messages, users
|
||||
|
||||
__all__ = ['auth', 'chats', 'health', 'messages', 'users']
|
||||
@@ -0,0 +1,71 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from binascii import Error as Base64Error
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
||||
|
||||
from ...auth.tokens import create_token
|
||||
from ...db.redis import RedisSessionStore
|
||||
from ...domain.models import User
|
||||
from ...services.users import UserService
|
||||
from ..deps import bearer_token, current_user, session_store, user_service
|
||||
from ..schemas import SessionOut, UserOut
|
||||
from ..timefmt import to_rfc3339
|
||||
|
||||
router = APIRouter(prefix='/api/v1/auth/sessions', tags=['auth'])
|
||||
|
||||
_BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
|
||||
|
||||
def _unauthorized_basic() -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail='неверные учётные данные',
|
||||
headers={'WWW-Authenticate': _BASIC_CHALLENGE},
|
||||
)
|
||||
|
||||
|
||||
def _parse_basic(authorization: str | None) -> tuple[str, str]:
|
||||
if not authorization:
|
||||
raise _unauthorized_basic()
|
||||
scheme, separator, encoded = authorization.partition(' ')
|
||||
if scheme.lower() != 'basic' or not separator or not encoded:
|
||||
raise _unauthorized_basic()
|
||||
try:
|
||||
decoded = base64.b64decode(encoded, validate=True).decode('utf-8')
|
||||
except (Base64Error, UnicodeDecodeError):
|
||||
raise _unauthorized_basic() from None
|
||||
username, separator, password = decoded.partition(':')
|
||||
if not separator or not username:
|
||||
raise _unauthorized_basic()
|
||||
return username, password
|
||||
|
||||
|
||||
@router.post('', status_code=status.HTTP_201_CREATED, response_model=SessionOut)
|
||||
async def create_session(
|
||||
authorization: str | None = Header(None),
|
||||
users: UserService = Depends(user_service),
|
||||
sessions: RedisSessionStore = Depends(session_store),
|
||||
) -> SessionOut:
|
||||
username, password = _parse_basic(authorization)
|
||||
user = await users.authenticate(username, password)
|
||||
if user is None:
|
||||
raise _unauthorized_basic()
|
||||
token = create_token()
|
||||
expires_at = await sessions.create(user.id, token)
|
||||
return SessionOut(
|
||||
token=token,
|
||||
token_type='Bearer',
|
||||
expires_at=to_rfc3339(expires_at),
|
||||
user=UserOut.from_domain(user),
|
||||
)
|
||||
|
||||
|
||||
@router.delete('/current', status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||
async def revoke_session(
|
||||
token: str = Depends(bearer_token),
|
||||
_: User = Depends(current_user),
|
||||
sessions: RedisSessionStore = Depends(session_store),
|
||||
) -> None:
|
||||
await sessions.revoke(token)
|
||||
@@ -0,0 +1,49 @@
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from ...domain.models import User
|
||||
from ...services.chats import ChatService
|
||||
from .. import cursors
|
||||
from ..deps import chat_service, current_user
|
||||
from ..schemas import (
|
||||
LIMIT_DEFAULT,
|
||||
LIMIT_MAX,
|
||||
LIMIT_MIN,
|
||||
ChatOut,
|
||||
ChatPageOut,
|
||||
CreateChat,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix='/api/v1/chats', tags=['chats'])
|
||||
|
||||
|
||||
@router.post('', status_code=201, response_model=ChatOut)
|
||||
async def create(
|
||||
body: CreateChat,
|
||||
actor: User = Depends(current_user),
|
||||
chats: ChatService = Depends(chat_service),
|
||||
) -> ChatOut:
|
||||
return ChatOut.from_domain(await chats.create(actor, body.title, body.member_ids))
|
||||
|
||||
|
||||
@router.get('', response_model=ChatPageOut)
|
||||
async def page(
|
||||
actor: User = Depends(current_user),
|
||||
chats: ChatService = Depends(chat_service),
|
||||
limit: int = Query(LIMIT_DEFAULT, ge=LIMIT_MIN, le=LIMIT_MAX),
|
||||
cursor: Optional[str] = Query(None, min_length=1, max_length=cursors.MAX_LENGTH),
|
||||
) -> ChatPageOut:
|
||||
scope = f'chats:{actor.id}'
|
||||
after = cursors.decode(scope, cursor) if cursor is not None else None
|
||||
return ChatPageOut.from_domain(await chats.page(actor, after, limit), scope)
|
||||
|
||||
|
||||
@router.get('/{chat_id}', response_model=ChatOut)
|
||||
async def get(
|
||||
chat_id: UUID,
|
||||
actor: User = Depends(current_user),
|
||||
chats: ChatService = Depends(chat_service),
|
||||
) -> ChatOut:
|
||||
return ChatOut.from_domain(await chats.get(actor, chat_id))
|
||||
@@ -0,0 +1,28 @@
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from redis.exceptions import RedisError
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from ...domain.errors import Unavailable
|
||||
|
||||
from ..schemas import HealthOut
|
||||
|
||||
router = APIRouter(tags=['health'])
|
||||
|
||||
|
||||
@router.get('/health/live', response_model=HealthOut)
|
||||
async def live() -> HealthOut:
|
||||
return HealthOut(status='ok')
|
||||
|
||||
|
||||
@router.get('/health/ready', response_model=HealthOut)
|
||||
async def ready(request: Request) -> HealthOut:
|
||||
if not request.app.state.ready:
|
||||
raise HTTPException(status_code=503, detail='приложение не готово принимать трафик')
|
||||
try:
|
||||
async with request.app.state.engine.connect() as connection:
|
||||
await connection.execute(text('SELECT 1'))
|
||||
await request.app.state.redis.ping()
|
||||
except (SQLAlchemyError, RedisError, Unavailable, OSError):
|
||||
raise HTTPException(status_code=503, detail='обязательное хранилище недоступно') from None
|
||||
return HealthOut(status='ok')
|
||||
@@ -0,0 +1,42 @@
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from ...domain.models import User
|
||||
from ...services.messages import MessageService
|
||||
from .. import cursors
|
||||
from ..deps import current_user, message_service
|
||||
from ..schemas import (
|
||||
LIMIT_DEFAULT,
|
||||
LIMIT_MAX,
|
||||
LIMIT_MIN,
|
||||
CreateMessage,
|
||||
MessageOut,
|
||||
MessagePageOut,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix='/api/v1/chats/{chat_id}/messages', tags=['messages'])
|
||||
|
||||
|
||||
@router.post('', status_code=201, response_model=MessageOut)
|
||||
async def send(
|
||||
chat_id: UUID,
|
||||
body: CreateMessage,
|
||||
actor: User = Depends(current_user),
|
||||
messages: MessageService = Depends(message_service),
|
||||
) -> MessageOut:
|
||||
return MessageOut.from_domain(await messages.send(actor, chat_id, body.text))
|
||||
|
||||
|
||||
@router.get('', response_model=MessagePageOut)
|
||||
async def page(
|
||||
chat_id: UUID,
|
||||
actor: User = Depends(current_user),
|
||||
messages: MessageService = Depends(message_service),
|
||||
limit: int = Query(LIMIT_DEFAULT, ge=LIMIT_MIN, le=LIMIT_MAX),
|
||||
cursor: Optional[str] = Query(None, min_length=1, max_length=cursors.MAX_LENGTH),
|
||||
) -> MessagePageOut:
|
||||
scope = f'messages:{chat_id}'
|
||||
after = cursors.decode(scope, cursor) if cursor is not None else None
|
||||
return MessagePageOut.from_domain(await messages.history(actor, chat_id, after, limit), scope)
|
||||
@@ -0,0 +1,18 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from ...domain.models import User
|
||||
from ...services.users import UserService
|
||||
from ..deps import current_user, user_service
|
||||
from ..schemas import CreateUser, UserOut
|
||||
|
||||
router = APIRouter(prefix='/api/v1', tags=['users'])
|
||||
|
||||
|
||||
@router.post('/users', status_code=201, response_model=UserOut)
|
||||
async def register(body: CreateUser, users: UserService = Depends(user_service)) -> UserOut:
|
||||
return UserOut.from_domain(await users.register(body.username, body.display_name, body.password))
|
||||
|
||||
|
||||
@router.get('/users/me', response_model=UserOut)
|
||||
async def me(actor: User = Depends(current_user)) -> UserOut:
|
||||
return UserOut.from_domain(actor)
|
||||
Reference in New Issue
Block a user