migrated lab1 minimum to lab2
This commit is contained in:
+173
@@ -0,0 +1,173 @@
|
||||
import json
|
||||
import uuid
|
||||
from typing import Optional, Sequence, Type, TypeVar
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from starlette.responses import Response
|
||||
|
||||
from .auth import BASIC_CHALLENGE, BEARER_CHALLENGE, parse_basic, parse_bearer
|
||||
from .errors import invalid_request, not_found, unauthorized
|
||||
from .pagination import encode_cursor, parse_page
|
||||
from .schemas import CreateChat, CreateMessage, CreateUser
|
||||
from .store import Chat, Store, User
|
||||
|
||||
router = APIRouter()
|
||||
Body = TypeVar('Body', bound=BaseModel)
|
||||
|
||||
|
||||
async def get_store(request: Request) -> Store:
|
||||
return request.app.state.store
|
||||
|
||||
|
||||
async def current_user(request: Request) -> User:
|
||||
"""Bearer only. X-User-Id is ignored and does not identify anyone."""
|
||||
token = parse_bearer(request.headers.get('Authorization', ''))
|
||||
if token is None:
|
||||
raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE)
|
||||
user = request.app.state.store.user_for_token(token)
|
||||
if user is None:
|
||||
raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE)
|
||||
return user
|
||||
|
||||
|
||||
async def read_body(request: Request, model: Type[Body]) -> Body:
|
||||
try:
|
||||
payload = json.loads(await request.body())
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise invalid_request('Тело запроса не является корректным JSON') from None
|
||||
if not isinstance(payload, dict):
|
||||
raise invalid_request('Тело запроса должно быть JSON-объектом')
|
||||
try:
|
||||
return model.model_validate(payload)
|
||||
except ValidationError:
|
||||
raise invalid_request('Тело запроса не соответствует контракту') from None
|
||||
|
||||
|
||||
def _member_chat(store: Store, chat_id: str, actor: User) -> Chat:
|
||||
try:
|
||||
canonical = str(uuid.UUID(chat_id))
|
||||
except ValueError:
|
||||
raise invalid_request('Некорректный chat_id') from None
|
||||
chat = store.find_chat(canonical, actor.id)
|
||||
if chat is None:
|
||||
raise not_found('Чат не найден')
|
||||
return chat
|
||||
|
||||
|
||||
def _page(items: Sequence, has_more: bool, scope: str) -> dict:
|
||||
cursor: Optional[str] = None
|
||||
if has_more and items:
|
||||
cursor = encode_cursor(scope, (items[-1].created_at, items[-1].id))
|
||||
return {'items': [item.to_dict() for item in items], 'next_cursor': cursor}
|
||||
|
||||
|
||||
@router.get('/health/live')
|
||||
async def liveness() -> JSONResponse:
|
||||
return JSONResponse({'status': 'ok'})
|
||||
|
||||
|
||||
@router.get('/health/ready')
|
||||
async def readiness() -> JSONResponse:
|
||||
"""In-memory only: the process itself is the single dependency of the sync path."""
|
||||
return JSONResponse({'status': 'ok'})
|
||||
|
||||
|
||||
@router.post('/api/v1/users')
|
||||
async def register_user(request: Request, store: Store = Depends(get_store)) -> JSONResponse:
|
||||
payload = await read_body(request, CreateUser)
|
||||
user = store.create_user(payload.username, payload.display_name, payload.password)
|
||||
return JSONResponse(user.to_dict(), status_code=201)
|
||||
|
||||
|
||||
@router.post('/api/v1/auth/sessions')
|
||||
async def create_session(request: Request, store: Store = Depends(get_store)) -> JSONResponse:
|
||||
parsed = parse_basic(request.headers.get('Authorization', ''))
|
||||
if parsed is None:
|
||||
raise unauthorized('Неверные учётные данные', BASIC_CHALLENGE)
|
||||
user = store.authenticate(*parsed)
|
||||
if user is None:
|
||||
raise unauthorized('Неверные учётные данные', BASIC_CHALLENGE)
|
||||
token, expires_at = store.create_session(user.id)
|
||||
body = {
|
||||
'token': token,
|
||||
'token_type': 'Bearer',
|
||||
'expires_at': expires_at,
|
||||
'user': user.to_dict(),
|
||||
}
|
||||
return JSONResponse(body, status_code=201)
|
||||
|
||||
|
||||
@router.delete('/api/v1/auth/sessions/current')
|
||||
async def revoke_session(request: Request, actor: User = Depends(current_user)) -> Response:
|
||||
token = parse_bearer(request.headers.get('Authorization', ''))
|
||||
if token is None or not request.app.state.store.revoke_session(token):
|
||||
raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get('/api/v1/users/me')
|
||||
async def show_current_user(actor: User = Depends(current_user)) -> JSONResponse:
|
||||
return JSONResponse(actor.to_dict())
|
||||
|
||||
|
||||
@router.post('/api/v1/chats')
|
||||
async def create_chat(
|
||||
request: Request,
|
||||
actor: User = Depends(current_user),
|
||||
store: Store = Depends(get_store),
|
||||
) -> JSONResponse:
|
||||
payload = await read_body(request, CreateChat)
|
||||
if actor.id not in payload.member_ids:
|
||||
raise invalid_request('Создатель чата должен быть указан в member_ids')
|
||||
chat = store.create_chat(payload.title, payload.member_ids)
|
||||
return JSONResponse(chat.to_dict(), status_code=201)
|
||||
|
||||
|
||||
@router.get('/api/v1/chats')
|
||||
async def list_chats(
|
||||
request: Request,
|
||||
actor: User = Depends(current_user),
|
||||
store: Store = Depends(get_store),
|
||||
) -> JSONResponse:
|
||||
scope = 'chats:' + actor.id
|
||||
limit, after = parse_page(request.query_params, scope)
|
||||
chats, has_more = store.list_chats(actor.id, limit, after)
|
||||
return JSONResponse(_page(chats, has_more, scope))
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}')
|
||||
async def show_chat(
|
||||
chat_id: str,
|
||||
actor: User = Depends(current_user),
|
||||
store: Store = Depends(get_store),
|
||||
) -> JSONResponse:
|
||||
return JSONResponse(_member_chat(store, chat_id, actor).to_dict())
|
||||
|
||||
|
||||
@router.post('/api/v1/chats/{chat_id}/messages')
|
||||
async def send_message(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
actor: User = Depends(current_user),
|
||||
store: Store = Depends(get_store),
|
||||
) -> JSONResponse:
|
||||
chat = _member_chat(store, chat_id, actor)
|
||||
payload = await read_body(request, CreateMessage)
|
||||
message = store.add_message(chat.id, actor.id, payload.text)
|
||||
return JSONResponse(message.to_dict(), status_code=201)
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}/messages')
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
actor: User = Depends(current_user),
|
||||
store: Store = Depends(get_store),
|
||||
) -> JSONResponse:
|
||||
chat = _member_chat(store, chat_id, actor)
|
||||
scope = 'messages:' + chat.id
|
||||
limit, after = parse_page(request.query_params, scope)
|
||||
messages, has_more = store.list_messages(chat.id, limit, after)
|
||||
return JSONResponse(_page(messages, has_more, scope))
|
||||
Reference in New Issue
Block a user