Skip to content

Commit dc09e8a

Browse files
authored
fix issue where trying another already confirmed email threw an uncaught exception (#11161)
## Purpose If user email already existed the error was uncaught. ## Changes - adds change to catch 400 error - adds test case.
1 parent e000c5b commit dc09e8a

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

api/users/views.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from urllib.parse import urlencode
33

44
from django.apps import apps
5+
from django.db import IntegrityError
56
from django.db.models import F
67
from django.utils.decorators import method_decorator
78
from django.views.decorators.csrf import csrf_protect
@@ -1146,7 +1147,12 @@ def post(self, request, *args, **kwargs):
11461147
if not user.is_registered:
11471148
user.register(email)
11481149

1149-
user.emails.get_or_create(address=email.lower())
1150+
if not user.emails.filter(address=email.lower()).exists():
1151+
try:
1152+
user.emails.create(address=email.lower())
1153+
except IntegrityError:
1154+
raise ValidationError('Email address already exists.')
1155+
11501156
user.date_last_logged_in = timezone.now()
11511157

11521158
del user.email_verifications[token]

api_tests/users/views/test_user_confirm.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,3 +199,31 @@ def test_post_success_link_with_email_verification_none(
199199

200200
user.reload()
201201
assert not user.external_identity
202+
203+
@mock.patch('website.mails.send_mail')
204+
def test_post_success_link_with_email_already_exists(
205+
self,
206+
mock_send_mail,
207+
app,
208+
confirm_url,
209+
user_with_email_verification
210+
):
211+
user, token, email = user_with_email_verification
212+
AuthUserFactory(username=email) # User with already existing email
213+
user.save()
214+
215+
res = app.post_json_api(
216+
confirm_url,
217+
{
218+
'data': {
219+
'attributes': {
220+
'uid': user._id,
221+
'token': token,
222+
'destination': 'doesnotmatter'
223+
}
224+
}
225+
},
226+
expect_errors=True
227+
)
228+
assert res.status_code == 400
229+
assert res.json['errors'][0] == {'detail': 'Email address already exists.'}

0 commit comments

Comments
 (0)