我正在尝试使用Python / Django / MongoDB创建登录系统。
这是我的代码
from django.shortcuts import render
from pymongo import MongoClient
import bcrypt
def login( req ):
response = { 'error': 'Error' }
if req.POST['username'] and req.POST['password']:
u = req.POST['username']
p = req.POST['password'].encode('utf8')
client = MongoClient()
result = client['db']['users'].find_one({'name': u})
if result:
hashed = bcrypt.hashpw( result['password'].encode('utf8'), bcrypt.gensalt() )
if bcrypt.checkpw( p, hashed ):
response = { 'error': 'Welcome!' }
else:
response = { 'error': 'Invalid password' }
else:
response = { 'error': 'Invalid username' }
else:
response = { 'error': 'Password/Username empty' }
return render( req, 'crawler/login.html', response )
我该如何使用bcrypt.checkpw()
我这样存储密码$2b$12$tapbosJdMHGCnO6zb.n7Wu3acXyBh4Cj2jdJGv.1TmMBWYtd.nnWW
,而测试的真实密码为'password'
,我该如何存储密码?我该如何比较密码? (从数据库对照表单的传入值)
感谢您的指导
答案 0 :(得分:0)
您的方法非常复杂,您可以轻松地做到这一点:
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...