Coverage for kwai/modules/identity/create_user.py: 96%
24 statements
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-05 17:55 +0000
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-05 17:55 +0000
1"""Use case: create a user."""
2from dataclasses import dataclass
4from kwai.core.domain.exceptions import UnprocessableException
5from kwai.core.domain.value_objects.email_address import EmailAddress
6from kwai.core.domain.value_objects.name import Name
7from kwai.core.domain.value_objects.password import Password
8from kwai.modules.identity.users.user import UserEntity
9from kwai.modules.identity.users.user_account import UserAccountEntity
10from kwai.modules.identity.users.user_account_repository import UserAccountRepository
13@dataclass(kw_only=True, frozen=True, slots=False)
14class CreateUserCommand:
15 """Input for the CreateUser use case.
17 See: [CreateUser][kwai.modules.identity.create_user.CreateUser]
19 Attributes:
20 email: The email address for the new user.
21 first_name: The first name of the new user.
22 last_name: The last name of the new user.
23 password: The password for the new user.
24 remark: A remark about the new user.
25 """
27 email: str
28 first_name: str
29 last_name: str
30 password: str
31 remark: str
34class CreateUser:
35 """Use case for creating a new user."""
37 def __init__(self, user_account_repo: UserAccountRepository):
38 """Create the use case.
40 Args:
41 user_account_repo: Repository that creates a new user account.
42 """
43 self._user_account_repo = user_account_repo
45 async def execute(self, command: CreateUserCommand) -> UserAccountEntity:
46 """Execute the use case.
48 Args:
49 command: The input for this use case.
51 Returns:
52 An entity for a user account.
54 Raises:
55 UnprocessableException: when the email address is already used by another
56 user.
57 """
58 email = EmailAddress(command.email)
59 if await self._user_account_repo.exists_with_email(email):
60 raise UnprocessableException(
61 f"A user with email {command.email} already exists."
62 )
64 user_account = UserAccountEntity(
65 user=UserEntity(
66 email=email,
67 remark=command.remark,
68 name=Name(first_name=command.first_name, last_name=command.last_name),
69 ),
70 password=Password.create_from_string(command.password),
71 )
72 return await self._user_account_repo.create(user_account)