Inform user that email is invalid using Django's Password Reset

房东的猫 提交于 2019-11-30 13:01:37

问题


I am using the built-in django password reset functionality. The documentation states:

If the email address provided does not exist in the system, this view won’t send an email, but the user won’t receive any error message either. This prevents information leaking to potential attackers. If you want to provide an error message in this case, you can subclass PasswordResetForm and use the password_reset_form argument.

However, in my case it's more important to show an error message when a user tries to reset using the wrong username.

I understand what I need to do but I don't know what to write in the form subclassing PasswordResetForm.

What should the form subclassing PasswordResetForm contain?

Thank you.


回答1:


So I finally figured it out myself. Here's my implementation:

class EmailValidationOnForgotPassword(PasswordResetForm):
    def clean_email(self):
        email = self.cleaned_data['email']
        if not User.objects.filter(email__iexact=email, is_active=True).exists():
            raise ValidationError("There is no user registered with the specified email address!")

        return email

You also need to add {'password_reset_form': EmailValidationOnForgotPassword} to urls.py. Here's an example:

url(r'^user/password/reset/$',
    'django.contrib.auth.views.password_reset',
    {'post_reset_redirect': '/user/password/reset/done/',
     'html_email_template_name': 'registration/password_reset_email.html',
     'password_reset_form': EmailValidationOnForgotPassword},
    name="password_reset"),



回答2:


For later versions of Django such as Django 2.1 there is a similar question with slightly modified code.

#forms.py
from django.contrib.auth.forms import PasswordResetForm

class EmailValidationOnForgotPassword(PasswordResetForm):

    def clean_email(self):
        email = self.cleaned_data['email']
        if not User.objects.filter(email__iexact=email, is_active=True).exists():
            msg = _("There is no user registered with the specified E-Mail address.")
            self.add_error('email', msg)
        return email

And

#urls.py
from accounts.forms import EmailValidationOnForgotPassword

path('accounts/password_reset/', auth_views.PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword), name='password_reset'),

Please be aware that this can be used to obtain usernames/e-mails. One way to reduce this issue is to respond with a 429 Too Many Requests as soon an user tries 3 different E-Mails. This can be achived using for example django-ratelimit



来源:https://stackoverflow.com/questions/27734185/inform-user-that-email-is-invalid-using-djangos-password-reset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!