from dataclasses import replace from apps.shared.application.ports import Clock, UnitOfWork from apps.shared.domain.exceptions import InvalidEmailAddress from apps.shared.domain.value_objects import EmailAddress from apps.users.application.dto import ( CreatedUser, PasswordLink, PasswordLinkPurpose, UserDetailsData, ) from apps.users.application.ports import PasswordLinkService from apps.users.domain.entities import UserAccount from apps.users.domain.exceptions import ( EmailAlreadyTaken, InvalidSupervisor, LastActiveAdmin, SupervisorHasInterns, UserNotFound, ) from apps.users.domain.repositories import UserRepository from apps.users.domain.value_objects import PersonName def _check_supervisor(repo: UserRepository, user: UserAccount) -> None: if user.supervisor_id is None: return supervisor = repo.get_by_id(user.supervisor_id) if supervisor is None or not supervisor.can_supervise or supervisor.id == user.id: raise InvalidSupervisor() class CreateUser: """An admin creates a user; the user sets the password with a 72 h link.""" def __init__(self, repo: UserRepository, uow: UnitOfWork, links: PasswordLinkService) -> None: self.repo = repo self.uow = uow self.links = links def execute(self, data: UserDetailsData) -> CreatedUser: name = PersonName(data.name) email = EmailAddress(data.email) with self.uow: if self.repo.is_email_taken(email): raise EmailAlreadyTaken() user = UserAccount.register( name=name, email=email, role=data.role, employment_ends_on=data.employment_ends_on, supervisor_id=data.supervisor_id, ) _check_supervisor(self.repo, user) user = self.repo.save(user) assert user.id is not None link = self.links.issue(user.id, PasswordLinkPurpose.SETUP) # Email is sent outside the transaction: a mail failure must not undo the user. emailed = self.links.send(user, link, PasswordLinkPurpose.SETUP) return CreatedUser(user_id=user.id, password_link=replace(link, emailed=emailed)) class UpdateUser: def __init__(self, repo: UserRepository, uow: UnitOfWork) -> None: self.repo = repo self.uow = uow def execute(self, user_id: int, data: UserDetailsData) -> None: name = PersonName(data.name) email = EmailAddress(data.email) with self.uow: current = self.repo.get_by_id(user_id) if current is None: raise UserNotFound() if self.repo.is_email_taken(email, exclude_id=user_id): raise EmailAlreadyTaken() updated = current.update_details( name=name, email=email, role=data.role, is_active=data.is_active, employment_ends_on=data.employment_ends_on, supervisor_id=data.supervisor_id, ) _check_supervisor(self.repo, updated) # The count locks the admin rows, so two concurrent changes cannot remove the last one. if ( current.is_active_admin and not updated.is_active_admin and self.repo.lock_active_admin_count() <= 1 ): raise LastActiveAdmin() if ( current.can_supervise and not updated.can_supervise and self.repo.has_active_interns(user_id) ): raise SupervisorHasInterns() self.repo.save(updated) class IssuePasswordLink: """An admin creates a new 72 h link for an existing user (shown and emailed).""" def __init__(self, repo: UserRepository, links: PasswordLinkService) -> None: self.repo = repo self.links = links def execute(self, user_id: int) -> PasswordLink: user = self.repo.get_by_id(user_id) if user is None: raise UserNotFound() link = self.links.issue(user_id, PasswordLinkPurpose.SETUP) emailed = self.links.send(user, link, PasswordLinkPurpose.SETUP) return replace(link, emailed=emailed) class RequestPasswordReset: """Forgot password: emails a 60 min link only to users allowed to log in today. The caller always shows the same message, so the page does not reveal which emails exist. """ def __init__(self, repo: UserRepository, links: PasswordLinkService, clock: Clock) -> None: self.repo = repo self.links = links self.clock = clock def execute(self, email: str) -> None: try: address = EmailAddress(email) except InvalidEmailAddress: return user = self.repo.get_by_email(address) if user is None or user.id is None or not user.can_log_in(self.clock.today()): return link = self.links.issue(user.id, PasswordLinkPurpose.RESET) self.links.send(user, link, PasswordLinkPurpose.RESET) class CheckLoginAllowed: """A user may log in (and keep a session) while active and, for interns, until the end date.""" def __init__(self, repo: UserRepository, clock: Clock) -> None: self.repo = repo self.clock = clock def execute(self, user_id: int) -> bool: user = self.repo.get_by_id(user_id) return user is not None and user.can_log_in(self.clock.today())