检查现有密码并重置密码

Posted

技术标签:

【中文标题】检查现有密码并重置密码【英文标题】:Check existing password and reset password 【发布时间】:2013-05-18 01:09:05 【问题描述】:

views.py 保存密码:

elif 'reset_password' in request.POST:
    if request.POST['reset_password'].strip():
    saveuser = User.objects.get(id=user.id)
    saveuser.set_password(request.POST['reset_password']);
    saveuser.save()
    userform = UserForm(instance=saveuser)
    return redirect('incident.views.about_me')

弹出框获取旧密码和新密码

<div id="overlay_form" style="display:none">
    <form  method="post" action=".">
        % csrf_token %
        <h2>Reset Password</h2><br />
        <table>
      <tr><td>Enter your old password</td><td>
        <input type="text" name="old_password" id="old_password" maxlength="30" /></td></tr>
      <tr><td>Enter your new password</td><td><input type="text" name="new_password" id="new_password" maxlength="30" /></td></tr>
     <tr><td>Confirm your new password</td><td><input type="text" name="reset_password" id="reset_password" maxlength="30" /></td></tr>
      </table>
        <div style="width:180px;float:right;margin:20px 5px 0 10px">
            % include "buttons/save.html" %
            <button style="margin-right:10px;" type="button" id="close" name="cancel" class="forward backicon">
                <img src=" STATIC_URL images/button-icon-ir-back.png"    />
            Cancel</button>
        </div>
    </form>
</div>

我可以保存新密码,但我想知道以下事情

如何检查输入的旧密码与现有密码是否正确。

如何验证新密码字段和确认密码字段。哪种验证更好。

需要帮助。

【问题讨论】:

【参考方案1】:

这是您检查旧密码的方式 - 在set_password 之前,

user.check_password(request.POST['reset_password'])

另外,请通过以下方式检查密码确认。

elif 'reset_password' in request.POST:
    old_password = request.POST['old_password'].strip()
    reset_password = request.POST['reset_password'].strip()
    new_password = request.POST['new_password'].strip()

    if old_password && reset_password && reset_password == new_password:
        saveuser = User.objects.get(id=user.id)
        if user.check_password(old_password):
            saveuser.set_password(request.POST['reset_password']);
            saveuser.save()

            userform = UserForm(instance=saveuser)

        return redirect('incident.views.about_me')

使用form 是一种更好的方法。

【讨论】:

【参考方案2】:

Django 代码检查用户输入的密码是否与实际的旧密码匹配;如果没有,则以 django 形式引发验证错误。此外,如果两个密码匹配,请更新密码。

测试于(Django 1.10,Python 3.4)

forms.py

从 django 导入表单

class changePassForm(forms.Form):

old_password_flag = True #Used to raise the validation error when it is set to False

old_password = forms.CharField(label="Old Password", min_length=6, widget=forms.PasswordInput())
new_password = forms.CharField(label="New Password", min_length=6, widget=forms.PasswordInput())
re_new_password = forms.CharField(label="Re-type New Password", min_length=6, widget=forms.PasswordInput())

def set_old_password_flag(self): 

#This method is called if the old password entered by user does not match the password in the database, which sets the flag to False

    self.old_password_flag = False

    return 0

def clean_old_password(self, *args, **kwargs):
    old_password = self.cleaned_data.get('old_password')

    if not old_password:
        raise forms.ValidationError("You must enter your old password.")

    if self.old_password_flag == False:
    #It raise the validation error that password entered by user does not match the actucal old password.

        raise forms.ValidationError("The old password that you have entered is wrong.")

    return old_password

views.py

def 设置(请求):

if request.user.is_authenticated:

    form = changePassForm(request.POST or None)

    old_password = request.POST.get("old_password")
    new_password = request.POST.get("new_password")
    re_new_password = request.POST.get("re_new__password")

    if request.POST.get("old_password"):

        user = User.objects.get(username= request.user.username)

        #User entered old password is checked against the password in the database below.
        if user.check_password(''.format(old_password)) == False:
            form.set_old_password_flag()

    if form.is_valid():

        user.set_password(''.format(new_password))
        user.save()
        update_session_auth_hash(request, user)

        return redirect('settings')

    else:
        return render(request, 'settings.html', "form": form)

else:
    return redirect('login')

settings.html

<h1>Settings Page</h1>

<h2>Change Password</h2>

<form action="" method="POST">

    % csrf_token %

     form.as_p 

    <input type="Submit" value="Update"></input>

</form>

【讨论】:

【参考方案3】:
<form class="form-horizontal" action="/your_views/reset_password/" method="post">
                            % csrf_token %
                            <div class="form-group">
                                <div class="col-md-12">
                                    <input type="password" placeholder="Old password" id="old_password" name="old_password" autocomplete="off" required class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <input type="password" placeholder="New password" id="password1" name="password1" autocomplete="off" required class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <input type="password" placeholder="Re-new password" id="password2" name="password2" autocomplete="off" required class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-block btn-success" style="background: #00A79D;">Reset</button>
                                </div>
                            </div>                         
                        </form>

【讨论】:

请添加一些关于您的答案的描述。【参考方案4】:

我实现了一个使用 JWT 登录的方法,它的作用是:

    获取随请求发送的电子邮件和密码,并 将其转换为字符串变量 我检查电子邮件是否已经 存在于我制作的自定义用户模型中。 如果用户已经 存在,我将对象模型转换为字典,以便我可以得到 它的特定密码。 因为我匹配密码 对应于用户模型和与发送的密码 发布请求。 如果用户模型中存在电子邮件,并且与该用户模型对应的密码与发布请求发送的密码匹配,我使用 pyJWT 使用我的自定义数据创建 JWT 并返回响应。 在所有其他情况下,电子邮件和密码不匹配,我返回“不匹配”

假设请求是 "email":"xyz@gmail.com", "password":"12345"

    @api_view(['POST'])
    def signin(request):

    email = list(request.data.values())[0] #gets email value from post request "email":"xyz@gmail.com", "password":"123" -> this xyz@gmail.com
    password = list(request.data.values())[1] #gets password value from post request "email":"xyz@gmail.com", "password":"123" -> this 123

    usr = User.objects.filter(email=email).exists() #checks if email exists
    if usr:
      dictionary = User.objects.filter(email=email).values()[0] #converts object to dictionary for accessing data like dictionary["password"] dictionary["first_name"] etc
      if usr and dictionary["password"] == password: #check if email and its corresponing password stored matches the password that is sent
        branch = dictionary["branch"]
        id = dictionary["id"]
        encoded_jwt = jwt.encode('email': email,, 'secret', algorithm='HS256')
        return Response('token':encoded_jwt,'email':email,'branch':branch,'id':id)
      else: 
        return Response('No Match')
    return Response('No Match')

【讨论】:

以上是关于检查现有密码并重置密码的主要内容,如果未能解决你的问题,请参考以下文章

新注册用户将被重定向到密码重置屏幕

使用 jwt 结构重置密码

Linux 忘记root密码并重置root密码

在Drupal中重置密码功能页面没有正确重定向

Flask-登录密码重置

mysql 重置root密码