Hi everyone,

I think I just need a little guidance on this one.

I have been following along with Pretty Printed’s Youtube tutorial for a Flask MongoDB login set up ( https://www.youtube.com/watch?v=vVx1737auSE ).

The registration part works fine –

@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_one({'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')

but for some reason, I can’t log back in with the registered user

@app.route('/')
def index():
    if 'username' in session:
        return redirect(url_for('warehouse'))

    return render_template('index.html')


@app.route('/login', methods=['POST', 'GET'])
def log_in():
    if 'username' in session:
        return render_template('warehouse_calendar.html')

    return render_template('login.html')

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

    if login_user:
        if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password'].encode('utf-8')) == login_user['password'].encode('utf-8'):
            session['username'] = request.form['username']
            return redirect(url_for('warehouse'))

    return 'Invalid username/password combo'

When I try to log in, I get the following –

r/webdev - Help with Flask Login (with MongoDB)

According to the comments under the Youtube video, if you are using Python3, you shouldn’t have .encode(‘utf-8’) in this line

if bcrypt.hashpw(request.form[‘pass’].encode(‘utf-8’), login_user[‘password’].encode(‘utf-8’)) == login_user[‘password’].encode(‘utf-8’):

However if I take it out I get a unicode error

r/webdev - Help with Flask Login (with MongoDB)

I can’t work out where I’ve gone wrong so any advice would be appreciated.

Thank you!



Source link

Write A Comment