From fa0f7f79aca34f005771dd3e41ad3838682a3053 Mon Sep 17 00:00:00 2001 From: catborise Date: Tue, 10 Nov 2026 07:58:46 +0300 Subject: [PATCH] fix(accounts): a failed OTP mail leaves the user without OTP The admin's "Email OTP QR code" made the user's TOTP device and then sent the mail. When the SMTP server refused it, the page said so, but the device stayed: the user's next login asked for a code from a QR code they never got. The device and the mail now share one transaction. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kk4h2TcUiaWmU5MUszYSea --- accounts/tests/test_admin_email_otp.py | 6 ++++++ accounts/views.py | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) 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