我试图用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'
我必须如何存储密码?我必须如何比较密码?(从数据库针对表单传入值(
感谢您的指导
你的方法非常复杂,你可以很容易地这样做:
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.
...