gpt4 book ai didi

python - 再次来自用户的 check_password()

转载 作者:IT老高 更新时间:2023-10-28 20:52:40 26 4
gpt4 key购买 nike

我有以下表格。在用户最终更改其电子邮件地址之前,如何再次检查用户的密码?即使用户已登录,我也只想确定它确实是用户。只是安全问题。

如何使用 .check_password()

'EmailChangeForm' object has no attribute 'user'

/home/craphunter/workspace/project/trunk/project/auth/user/email_change/forms.py in clean_password, line 43
from django import forms
from django.db.models.loading import cache
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User


class EmailChangeForm(forms.Form):

email = forms.EmailField(label='New E-mail', max_length=75)
password = forms.CharField(widget=forms.PasswordInput)

def __init__(self, user, *args, **kwargs):
super(EmailChangeForm, self).__init__(*args, **kwargs)
self.user = user

def clean_password(self):
valid = self.user.check_password(self.cleaned_data['password'])
if not valid:
raise forms.ValidationError("Password Incorrect")
return valid

def __init__(self, username=None, *args, **kwargs):
"""Constructor.

**Mandatory arguments**

``username``
The username of the user that requested the email change.

"""
self.username = username
super(EmailChangeForm, self).__init__(*args, **kwargs)

def clean_email(self):
"""Checks whether the new email address differs from the user's current
email address.

"""
email = self.cleaned_data.get('email')

User = cache.get_model('auth', 'User')
user = User.objects.get(username__exact=self.username)

# Check if the new email address differs from the current email address.
if user.email == email:
raise forms.ValidationError('New email address cannot be the same \
as your current email address')

return email

最佳答案

我会将您的代码重构为如下所示:

查看:

@login_required
def view(request, extra_context=None, ...):

form = EmailChangeForm(user=request.user, data=request.POST or None)

if request.POST and form.is_valid():
send_email_change_request(request.user,
form.cleaned_data['email'],
https=request.is_secure())
return redirect(success_url)
...

密码验证进入表单:

class EmailChangeForm(Form):
email = ...
old_password = CharField(..., widget=Password())

def __init__(self, user, data=None):
self.user = user
super(EmailChangeForm, self).__init__(data=data)

def clean_old_password(self):
password = self.cleaned_data.get('password', None)
if not self.user.check_password(password):
raise ValidationError('Invalid password')

从 View 中提取逻辑:

 def send_email_change_request(user, new_email, https=True):

site = cache.get_model('sites', 'Site')

email = new_email
verification_key = generate_key(user, email)

current_site = Site.objects.get_current()
site_name = current_site.name
domain = current_site.domain

protocol = 'https' if https else 'http'

# First clean all email change requests made by this user
qs = EmailChangeRequest.objects.filter(user=request.user)
qs.delete()

# Create an email change request
change_request = EmailChangeRequest(
user = request.user,
verification_key = verification_key,
email = email
)
change_request.save()

# Prepare context
c = {
'email': email,
'site_domain': 'dev.tolisto.de',
'site_name': 'tolisto',
'user': self.user,
'verification_key': verification_key,
'protocol': protocol,
}
c.update(extra_context)
context = Context(c)

# Send success email
subject = "Subject" # I don't think that using template for
# subject is good idea
message = render_to_string(email_message_template_name, context_instance=context)

send_mail(subject, message, None, [email])

不要把复杂的东西放在 View 里面(比如渲染和发送邮件)。

关于python - 再次来自用户的 check_password(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4822724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com