我有2个意见。 1)用于用户注册。 2)用于密码重置。 这两个任务的激活链接已生成并发送到邮件。 我的首次注册激活链接工作正常。 创建密码重置的激活链接时,使用后它不会过期。
@csrf_protect
def changing_password_confirmation(request, uidb64, token):
try:
uid = force_bytes(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and passord_reset_token.check_token(user, token):
print('user is not None and passord_reset_token.check_token(user, token)')
if request.method == 'POST':
password1 = request.POST.get('password1')
password2 = request.POST.get('password2')
if password1 == password2:
user.set_password(password1)
user.save()
return render(request=request, template_name='website/password_reset_complete.html')
else:
return HttpResponse('<h1>Password doesnt match</h1>')
return render(request=request, template_name='website/password_reset_confirm.html')
else:
print('User', user)
result = 'Activation link is invalid!'
return render(request=request, template_name='website/password_reset_confirm.html', context={'result': result})
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(user.is_active)
)
class PasswordTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(user.is_active)
)
account_activation_token = TokenGenerator()
passord_reset_token = PasswordTokenGenerator()
重置密码模板
{% extends "website/header.html" %}
{% block title %}Enter new password{% endblock %}
{% block content %}
{% if validlink %}
<h1>Set a new password!</h1>
<form method="POST">
{% csrf_token %}
<div class="form-group">
Password: <input type="text" class="form-control" name='password1' placeholder="password" value=""/>
</div>
<div class="form-group">
Repeat Password: <input type="text" class="form-control" name='password2' placeholder="confirm" value=""/>
</div>
<input type="submit" value="Change my password">
</form>
{% else %}
{{ result }}
{% endif %}
{% endblock %}```
答案 0 :(得分:1)
首先,Django comes with views to reset passwords。我建议您使用它们而不是自己编写。
您的哈希仅随用户的pk
和is_active
字段而变化,并且在用户重置密码后这些哈希值不会改变。
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(user.is_active)
)
在Django solves the problem中,将用户的password
和last_login
包括在哈希中,以便在重置密码后更改它。