Coverage for fastid / auth / models.py: 100%

79 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-10-18 16:37 +0000

1from __future__ import annotations 

2 

3from typing import TYPE_CHECKING, Self 

4 

5import anyio.to_thread 

6from sqlalchemy.ext.hybrid import hybrid_property 

7from sqlalchemy.orm import Mapped, mapped_column, relationship 

8 

9from fastid.auth.exceptions import WrongPasswordError 

10from fastid.auth.schemas import Contact, ContactType 

11from fastid.database.base import VersionedEntity 

12from fastid.database.utils import uuid 

13from fastid.email.config import email_settings 

14from fastid.integrations.config import integration_settings 

15from fastid.notify.config import notify_settings 

16from fastid.notify.schemas import SendOTPRequest, UserAction 

17from fastid.security.crypto import crypt_ctx 

18 

19if TYPE_CHECKING: 

20 from collections.abc import Mapping, Sequence 

21 

22 from fastid.auth.schemas import UserCreate 

23 from fastid.notify.models import Notification 

24 from fastid.oauth.models import OAuthAccount 

25 from fastid.oauth.schemas import OpenIDBearer 

26 

27 

28class User(VersionedEntity): 

29 __tablename__ = "users" 

30 

31 first_name: Mapped[str] 

32 last_name: Mapped[str | None] 

33 email: Mapped[str | None] = mapped_column(index=True) 

34 telegram_id: Mapped[int | None] = mapped_column(index=True) 

35 hashed_password: Mapped[str | None] 

36 is_active: Mapped[bool] = mapped_column(default=True) 

37 is_superuser: Mapped[bool] = mapped_column(default=False) 

38 is_verified: Mapped[bool] = mapped_column(default=False) 

39 

40 oauth_accounts: Mapped[list[OAuthAccount]] = relationship(back_populates="user", cascade="delete") 

41 notifications: Mapped[list[Notification]] = relationship(back_populates="user", cascade="delete") 

42 

43 @hybrid_property 

44 def is_oauth(self) -> bool: 

45 return bool(self.hashed_password) 

46 

47 @hybrid_property 

48 def display_name(self) -> str: 

49 if self.last_name: 

50 return f"{self.first_name} {self.last_name}" 

51 if self.first_name: 

52 return self.first_name 

53 msg = f"User id={self.id} has no available names" 

54 raise ValueError(msg) 

55 

56 @classmethod 

57 def from_create(cls, dto: UserCreate) -> Self: 

58 user = cls( 

59 first_name=dto.first_name, 

60 last_name=dto.last_name, 

61 email=dto.email, 

62 ) 

63 user.set_password(dto.password) 

64 return user 

65 

66 @classmethod 

67 def from_open_id(cls, open_id: OpenIDBearer) -> Self: 

68 user = cls( 

69 id=uuid(), 

70 first_name=open_id.first_name, 

71 last_name=open_id.last_name, 

72 email=open_id.email, 

73 ) 

74 user.verify() 

75 user.connect_open_id(open_id) 

76 return user 

77 

78 def connect_open_id(self, open_id: OpenIDBearer) -> None: 

79 if open_id.provider == "telegram": 

80 self.telegram_id = int(open_id.id) 

81 

82 def disconnect_open_id(self, provider: str) -> None: 

83 if provider == "telegram": 

84 self.telegram_id = None 

85 

86 def set_password(self, password: str) -> None: 

87 self.hashed_password = crypt_ctx.hash(password) 

88 

89 def change_email(self, new_email: str) -> None: 

90 self.email = new_email 

91 

92 async def verify_password(self, password: str) -> None: 

93 valid = await anyio.to_thread.run_sync( 

94 crypt_ctx.verify, 

95 password, 

96 self.hashed_password, 

97 ) 

98 if not valid: 

99 raise WrongPasswordError 

100 

101 def grant_superuser(self) -> None: 

102 self.is_superuser = True 

103 

104 def revoke_superuser(self) -> None: 

105 self.is_superuser = False 

106 

107 def verify(self) -> None: 

108 self.is_verified = True 

109 

110 def is_email_available(self) -> bool: 

111 return self.email is not None and email_settings.smtp_enabled 

112 

113 def is_telegram_available(self) -> bool: 

114 return self.telegram_id is not None and integration_settings.telegram_notification_enabled 

115 

116 def email_contact(self) -> Contact: 

117 if not self.is_email_available(): 

118 msg = f"User id={self.id} has no available email" 

119 raise ValueError(msg) 

120 return Contact(type=ContactType.email, recipient={"email": self.email}) 

121 

122 def telegram_contact(self) -> Contact: 

123 if not self.is_telegram_available(): 

124 msg = f"User id={self.id} has no available telegram" 

125 raise ValueError(msg) 

126 return Contact(type=ContactType.telegram, recipient={"telegram_id": self.telegram_id}) 

127 

128 def find_contacts(self) -> Mapping[ContactType, Contact]: 

129 contacts = {} 

130 if self.is_email_available(): 

131 contacts[ContactType.email] = self.email_contact() 

132 if self.is_telegram_available(): 

133 contacts[ContactType.telegram] = self.telegram_contact() 

134 if not contacts: 

135 msg = f"User id={self.id} has no available contacts" 

136 raise ValueError(msg) 

137 return contacts 

138 

139 def sort_contacts(self) -> Sequence[Contact]: 

140 contacts = list(self.find_contacts().values()) 

141 contacts.sort(key=lambda x: notify_settings.contact_priority[x.type]) 

142 return contacts 

143 

144 def find_priority_contact(self) -> Contact: 

145 return self.sort_contacts()[0] 

146 

147 def find_contact_for_otp(self, dto: SendOTPRequest) -> Contact: 

148 if dto.action == UserAction.change_email and dto.email: 

149 return Contact(type=ContactType.email, recipient={"email": dto.email}) 

150 return self.find_priority_contact()