1

我想知道如何通过比较数据库中的用户名和密码来登录烧瓶中的用户。如果错误是用户名不存在闪烁“用户不存在”如果该密码与用户密码不匹配闪烁“worng passsword”并且成功闪烁“您已登录”

现在我有这个代码。

if request.method == 'POST':
    if request.form['username'] != app.config['USERNAME']:
        error = 'Invalid username'
    elif request.form['password'] != app.config['PASSWORD']:
        error = 'Invalid password'
    else:
        session['logged_in'] = True
        flash('You were logged in')
        return redirect(url_for('show_entries'))

我想从 db 更改用户名和密码检查而不是 app.config

4

1 回答 1

4

使用Flask-SQLAlchemy,然后简单地检查您的数据库中是否有匹配的用户。此外,使用bcrypt对密码进行哈希处理。在任何情况下都不能以明文形式存储密码。

user = User.query.filter_by(username=request.form['USERNAME']).first()
if not user:
    error = 'Invalid username'
elif bcrypt.hashpw(request.form['password'], user.password) != hashed:
    error = 'Invalid password'
else:
    session['user_id'] = user.id  # makes more sense than storing just a bool
    flash('You were logged in')
    return redirect(url_for('show_entries'))

当然,您可能需要先定义您的用户表。这是一个例子:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, unique=True)
    password = db.Column(db.String)

为了使实际用户可用,我建议您使用 before_request 函数,该函数在用户登录时检查并存储session['user_id']User.query.get(session['user_id'])g.user

于 2013-11-10T12:18:45.793 回答