Files

36 lines
1.3 KiB
Python

from __future__ import annotations
from datetime import datetime, timezone
from uuid import UUID, uuid4
from ..auth.passwords import hash_password, password_matches
from ..domain.errors import Unauthorized
from ..domain.models import User
from ..repositories import UserRepository
class UserService:
def __init__(self, repository: UserRepository) -> None:
self._repository = repository
async def register(self, username: str, display_name: str, password: str) -> User:
return await self._repository.register(
user_id=uuid4(),
username=username,
display_name=display_name,
password_hash=hash_password(password),
created_at=datetime.now(timezone.utc),
)
async def identify(self, user_id: UUID) -> User:
user = await self._repository.get_by_id(user_id)
if user is None:
raise Unauthorized('требуется действующая сессия')
return user
async def authenticate(self, username: str, password: str) -> User | None:
row = await self._repository.get_credentials(username)
if row is None or not password_matches(row.password_hash, password):
return None
return self._repository.to_domain(row)