再次来自用户的check_password()

cra*_*ter 21 python authentication django web

我有以下表格.在用户最终更改其电子邮件之前,如何再次检查用户的密码.即使他已登录,我只想确定它真的是用户.只是一个安全的事情.

我该怎么做.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
Run Code Online (Sandbox Code Playgroud)

Ski*_*Ski 23

我会重构你的代码看起来像这样:

视图:

@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)
    ...
Run Code Online (Sandbox Code Playgroud)

密码验证形式如下:

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')
Run Code Online (Sandbox Code Playgroud)

从视图中提取逻辑:

 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])
Run Code Online (Sandbox Code Playgroud)

不要在视图中放置复杂的内容(例如渲染和发送电子邮件).


Yuj*_*ita 9

我觉得你回答了自己的问题:)

check_password方法的文档在这里:http: //docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.check_password

success = user.check_password(request.POST['submitted_password'])
if success: 
   # do your email changing magic
else:
   return http.HttpResponse("Your password is incorrect") 
   # or more appropriately your template with errors
Run Code Online (Sandbox Code Playgroud)

由于您已经将request.user传递给表单构造函数(看起来您已经__init__因为自己的原因而重写),因此您可以毫无困难地将所有逻辑放在表单中.

class MyForm(forms.Form):
     # ...
     password = forms.CharField(widget=forms.PasswordInput)

     def __init__(self, user, *args, **kwargs):
          super(MyForm, 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
Run Code Online (Sandbox Code Playgroud)

看到你的表格后更新

好.主要问题是__init__已经定义了两次,使得第一个语句无用.我看到的第二个问题是,我们会在不需要的user时候进行多次查询.

我们已经偏离了你原来的问题,但希望这是一次学习经历.

我只改变了一些事情:

  • 删除了额外的__init__定义
  • 更改__init__为接受User实例而不是文本username
  • User.objects.get(username=username)从我们传入用户对象后删除了查询.

只记得传递表单构造函数user=request.user而不是username=request.user.username

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

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

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

    def clean_email(self):
        email = self.cleaned_data.get('email')

        # no need to query a user object if we're passing it in anyways.
        user = self.user 

        # 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
Run Code Online (Sandbox Code Playgroud)

最后,因为我们在这里谈论好的做法,我建议您遵循Skirmantas关于将当前视图代码移动到表单方法的建议,以便您可以简单地调用myform.send_confirmation_email.

听起来很棒!

  • 真棒!我很高兴你在学习新东西.init.py?`__init __.py`告诉python该文件夹与python有关.首次创建python对象时调用`__init__`方法.http://docs.python.org/reference/datamodel.html#object.__init__这是我们初始化类(`init`)时触发的代码.form = MyForm()< - 调用__init__.`super()`确保父类的__init__也被调用.啊发现了一篇SO帖子:http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do (2认同)