Coverage for kwai/modules/identity/recover_user.py: 96%

24 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2023-09-05 17:55 +0000

1"""Module that implements the recover user use case.""" 

2from dataclasses import dataclass 

3 

4from kwai.core.domain.exceptions import UnprocessableException 

5from kwai.core.domain.value_objects.email_address import EmailAddress 

6from kwai.core.domain.value_objects.local_timestamp import LocalTimestamp 

7from kwai.core.events.bus import Bus 

8from kwai.modules.identity.user_recoveries.user_recovery import UserRecoveryEntity 

9from kwai.modules.identity.user_recoveries.user_recovery_events import ( 

10 UserRecoveryCreatedEvent, 

11) 

12from kwai.modules.identity.user_recoveries.user_recovery_repository import ( 

13 UserRecoveryRepository, 

14) 

15from kwai.modules.identity.users.user_account_repository import UserAccountRepository 

16 

17 

18@dataclass(frozen=True, kw_only=True) 

19class RecoverUserCommand: 

20 """Command for the recover user use case.""" 

21 

22 email: str 

23 

24 

25class RecoverUser: 

26 """Use case: recover user. 

27 

28 Attributes: 

29 _user_account_repo (UserAccountRepository): The repository for getting the 

30 user account. 

31 _user_recovery_repo (UserRecoveryRepository): The repository for creating a 

32 user recovery. 

33 _event_bus (Bus): An event bus for dispatching the UserRecoveryCreatedEvent 

34 event. 

35 """ 

36 

37 def __init__( 

38 self, 

39 user_repo: UserAccountRepository, 

40 user_recovery_repo: UserRecoveryRepository, 

41 event_bus: Bus, 

42 ): 

43 self._user_account_repo = user_repo 

44 self._user_recovery_repo = user_recovery_repo 

45 self._event_bus = event_bus 

46 

47 async def execute(self, command: RecoverUserCommand) -> UserRecoveryEntity: 

48 """Execute the use case. 

49 

50 Args: 

51 command: The input for this use case. 

52 

53 Raises: 

54 UserAccountNotFoundException: Raised when the user with the given email 

55 address does not exist. 

56 UnprocessableException: Raised when the user is revoked 

57 """ 

58 user_account = await self._user_account_repo.get_user_by_email( 

59 EmailAddress(command.email) 

60 ) 

61 if user_account.revoked: 

62 raise UnprocessableException("User account is revoked") 

63 

64 user_recovery = await self._user_recovery_repo.create( 

65 UserRecoveryEntity( 

66 user=user_account.user, 

67 expiration=LocalTimestamp.create_with_delta(hours=2), 

68 ) 

69 ) 

70 

71 await self._event_bus.publish( 

72 UserRecoveryCreatedEvent(uuid=str(user_recovery.uuid)) 

73 ) 

74 

75 return user_recovery