def reset_password(request): """Allow a user to reset their password. The user authenticates by presenting a security token. Users will arrive at this page by clicking on the URL in the email they are sent by the /auth/forgot_password page. """ if request.user: return http.HttpResponseForbidden('Logged-in users prohibited.') tmpl = loader.get_template('auth/reset_password.html') ctx_vars = { 'Title': 'Reset Password', } user = None if request.method == 'GET': token = request.GET.get('token') if token is None: return http.HttpResponseForbidden('Missing token') email = auth.parse_password_reset_token(token) if email is None: return http.HttpResponseForbidden('Invalid token') ctx_vars['form'] = auth_forms.ResetPasswordForm( initial={'token': token}) else: form = auth_forms.ResetPasswordForm(request.POST) if not form.is_valid(): ctx_vars['form'] = form else: token = form.cleaned_data['token'] email = token and auth.parse_password_reset_token(token) if email is None: return http.HttpResponseForbidden('Invalid token') user = User.get_by_email(email) if user is None: return http.HttpResponseForbidden('No user for token') user.set_password(form.cleaned_data['new_password']) # We are also logging the user in automatically, so record # the time. user.last_login = datetime.datetime.now() AutoRetry(user).save() # Attach the user to the request so that our page will # display the chrome shown to logged-in users. request.user = user ctx = RequestContext(request, ctx_vars) response = http.HttpResponse(tmpl.render(ctx)) if request.user: auth.attach_credentials(response, request.user) return response
def test_password_reset_token_create_and_parse(self): email = '*****@*****.**' user = User(email=email) token = auth.get_password_reset_token(user) observed_email = auth.parse_password_reset_token(token) self.assertEqual(email, observed_email)