Merge pull request #2153 from cisagov/nl/1780-check-SES-before-adding-user

Issue #1780: Don't add user to a domain invitation if we don't have a connection to SES
This commit is contained in:
CuriousX 2024-05-24 13:25:35 -06:00 committed by GitHub
commit a606fe71e7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 45 additions and 14 deletions

View file

@ -32,8 +32,9 @@ def send_templated_email(
template_name and subject_template_name are relative to the same template template_name and subject_template_name are relative to the same template
context as Django's HTML templates. context gives additional information context as Django's HTML templates. context gives additional information
that the template may use. that the template may use.
Raises EmailSendingError if SES client could not be accessed
""" """
logger.info(f"An email was sent! Template name: {template_name} to {to_address}")
template = get_template(template_name) template = get_template(template_name)
email_body = template.render(context=context) email_body = template.render(context=context)
@ -48,7 +49,9 @@ def send_templated_email(
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
config=settings.BOTO_CONFIG, config=settings.BOTO_CONFIG,
) )
logger.info(f"An email was sent! Template name: {template_name} to {to_address}")
except Exception as exc: except Exception as exc:
logger.debug("E-mail unable to send! Could not access the SES client.")
raise EmailSendingError("Could not access the SES client.") from exc raise EmailSendingError("Could not access the SES client.") from exc
destination = {"ToAddresses": [to_address]} destination = {"ToAddresses": [to_address]}

View file

@ -734,7 +734,10 @@ class DomainAddUserView(DomainFormBaseView):
does not make a domain information object does not make a domain information object
email: string- email to send to email: string- email to send to
add_success: bool- default True indicates: add_success: bool- default True indicates:
adding a success message to the view if the email sending succeeds""" adding a success message to the view if the email sending succeeds
raises EmailSendingError
"""
# Set a default email address to send to for staff # Set a default email address to send to for staff
requestor_email = settings.DEFAULT_FROM_EMAIL requestor_email = settings.DEFAULT_FROM_EMAIL
@ -762,33 +765,43 @@ class DomainAddUserView(DomainFormBaseView):
"requestor_email": requestor_email, "requestor_email": requestor_email,
}, },
) )
except EmailSendingError: except EmailSendingError as exc:
messages.warning(self.request, "Could not send email invitation.")
logger.warn( logger.warn(
"Could not sent email invitation to %s for domain %s", "Could not sent email invitation to %s for domain %s",
email, email,
self.object, self.object,
exc_info=True, exc_info=True,
) )
raise EmailSendingError("Could not send email invitation.") from exc
else: else:
if add_success: if add_success:
messages.success(self.request, f"{email} has been invited to this domain.") messages.success(self.request, f"{email} has been invited to this domain.")
def _make_invitation(self, email_address: str, requestor: User): def _make_invitation(self, email_address: str, requestor: User):
"""Make a Domain invitation for this email and redirect with a message.""" """Make a Domain invitation for this email and redirect with a message."""
invitation, created = DomainInvitation.objects.get_or_create(email=email_address, domain=self.object) # Check to see if an invite has already been sent (NOTE: we do not want to create an invite just yet.)
if not created: try:
invite = DomainInvitation.objects.get(email=email_address, domain=self.object)
# that invitation already existed # that invitation already existed
messages.warning( if invite is not None:
self.request, messages.warning(
f"{email_address} has already been invited to this domain.", self.request,
) f"{email_address} has already been invited to this domain.",
else: )
self._send_domain_invitation_email(email=email_address, requestor=requestor) except DomainInvitation.DoesNotExist:
# Try to send the invitation. If it succeeds, add it to the DomainInvitation table.
try:
self._send_domain_invitation_email(email=email_address, requestor=requestor)
except EmailSendingError:
messages.warning(self.request, "Could not send email invitation.")
else:
# (NOTE: only create a domainInvitation if the e-mail sends correctly)
DomainInvitation.objects.get_or_create(email=email_address, domain=self.object)
return redirect(self.get_success_url()) return redirect(self.get_success_url())
def form_valid(self, form): def form_valid(self, form):
"""Add the specified user on this domain.""" """Add the specified user on this domain.
Throws EmailSendingError."""
requested_email = form.cleaned_data["email"] requested_email = form.cleaned_data["email"]
requestor = self.request.user requestor = self.request.user
# look up a user with that email # look up a user with that email
@ -799,7 +812,22 @@ class DomainAddUserView(DomainFormBaseView):
return self._make_invitation(requested_email, requestor) return self._make_invitation(requested_email, requestor)
else: else:
# if user already exists then just send an email # if user already exists then just send an email
self._send_domain_invitation_email(requested_email, requestor, add_success=False) try:
self._send_domain_invitation_email(requested_email, requestor, add_success=False)
except EmailSendingError:
logger.warn(
"Could not send email invitation (EmailSendingError)",
self.object,
exc_info=True,
)
messages.warning(self.request, "Could not send email invitation.")
except Exception:
logger.warn(
"Could not send email invitation (Other Exception)",
self.object,
exc_info=True,
)
messages.warning(self.request, "Could not send email invitation.")
try: try:
UserDomainRole.objects.create( UserDomainRole.objects.create(