2017-07-31 135 views
0

我想創建一個網站使用燒瓶,bcrypt和pymongo,允許您註冊一個帳戶和登錄。目前註冊正在工作,但登錄不是。當我點擊登錄時,我得到this error。 我的代碼:python3 bcrypt,pymongo,flask ValueError:無效的鹽

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) 

任何幫助將不勝感激。謝謝!

+0

任何原因,您鹽(第二個參數'brcypt.hashpw() ')是來自[bcrypt文檔](https://pypi.python.org/pypi/bcrypt/3.1.0)的一個字節編碼密碼(在'if login_user'下)而不是'bcrypt.gensalt()'。 ?另外,你應該使用'brcypt.checkpw(密碼,散列)'來自同一個鏈接。 – jarcobi889

回答

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): 
+1

我知道你不應該這樣做,但非常感謝你!我一直在努力解決這個問題! – ByteSize