ByteSize
ByteSize

Reputation: 5

Python3 bcrypt, pymongo, flask ValueError: Invalid salt

I am trying to create a website using flask, bcrypt and pymongo that allows you to register an account and login. Currently register is working but login is not. When I click login I get this error. My code:

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)

Any help would be greatly appreciated. Thanks!

Upvotes: 0

Views: 2172

Answers (1)

JacobIRR
JacobIRR

Reputation: 8946

This line is not following the API description of bcrypt:

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

The docs say to compare like so:

if bcrypt.hashpw(password, hashed) == hashed:

hashed in your environment is represented by this line in your code:

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

So you need to retrieve hashpass in some way so your code compares thusly:

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

Note that if you are using a more recent version (3x) of bcrypt, you should use:

bcrypt.checkpw(password, hashed):

Upvotes: 2

Related Questions