forked from mtusi2026/mtusi2026lab2
42 lines
1.4 KiB
Python
42 lines
1.4 KiB
Python
from fastapi import Request
|
|
|
|
from app.core.errors import ApiError
|
|
from app.repositories.memory import SessionRow, UserRow
|
|
|
|
import uuid as _uuid
|
|
|
|
BEARER_CHALLENGE = {'WWW-Authenticate': 'Bearer realm="messenger"'}
|
|
|
|
|
|
def storage_of(request: Request):
|
|
return request.app.state.storage
|
|
|
|
|
|
async def current_session(request: Request) -> SessionRow:
|
|
header = request.headers.get('authorization', '')
|
|
token = header[7:].strip() if header[:7].lower() == 'bearer ' else ''
|
|
if not token:
|
|
raise ApiError(401, 'Bearer session required', headers=BEARER_CHALLENGE)
|
|
row = await storage_of(request).session(token)
|
|
if row is None:
|
|
raise ApiError(401, 'Session is missing, expired or revoked', headers=BEARER_CHALLENGE)
|
|
return row
|
|
|
|
|
|
async def current_user(request: Request) -> UserRow:
|
|
session = await current_session(request)
|
|
user = await storage_of(request).user(session.user_id)
|
|
if user is None:
|
|
raise ApiError(401, 'Session user no longer exists', headers=BEARER_CHALLENGE)
|
|
return user
|
|
|
|
|
|
async def require_chat_member(request: Request, chat_id: str, user: UserRow):
|
|
try:
|
|
_uuid.UUID(chat_id)
|
|
except ValueError:
|
|
raise ApiError(400, 'chat_id must be a UUID')
|
|
row = await storage_of(request).chat(chat_id)
|
|
if row is None or user.id not in row.member_ids:
|
|
raise ApiError(404, 'Chat is not available for this user')
|
|
return row |