Permalink
Browse files

Fixed #7723 - implemented a secure password reset form that uses a to…

…ken and prompts user for new password.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@8162 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent 9a56fe7 commit fcd837cd0f9b2c706bc49af509628778d442bb3f @spookylukey spookylukey committed Jul 31, 2008
@@ -366,6 +366,9 @@
LOGIN_REDIRECT_URL = '/accounts/profile/'
+# The number of days a password reset link is valid for
+PASSWORD_RESET_TIMEOUT_DAYS = 3
+
###########
# TESTING #
###########
@@ -0,0 +1,14 @@
+{% extends "admin/base_site.html" %}
+{% load i18n %}
+
+{% block breadcrumbs %}<div class="breadcrumbs"><a href="../../">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset' %}</div>{% endblock %}
+
+{% block title %}{% trans 'Password reset complete' %}{% endblock %}
+
+{% block content %}
+
+<h1>{% trans 'Password reset complete' %}</h1>
+
+<p>{% trans "Your password has been set. You may go ahead and log in now." %}</p>
+
+{% endblock %}
@@ -0,0 +1,32 @@
+{% extends "admin/base_site.html" %}
+{% load i18n %}
+
+{% block breadcrumbs %}<div class="breadcrumbs"><a href="../">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset confirmation' %}</div>{% endblock %}
+
+{% block title %}{% trans 'Password reset' %}{% endblock %}
+
+{% block content %}
+
+{% if validlink %}
+
+<h1>{% trans 'Enter new password' %}</h1>
+
+<p>{% trans "Please enter your new password twice so we can verify you typed it in correctly." %}</p>
+
+<form action="" method="post">
+{% if form.new_password1.errors %}{{ form.new_password1.errors }}{% endif %}
+<p class="aligned wide"><label for="id_new_password1">{% trans 'New password:' %}</label>{{ form.new_password1 }}</p>
+{% if form.new_password2.errors %}{{ form.new_password2.errors }}{% endif %}
+<p class="aligned wide"><label for="id_new_password2">{% trans 'Confirm password:' %}</label>{{ form.new_password2 }}</p>
+<p><input type="submit" value="{% trans 'Change my password' %}" /></p>
+</form>
+
+{% else %}
+
+<h1>{% trans 'Password reset unsuccessful' %}</h1>
+
+<p>{% trans "The password reset link was invalid, possibly because it has already been used. Please request a new password reset." %}
+
+{% endif %}
+
+{% endblock %}
@@ -9,6 +9,6 @@
<h1>{% trans 'Password reset successful' %}</h1>
-<p>{% trans "We've e-mailed a new password to the e-mail address you submitted. You should be receiving it shortly." %}</p>
+<p>{% trans "We've e-mailed you instructions for setting your password to the e-mail address you submitted. You should be receiving it shortly." %}</p>
{% endblock %}
@@ -1,15 +1,15 @@
-{% load i18n %}
+{% load i18n %}{% autoescape off %}
{% trans "You're receiving this e-mail because you requested a password reset" %}
{% blocktrans %}for your user account at {{ site_name }}{% endblocktrans %}.
-{% blocktrans %}Your new password is: {{ new_password }}{% endblocktrans %}
-
-{% trans "Feel free to change this password by going to this page:" %}
-
-http://{{ domain }}/password_change/
-
+{% trans "Please go to the following page and choose a new password:" %}
+{% block reset_link %}
+{{ protocol }}://{{ domain }}/reset/{{ uid }}-{{ token }}/
+{% endblock %}
{% trans "Your username, in case you've forgotten:" %} {{ user.username }}
{% trans "Thanks for using our site!" %}
{% blocktrans %}The {{ site_name }} team{% endblocktrans %}
+
+{% endautoescape %}
@@ -9,7 +9,7 @@
<h1>{% trans "Password reset" %}</h1>
-<p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll reset your password and e-mail the new one to you." %}</p>
+<p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll e-mail instructions for setting a new one." %}</p>
<form action="" method="post">
{% if form.email.errors %}{{ form.email.errors }}{% endif %}
@@ -1,9 +1,11 @@
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
+from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.template import Context, loader
from django import forms
from django.utils.translation import ugettext_lazy as _
+from django.utils.http import int_to_base36
class UserCreationForm(forms.ModelForm):
"""
@@ -97,16 +99,14 @@ def clean_email(self):
self.users_cache = User.objects.filter(email__iexact=email)
if len(self.users_cache) == 0:
raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
-
- def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
+
+ def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
+ use_https=False, token_generator=default_token_generator):
"""
- Calculates a new password randomly and sends it to the user.
+ Generates a one-use only link for restting password and sends to the user
"""
from django.core.mail import send_mail
for user in self.users_cache:
- new_pass = User.objects.make_random_password()
- user.set_password(new_pass)
- user.save()
if not domain_override:
current_site = Site.objects.get_current()
site_name = current_site.name
@@ -115,50 +115,60 @@ def save(self, domain_override=None, email_template_name='registration/password_
site_name = domain = domain_override
t = loader.get_template(email_template_name)
c = {
- 'new_password': new_pass,
'email': user.email,
'domain': domain,
'site_name': site_name,
+ 'uid': int_to_base36(user.id),
'user': user,
+ 'token': token_generator.make_token(user),
+ 'protocol': use_https and 'https' or 'http',
}
send_mail(_("Password reset on %s") % site_name,
t.render(Context(c)), None, [user.email])
-class PasswordChangeForm(forms.Form):
+class SetPasswordForm(forms.Form):
"""
- A form that lets a user change his/her password.
+ A form that lets a user change set his/her password without
+ entering the old password
"""
- old_password = forms.CharField(label=_("Old password"), max_length=30, widget=forms.PasswordInput)
- new_password1 = forms.CharField(label=_("New password"), max_length=30, widget=forms.PasswordInput)
- new_password2 = forms.CharField(label=_("New password confirmation"), max_length=30, widget=forms.PasswordInput)
-
+ new_password1 = forms.CharField(label=_("New password"), max_length=60, widget=forms.PasswordInput)
+ new_password2 = forms.CharField(label=_("New password confirmation"), max_length=60, widget=forms.PasswordInput)
+
def __init__(self, user, *args, **kwargs):
self.user = user
- super(PasswordChangeForm, self).__init__(*args, **kwargs)
-
- def clean_old_password(self):
- """
- Validates that the old_password field is correct.
- """
- old_password = self.cleaned_data["old_password"]
- if not self.user.check_password(old_password):
- raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
- return old_password
-
+ super(SetPasswordForm, self).__init__(*args, **kwargs)
+
def clean_new_password2(self):
password1 = self.cleaned_data.get('new_password1')
password2 = self.cleaned_data.get('new_password2')
if password1 and password2:
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
-
+
def save(self, commit=True):
self.user.set_password(self.cleaned_data['new_password1'])
if commit:
self.user.save()
return self.user
-
+
+class PasswordChangeForm(SetPasswordForm):
+ """
+ A form that lets a user change his/her password by entering
+ their old password.
+ """
+ old_password = forms.CharField(label=_("Old password"), max_length=60, widget=forms.PasswordInput)
+
+ def clean_old_password(self):
+ """
+ Validates that the old_password field is correct.
+ """
+ old_password = self.cleaned_data["old_password"]
+ if not self.user.check_password(old_password):
+ raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
+ return old_password
+PasswordChangeForm.base_fields.keyOrder = ['old_password', 'new_password1', 'new_password2']
+
class AdminPasswordChangeForm(forms.Form):
"""
A form used to change the password of a user in the admin interface.
@@ -1,8 +1,11 @@
-from django.contrib.auth.tests.basic import BASIC_TESTS, PasswordResetTest
+from django.contrib.auth.tests.basic import BASIC_TESTS
+from django.contrib.auth.tests.views import PasswordResetTest
from django.contrib.auth.tests.forms import FORM_TESTS
+from django.contrib.auth.tests.tokens import TOKEN_GENERATOR_TESTS
__test__ = {
'BASIC_TESTS': BASIC_TESTS,
'PASSWORDRESET_TESTS': PasswordResetTest,
'FORM_TESTS': FORM_TESTS,
+ 'TOKEN_GENERATOR_TESTS': TOKEN_GENERATOR_TESTS
}
@@ -54,24 +54,3 @@
>>> u.password
u'!'
"""
-
-from django.test import TestCase
-from django.core import mail
-
-class PasswordResetTest(TestCase):
- fixtures = ['authtestdata.json']
- urls = 'django.contrib.auth.urls'
-
- def test_email_not_found(self):
- "Error is raised if the provided email address isn't currently registered"
- response = self.client.get('/password_reset/')
- self.assertEquals(response.status_code, 200)
- response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'})
- self.assertContains(response, "That e-mail address doesn't have an associated user account")
- self.assertEquals(len(mail.outbox), 0)
-
- def test_email_found(self):
- "Email is sent if a valid email address is provided for password reset"
- response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
- self.assertEquals(response.status_code, 302)
- self.assertEquals(len(mail.outbox), 1)
@@ -2,7 +2,7 @@
FORM_TESTS = """
>>> from django.contrib.auth.models import User
>>> from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
->>> from django.contrib.auth.forms import PasswordChangeForm
+>>> from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm
The user already exists.
@@ -95,6 +95,32 @@
>>> form.non_field_errors()
[]
+SetPasswordForm:
+
+The two new passwords do not match.
+
+>>> data = {
+... 'new_password1': 'abc123',
+... 'new_password2': 'abc',
+... }
+>>> form = SetPasswordForm(user, data)
+>>> form.is_valid()
+False
+>>> form["new_password2"].errors
+[u"The two password fields didn't match."]
+
+The success case.
+
+>>> data = {
+... 'new_password1': 'abc123',
+... 'new_password2': 'abc123',
+... }
+>>> form = SetPasswordForm(user, data)
+>>> form.is_valid()
+True
+
+PasswordChangeForm:
+
The old password is incorrect.
>>> data = {
@@ -132,4 +158,9 @@
>>> form.is_valid()
True
+Regression test - check the order of fields:
+
+>>> PasswordChangeForm(user, {}).fields.keys()
+['old_password', 'new_password1', 'new_password2']
+
"""
@@ -0,0 +1,29 @@
+TOKEN_GENERATOR_TESTS = """
+>>> from django.contrib.auth.models import User, AnonymousUser
+>>> from django.contrib.auth.tokens import PasswordResetTokenGenerator
+>>> from django.conf import settings
+>>> u = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw')
+>>> p0 = PasswordResetTokenGenerator()
+>>> tk1 = p0.make_token(u)
+>>> p0.check_token(u, tk1)
+True
+
+Tests to ensure we can use the token after n days, but no greater.
+Use a mocked version of PasswordResetTokenGenerator so we can change
+the value of 'today'
+
+>>> class Mocked(PasswordResetTokenGenerator):
+... def __init__(self, today):
+... self._today_val = today
+... def _today(self):
+... return self._today_val
+
+>>> from datetime import date, timedelta
+>>> p1 = Mocked(date.today() + timedelta(settings.PASSWORD_RESET_TIMEOUT_DAYS))
+>>> p1.check_token(u, tk1)
+True
+>>> p2 = Mocked(date.today() + timedelta(settings.PASSWORD_RESET_TIMEOUT_DAYS + 1))
+>>> p2.check_token(u, tk1)
+False
+
+"""
Oops, something went wrong.

0 comments on commit fcd837c

Please sign in to comment.