Skip to content

Commit

Permalink
api.user_manager: create EmailSender only when required
Browse files Browse the repository at this point in the history
Convert self._email_sender to an attribute and only create the object
when required.  This way, the API can be run without email support as
long as no endpoints that rely on email features are used.

Signed-off-by: Guillaume Tucker <[email protected]>
  • Loading branch information
gctucker committed Nov 10, 2023
1 parent 2ff0faf commit a5b7a15
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions api/user_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,19 @@ class UserManager(ObjectIDIDMixin, BaseUserManager[User, PydanticObjectId]):

def __init__(self, user_db: BaseUserDatabase[User, PydanticObjectId],
password_helper: PasswordHelperProtocol | None = None):
self._email_sender = EmailSender()
self._email_sender = None
self._template_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(
"./templates/")
)
super().__init__(user_db, password_helper)

@property
def email_sender(self):
if self._email_sender is None:
self._email_sender = EmailSender()
return self._email_sender

async def on_after_register(self, user: User,
request: Optional[Request] = None):
"""Handler to execute after successful user registration"""
Expand All @@ -50,7 +56,7 @@ async def on_after_request_verify(self, user: User, token: str,
content = template.render(
username=user.username, token=token
)
self._email_sender.create_and_send_email(subject, content, user.email)
self.email_sender.create_and_send_email(subject, content, user.email)

async def on_after_verify(self, user: User,
request: Optional[Request] = None):
Expand All @@ -62,7 +68,7 @@ async def on_after_verify(self, user: User,
content = template.render(
username=user.username,
)
self._email_sender.create_and_send_email(subject, content, user.email)
self.email_sender.create_and_send_email(subject, content, user.email)

async def on_after_login(self, user: User,
request: Optional[Request] = None):
Expand All @@ -77,7 +83,7 @@ async def on_after_forgot_password(self, user: User, token: str,
content = template.render(
username=user.username, token=token
)
self._email_sender.create_and_send_email(subject, content, user.email)
self.email_sender.create_and_send_email(subject, content, user.email)

async def on_after_reset_password(self, user: User,
request: Optional[Request] = None):
Expand All @@ -89,7 +95,7 @@ async def on_after_reset_password(self, user: User,
content = template.render(
username=user.username,
)
self._email_sender.create_and_send_email(subject, content, user.email)
self.email_sender.create_and_send_email(subject, content, user.email)

async def on_after_update(self, user: User, update_dict: Dict[str, Any],
request: Optional[Request] = None):
Expand Down

0 comments on commit a5b7a15

Please sign in to comment.