Python3 bcrypt,pymongo,flask ValueError:无效的盐

时间:2017-07-31 22:21:44

标签: python flask pymongo bcrypt

我正在尝试使用flask,bcrypt和pymongo创建一个网站,允许您注册帐户并登录。目前注册正在运行,但登录不是。当我点击登录时,我得到this error。 我的代码:

from flask import Flask, render_template, url_for, request, session, redirect
from flask_pymongo import PyMongo
import bcrypt

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'websitetest'
app.config['MONGO_URI'] = 'mongodb://localhost:27017'

mongo = PyMongo(app)


@app.route('/')
def index():
    if 'username' in session:
        return('You are logged in as ' + session['username'])

    return render_template('index.html')


@app.route('/login', methods=['POST'])
def login():
    users = mongo.db.users
    login_user = users.find_one({'name': request.form['username']})

    if login_user:
        if bcrypt.hashpw(bytes(request.form['pass'], 'utf-8'), bytes(request.form['pass'], 'utf-8')) == bytes(request.form['pass'], 'utf-8'):
            session['username'] = request.form['username']
            return redirect(url_for('index'))
    return 'Invalid username/password combination.'


@app.route('/register', methods=['POST', 'GET'])
def register():
    if request.method == 'POST':
        users = mongo.db.users
        existing_user = users.find_one({'name': request.form['username']})

        if existing_user is None:
            hashpass = bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt())
            users.insert({'name': request.form['username'], 'password': hashpass})
            session['username'] = request.form['username']
            return redirect(url_for('index'))

        return('That username already exists!')

    return render_template('register.html')


if __name__ == '__main__':
    app.secret_key = 'mysecret'
    app.run(debug=True)

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

此行未遵循bcrypt的API说明:

if bcrypt.hashpw(bytes(request.form['pass'], 'utf-8'), bytes(request.form['pass'], 'utf-8')) == bytes(request.form['pass'], 'utf-8'):

文档说比较如下:

if bcrypt.hashpw(password, hashed) == hashed:
您环境中的

hashed由代码中的此行表示:

hashpass = bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt())

因此,您需要以某种方式检索hashpass,以便您的代码进行比较:

if bcrypt.hashpw(bytes(request.form['pass'], 'utf-8'), hashpass) == hashpass:

请注意,如果您使用的是more recent version (3x) of bcrypt,则应使用:

bcrypt.checkpw(password, hashed):