79 lines
2.2 KiB
Python
79 lines
2.2 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
from fastapi import Depends, Header, HTTPException, Request, status
|
|
|
|
from ..db.redis import RedisSessionStore
|
|
from ..domain.errors import Unauthorized
|
|
from ..domain.models import User
|
|
from ..services.chats import ChatService
|
|
from ..services.attachments import AttachmentService
|
|
from ..services.messages import MessageService
|
|
from ..services.users import UserService
|
|
|
|
_BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class Services:
|
|
attachments: AttachmentService
|
|
users: UserService
|
|
chats: ChatService
|
|
messages: MessageService
|
|
sessions: RedisSessionStore
|
|
|
|
|
|
def services(request: Request) -> Services:
|
|
return request.app.state.services
|
|
|
|
|
|
def user_service(container: Services = Depends(services)) -> UserService:
|
|
return container.users
|
|
|
|
|
|
def chat_service(container: Services = Depends(services)) -> ChatService:
|
|
return container.chats
|
|
|
|
|
|
def message_service(container: Services = Depends(services)) -> MessageService:
|
|
return container.messages
|
|
|
|
|
|
def attachment_service(container: Services = Depends(services)) -> AttachmentService:
|
|
return container.attachments
|
|
|
|
|
|
def session_store(container: Services = Depends(services)) -> RedisSessionStore:
|
|
return container.sessions
|
|
|
|
|
|
def _bearer_error() -> HTTPException:
|
|
return HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail='требуется действующая Bearer-сессия',
|
|
headers={'WWW-Authenticate': _BEARER_CHALLENGE},
|
|
)
|
|
|
|
|
|
async def bearer_token(authorization: str | None = Header(None)) -> str:
|
|
if not authorization:
|
|
raise _bearer_error()
|
|
scheme, separator, token = authorization.partition(' ')
|
|
if scheme.lower() != 'bearer' or not separator or not token or token.strip() != token:
|
|
raise _bearer_error()
|
|
return token
|
|
|
|
|
|
async def current_user(
|
|
token: str = Depends(bearer_token),
|
|
container: Services = Depends(services),
|
|
) -> User:
|
|
user_id = await container.sessions.get_user_id(token)
|
|
if user_id is None:
|
|
raise _bearer_error()
|
|
try:
|
|
return await container.users.identify(user_id)
|
|
except Unauthorized:
|
|
raise _bearer_error() from None
|