Coverage for src/kwai/modules/identity/mail_user_recovery.py: 93%
30 statements
« prev ^ index » next coverage.py v7.6.10, created at 2024-01-01 00:00 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2024-01-01 00:00 +0000
1"""Module that defines the use case for sending a recovery email."""
3from dataclasses import dataclass
5from kwai.core.domain.exceptions import UnprocessableException
6from kwai.core.domain.value_objects.unique_id import UniqueId
7from kwai.core.mail.mailer import Mailer
8from kwai.core.mail.recipient import Recipients
9from kwai.core.template.mail_template import MailTemplate
10from kwai.modules.identity.user_recoveries.user_recovery import UserRecoveryEntity
11from kwai.modules.identity.user_recoveries.user_recovery_mailer import (
12 UserRecoveryMailer,
13)
14from kwai.modules.identity.user_recoveries.user_recovery_repository import (
15 UserRecoveryRepository,
16)
19@dataclass(frozen=True, kw_only=True)
20class MailUserRecoveryCommand:
21 """Command for the use case MailUserRecovery.
23 Attributes:
24 uuid: The unique id of the user recovery.
25 """
27 uuid: str
30class MailUserRecovery:
31 """Use case for sending a recovery email."""
33 def __init__(
34 self,
35 user_recovery_repo: UserRecoveryRepository,
36 mailer: Mailer,
37 recipients: Recipients,
38 mail_template: MailTemplate,
39 ):
40 self._user_recovery_repo = user_recovery_repo
41 self._mailer = mailer
42 self._recipients = recipients
43 self._mail_template = mail_template
45 async def execute(self, command: MailUserRecoveryCommand) -> UserRecoveryEntity:
46 """Execute the use case.
48 Args:
49 command: The input for this use case.
51 Raises:
52 UserRecoveryNotFoundException: Raised when
53 the user recovery cannot be found.
54 UnprocessableException: Raised when the mail was already sent.
55 Raised when the user recovery was already confirmed.
56 """
57 user_recovery = await self._user_recovery_repo.get_by_uuid(
58 UniqueId.create_from_string(command.uuid)
59 )
61 if user_recovery.mailed:
62 raise UnprocessableException(
63 f"Mail already send for user recovery {command.uuid}"
64 )
66 if user_recovery.is_expired:
67 raise UnprocessableException(
68 f"User recovery {command.uuid} already expired"
69 )
71 if user_recovery.confirmed:
72 raise UnprocessableException(
73 f"User recovery {command.uuid} already confirmed"
74 )
76 UserRecoveryMailer(
77 self._mailer, self._recipients, self._mail_template, user_recovery
78 ).send()
80 user_recovery = user_recovery.mail_sent()
82 await self._user_recovery_repo.update(user_recovery)
84 return user_recovery