forms: show error if all accounts for reset have no email (#62866)

This commit is contained in:
Benjamin Dauvergne 2022-04-28 15:57:30 +02:00
parent 4da7c8492f
commit 0148257950
2 changed files with 19 additions and 1 deletions

View File

@ -43,6 +43,7 @@ class PasswordResetForm(HoneypotForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.users = []
if app_settings.A2_USER_CAN_RESET_PASSWORD_BY_USERNAME:
del self.fields['email']
self.fields['email_or_username'] = forms.CharField(label=_('Email or username'), max_length=254)
@ -67,6 +68,11 @@ class PasswordResetForm(HoneypotForm):
self.cleaned_data['email'] = email_or_username
return email_or_username
def clean(self):
if self.users and not any(user.email for user in self.users):
raise ValidationError(_('Your account has no email, you cannot ask for a password reset.'))
return self.cleaned_data
def save(self):
"""
Generates a one-use only link for resetting password and sends to the

View File

@ -95,12 +95,24 @@ def test_can_reset_by_username(app, db, simple_user, settings, mailoutbox):
def test_can_reset_by_username_with_email(app, db, simple_user, settings, mailoutbox):
settings.A2_USER_CAN_RESET_PASSWORD_BY_USERNAME = True
resp = app.get('/password/reset/')
resp.form.set('email_or_username', simple_user.email)
resp.form.set('email_or_username', simple_user.username)
resp = resp.form.submit().follow()
assert 'An email has been sent to %s' % simple_user.username in resp
assert len(mailoutbox) == 1
def test_can_reset_by_username_no_email(app, db, simple_user, settings, mailoutbox):
settings.A2_USER_CAN_RESET_PASSWORD_BY_USERNAME = True
simple_user.email = ''
simple_user.save()
resp = app.get('/password/reset/')
resp.form.set('email_or_username', simple_user.username)
resp = resp.form.submit()
assert any('Your account has no email' in text for text in resp.pyquery('.errornotice p').contents())
assert len(mailoutbox) == 0
def test_reset_by_email_no_account(app, db, mailoutbox):
resp = app.get('/password/reset/')
resp.form.set('email', 'john.doe@example.com')