Django如何比较存储的哈希密码和普通密码

pjngdqdw  于 2023-03-09  发布在  Go
关注(0)|答案(3)|浏览(147)

我是Django新手,我创建了一个函数来允许管理员创建用户帐户。我使用了一个密码生成器+ make_password()函数来散列密码。
现在,它将普通密码发送到用户的电子邮件中,并将其散列存储在数据库中。
现在用户只能用散列密码登录。
我的view.py:

@admin_login_required
def add_emp(request):
    if request.method == 'POST':
        user_name = request.POST['user_name']
        user_email = request.POST['user_email']
        user_otj = request.POST['user_otj']
        user_password = pwo.generate()
        user_password1 = make_password(user_password)
        empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj)
        if empObj:
            subject = 'Login Info'
            message = f'Name : {user_name}, \n Email : {user_email}, \n Password : {user_password} \n FROM - AA Portal'
            email_from = settings.EMAIL_HOST_USER
            send_mail(subject, message, email_from, [user_email])
            messages.success(request, "Employee was added successfully!")
            return HttpResponseRedirect('/create-emp')
        else:
            messages.error(request, "Some error was occurred!")
            return HttpResponseRedirect('/create-emp')
    return render(request, 'AddEmp.html')

def user_login(request):
    if request.method == "POST":
        user_email = request.POST['user_email']
        user_password = request.POST['user_password']
        user_details = User.objects.filter(user_email=user_email).values()
        hashed_pw = User.objects.all().first().user_password
        checkpass = check_password(user_password, hashed_pw)

        if user_details and checkpass:
            request.session['logged_in'] = True
            request.session['user_email'] = user_details[0]["user_email"]
            request.session['u_id'] = user_details[0]["user_email"]
            request.session['user_name'] = user_details[0]["user_name"]
            request.session['u_type'] = "emp"
            return HttpResponseRedirect('/user_index')
        else:
            return render(request, 'EmpLogin.html', {'msg': "0"})
    else:
        return render(request, 'EmpLogin.html')

用户模型:

class User(models.Model):
    user_email = models.CharField(primary_key=True, max_length=100)
    user_role_id = models.CharField(max_length=20)
    user_password = models.CharField(max_length=20)
    user_name = models.CharField(max_length=100)
    user_avatar_path = models.CharField(max_length=300)
    user_job_title = models.TextField(blank=True, null=True)
    user_educ_qual = models.TextField(blank=True, null=True)
    user_companies = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'user'

知道如何让用户使用普通密码登录并在数据库中保持散列吗?

b0zn9rqh

b0zn9rqh1#

在这里你应该找到你需要的一切。你需要一个密码字段为您的用户,这应该是明确的。
如果您希望通过比较纯文本密码和数据库中的散列密码来手动验证用户,请使用便捷的函数check_password(),它需要两个强制参数:要检查的纯文本密码,以及要检查的数据库中用户密码字段的完整值。如果它们匹配,则返回True,否则返回False。
它的工作原理是这样的:
views.py

from django.contrib.auth.hashers import check_password

[...]
plain_pw_from_post = form.cleaned_data.get(...)
hashed_pw_from_usermodel = User.objects.all().first().password

if check_password(plain_pw_from_post, hashed_pw_from_usermodel):
    # insert your login logic here
else:
    # login failed logic here
[...]

OP共享其用户模型的代码后编辑:

看看这个:Django的用户模型很可能你想从那个模型继承你的自定义用户模型!它已经给了你很多功能。正如你在链接中看到的,它也已经有了密码。如果你从那里继承了你的模型,你也可以很容易地使用authenticate函数,就像对你问题的另一个回答中描述的那样。
models.py

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    user_role_id = models.CharField(max_length=20)
    user_avatar_path = models.CharField(max_length=300)
    user_job_title = models.TextField(blank=True, null=True)
    user_educ_qual = models.TextField(blank=True, null=True)
    user_companies = models.TextField(blank=True, null=True)

替换电子邮件,用户名和密码字段,因为通过继承AbstractUser,我们已经有了这些。
views.py

from django.contrib.auth import authenticate

def user_login(request):
    if request.method == "POST":
        posting_user = User.objects.get_or_404(username=request.POST['username'])
      #  if check_password(request.POST['password'], posting_user.password):
          
        user = authenticate(username=posting_user.username, password=request.POST['password'])
        if user is not None:
            return HttpResponseRedirect('/user_index')
        else:
            return render(request, 'EmpLogin.html', {'msg': "0"})
    else:
        return render(request, 'EmpLogin.html')

请阅读此“普通”django authentication用户。

ny6fqffe

ny6fqffe2#

请使用autenticate方法验证用户。

from django.contrib.auth import authenticate

def user_login(request):
   if request.method == "POST":
    user_email = request.POST.get('user_email')
    user_password = request.POST.get('user_password')
    user_details = authenticate(request, email=user_email, password=user_password)
    
    if user_details is not None:
        request.session['logged_in'] = True
        request.session['user_email'] = user_details.email
        request.session['u_id'] = user_details.id
        request.session['user_name'] = user_details.username
        request.session['u_type'] = "emp"
        return HttpResponseRedirect('/user_index/')
    else:
        return render(request, 'EmpLogin.html', {'msg': "0"})
else:
    return render(request, 'EmpLogin.html')
bxjv4tth

bxjv4tth3#

修复代码终于它的工作我想我会分享:

def user_login(request):
    if request.method == "POST":
        user_email = request.POST['user_email']
        user_password = request.POST['user_password']
        user_details = User.objects.filter(user_email=user_email).values()
        hashed_pw = User.objects.all().first().user_password
        check_password(user_password, hashed_pw)

        if user_details:
            request.session['logged_in'] = True
            request.session['user_email'] = user_details[0]["user_email"]
            request.session['u_id'] = user_details[0]["user_email"]
            request.session['user_name'] = user_details[0]["user_name"]
            request.session['u_type'] = "emp"
            return HttpResponseRedirect('/user_index')
        else:
            return render(request, 'EmpLogin.html', {'msg': "0"})
    else:
        return render(request, 'EmpLogin.html')

相关问题