diff --git a/accounts/tests/test_admin_email_otp.py b/accounts/tests/test_admin_email_otp.py index f3d14f41..2897cbc9 100644 --- a/accounts/tests/test_admin_email_otp.py +++ b/accounts/tests/test_admin_email_otp.py @@ -3,6 +3,7 @@ from unittest.mock import patch from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse +from django_otp.plugins.otp_totp.models import TOTPDevice class AdminEmailOtpTestCase(TestCase): @@ -31,6 +32,11 @@ class AdminEmailOtpTestCase(TestCase): self.assertEqual(response.status_code, 302) mock_send.assert_called_once() + @patch("accounts.views.send_email_with_otp", side_effect=ConnectionRefusedError) + def test_a_mail_that_did_not_go_leaves_the_user_without_otp(self, mock_send): + self.client.post(self.url) + self.assertFalse(TOTPDevice.objects.filter(user=self.user).exists()) + def test_the_smtp_connection_waits_a_bounded_time(self): from django.core.mail.backends.smtp import EmailBackend diff --git a/accounts/views.py b/accounts/views.py index 72105fbb..8ab4ea4a 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -380,7 +380,8 @@ def admin_email_otp(request, user_id): subject = f"User {user.username}" if user.email != "": try: - with audit(request, None, subject, "mail OTP QR code"): + # a device made for a mail that did not go would ask for codes the user never got + with audit(request, None, subject, "mail OTP QR code"), transaction.atomic(): get_user_totp_device(user) send_email_with_otp(request, user) except OSError as err: # the SMTP server refused it, or did not answer within EMAIL_TIMEOUT