Coverage for fastid / notify / use_cases.py: 96%
77 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-10-18 16:37 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-10-18 16:37 +0000
1import secrets
3from fastid.auth.config import auth_settings
4from fastid.auth.exceptions import EmailNotFoundError
5from fastid.auth.models import User
6from fastid.auth.repositories import EmailUserSpecification
7from fastid.auth.schemas import Contact, ContactType
8from fastid.auth.server import ServerURLDep
9from fastid.cache.dependencies import CacheDep
10from fastid.cache.exceptions import KeyNotFoundError
11from fastid.core.base import UseCase
12from fastid.database.dependencies import UOWRawDep, transactional
13from fastid.database.exceptions import NoResultFoundError
14from fastid.email.config import email_settings
15from fastid.email.dependencies import MailDep
16from fastid.integrations.config import integration_settings
17from fastid.integrations.dependencies import TelegramNotificationsDep
18from fastid.notify.exceptions import (
19 InvalidContactTypeError,
20 MethodDisabledError,
21 NoEmailError,
22 NoTelegramIDError,
23 TemplateNotFoundError,
24 WrongCodeError,
25)
26from fastid.notify.models import Notification, NotificationType
27from fastid.notify.repositories import EmailTemplateSlugSpecification, TelegramTemplateSlugSpecification
28from fastid.notify.schemas import (
29 PushNotificationRequest,
30 SendOTPRequest,
31 UserAction,
32 VerifyOTPRequest,
33)
34from fastid.notify.templating import jinja_env
35from fastid.security.crypto import generate_otp
36from fastid.security.jwt import jwt_backend
37from fastid.security.schemas import JWTPayload
40class NotificationUseCases(UseCase):
41 def __init__(
42 self,
43 uow: UOWRawDep, # Due to background nature of notification use cases, use raw dependency
44 mail: MailDep,
45 telegram: TelegramNotificationsDep,
46 cache: CacheDep,
47 server_url: ServerURLDep,
48 ) -> None:
49 self.uow = uow
50 self.mail = mail
51 self.telegram = telegram
52 self.cache = cache
53 self.server_url = server_url
55 @transactional
56 async def push_email(self, user: User, dto: PushNotificationRequest, contact: Contact | None = None) -> None:
57 if not email_settings.smtp_enabled: 57 ↛ 58line 57 didn't jump to line 58 because the condition on line 57 was never true
58 raise MethodDisabledError
59 if contact is None:
60 try:
61 contact = user.email_contact()
62 except ValueError as e:
63 raise NoEmailError from e
64 assert contact.type == ContactType.email
66 base = await self.uow.email_templates.find(EmailTemplateSlugSpecification("base"))
67 base_template = jinja_env.from_string(base.source)
69 try:
70 main = await self.uow.email_templates.find(EmailTemplateSlugSpecification(dto.template))
71 except NoResultFoundError as e:
72 raise TemplateNotFoundError from e
74 main_template = jinja_env.from_string(main.source)
75 content = main_template.render(base=base_template, user=user, **dto.context)
76 await self.mail.send(contact=contact, subject=main.subject, content=content)
77 notification = Notification(user=user, type=NotificationType.email, template=dto.template, context=dto.context)
78 await self.uow.notifications.add(notification)
80 @transactional
81 async def push_telegram(self, user: User, dto: PushNotificationRequest, contact: Contact | None = None) -> None:
82 if not integration_settings.telegram_notification_enabled: 82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true
83 raise MethodDisabledError
84 if contact is None:
85 try:
86 contact = user.telegram_contact()
87 except ValueError as e:
88 raise NoTelegramIDError from e
89 assert contact.type == ContactType.telegram
91 try:
92 template = await self.uow.telegram_templates.find(TelegramTemplateSlugSpecification(dto.template))
93 except NoResultFoundError as e:
94 raise TemplateNotFoundError from e
96 jinja_template = jinja_env.from_string(template.source)
97 content = jinja_template.render(user=user, **dto.context)
98 await self.telegram.send(contact=contact, content=content)
99 notification = Notification(
100 user=user,
101 type=NotificationType.telegram,
102 template=dto.template,
103 context=dto.context,
104 )
105 await self.uow.notifications.add(notification)
107 async def push(self, user: User, dto: PushNotificationRequest, contact: Contact | None = None) -> None:
108 if contact is None:
109 contact = user.find_priority_contact()
110 match contact.type:
111 case ContactType.email:
112 return await self.push_email(user, dto, contact)
113 case ContactType.telegram:
114 return await self.push_telegram(user, dto, contact)
115 case _: # pragma: nocover
116 raise InvalidContactTypeError
118 async def push_otp(self, user: User | None, dto: SendOTPRequest) -> None:
119 if dto.action == UserAction.recover_password:
120 assert dto.email is not None
121 user = await self._get_user_by_email(dto.email)
122 assert user is not None
123 contact = user.find_contact_for_otp(dto)
124 code = await self._generate_otp(user)
125 request = PushNotificationRequest(template="code", context={"code": code})
126 await self.push(user, request, contact)
128 async def validate_otp(self, user: User, code: str) -> None:
129 try:
130 user_code = await self.cache.pop(f"otp:users:{user.id}")
131 except KeyNotFoundError as e:
132 raise WrongCodeError from e
133 if not secrets.compare_digest(user_code, code):
134 raise WrongCodeError
136 async def verify_otp(self, user: User | None, dto: VerifyOTPRequest) -> str:
137 if dto.action == UserAction.recover_password:
138 assert dto.email is not None
139 user = await self._get_user_by_email(dto.email)
140 assert user is not None
141 await self.validate_otp(user, dto.code)
142 token_data = jwt_backend.create("verify", JWTPayload(sub=str(user.id)), issuer=self.server_url)
143 return token_data[0]
145 @transactional
146 async def _get_user_by_email(self, email: str) -> User:
147 try:
148 return await self.uow.users.find(EmailUserSpecification(email))
149 except NoResultFoundError as e:
150 raise EmailNotFoundError from e
152 async def _generate_otp(self, user: User) -> str:
153 code = generate_otp()
154 await self.cache.set(
155 f"otp:users:{user.id}",
156 code,
157 expire=auth_settings.verification_code_expires_in,
158 )
159 return code