我如何使用Bcrypt。试着看看实际代码是什么样的

时间:2017-04-05 12:33:07

标签: python django authentication passwords bcrypt

我的问题,我在哪里以及如何在django / python中实现Bcrypt。 我还在学习。我已经阅读了文档。我加你了 在settings.py中但在实际代码中的哈希行。这就是我所拥有的 我的models.py和views.py。我知道我的错误。当我尝试 登录,我可以输入任何密码,它会让我登录。所有和任何 帮助将不胜感激。提前谢谢。

models.py

from __future__ import unicode_literals 
from django.db import
models from django.contrib 
import messages
import bcrypt<br>
import re from django.conf 
import settings
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')

class UserManager(models.Manager):
    def validate(self, data):
    flag = True
    errs = []

    if len(data['first_name']) < 2:
        flag = False
        errs.append("First cannot be less than 2 characters.")

    if not data['first_name'].isalpha():
            flag = False
            errs.append("First name must not contain numbers.")

    if len(data['last_name']) < 2:
            flag = False
            errs.append("Last cannot be less than 2 characters.")

    if not data['last_name'].isalpha():
            flag = False
            errs.append("Last name must not contain numbers")

    if not EMAIL_REGEX.match(data['email']):
            flag = False
            errs.append("This is an invalid email.")

    if data['pass'] != data['c_pass']:
            flag = False
            errs.append("Your passwords do not match.")

    if flag:
        # messages.success(request, "Success! Welcome, " + userInfo['first_name'] + "!")
        hashed = bcrypt.hashpw(data['pass'].encode(), bcrypt.gensalt())
        user = User.objects.create(first_name = data['first_name'], last_name = data['last_name'], email = data['email'], password = hashed)
        # print data
        return (True, user)

    else:
        return(False, errs)

def l_process(self,data):
    flag = True
    errs = []
    suspect_user = User.objects.filter(email=data['email'])


    if suspect_user:
        hashed = User.objects.get(email = data['email']).password
        hashed = hashed.encode('utf-8')
        password = data['pass']
        password = password.encode('utf-8')
        if bcrypt.hashpw(password, hashed) == hashed:
            # messages.success(request, "Success! Welcome, " + User.objects.get(email = data['email']).first_name + "!")

            print suspect_user
            flag = True
        else:
            # messages.warning(request, "Unsuccessful login. Incorrect password")
            passFlag = False
            errs.append("Unsuccessful login. Incorrect Password")
    else:
        # messages.warning(request, "Unsuccessful login. Your email is incorrect.")
        passFlag = False
        errs.append("Unsuccessful login. Your email is incorrect.")

    print suspect_user
    return (True, suspect_user[0])

class User(models.Model):
    first_name = models.CharField(max_length=45)
    last_name = models.CharField(max_length=45)
    email = models.EmailField(max_length=45)
    password = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

objects = UserManager() #object UserManager is created and inherits attributes of User
在views.py 中

from django.shortcuts import render, redirect 
from django.contrib
import messages 
from .models import User 
from django.core.urlresolvers import reverse


def index(request):
    return render(request, 'lr_templates/index.html')

def r_process(request):
    data = {
        "first_name" : request.POST['first'],
        "last_name" : request.POST['last'],
        "email" : request.POST['email'],
        "pass" : request.POST['pass'],
        "c_pass" : request.POST['c_pass']
    }

    result = User.objects.validate(data)
    if result[0]:
        # print "*" * 20
        request.session['user_id'] = result[1].id
        # print "*" * 20
        return redirect("/success")
    else:
        for err in result[1]:
        messages.error(request, err)
        return redirect("/")

def l_process(request):
    data = {
        "email": request.POST['email'],
        "pass": request.POST['pass'],
    }

    result = User.objects.l_process(data)

     if result[0]:
         request.session['user_id'] =result[1].id
         return redirect("/success")
    else:
        for err in result[1]:
            messages.error(request, err)
        return redirect("/")

def success(request):
    user_obj = User.objects.get(id=request.session['user_id'])
    context = {
       "user" : user_obj
    }
    return render(request, "lr_templates/success.html", context)

def logout(request):
    request.session.clear()
    return redirect("/")

1 个答案:

答案 0 :(得分:0)

我同意阿拉斯戴尔的意见。

Django有一个内置的登录模块。使用它会更容易。

您应该导入到您的项目中。你可以在这里阅读更多相关信息:

https://docs.djangoproject.com/en/1.10/ref/contrib/auth/

如果您需要扩展模型(添加更多信息),也可以。

https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model