我很难使用 Flask-Login 框架进行身份验证。我已经尽可能彻底地查看了文档,但显然我遗漏了一些明显的东西。
class User():
def __init__(self, userid=None, username=None, password=None):
self.userid = userid
self.username = username
self.password = password
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.userid)
def __repr__(self):
return '<User %r>' % self.username
def find_by_username(username):
try:
data = app.mongo.db.users.find_one_or_404({'username': username})
user = User()
user.userid = data['_id']
user.username = data['username']
user.password = data['password']
return user
except HTTPException:
return None
def find_by_id(userid):
try:
data = app.mongo.db.users.find_one_or_404({'_id': userid})
user = User(data['_id'], data['username'], data['password'])
return user
except HTTPException:
return None
以上是我的用户类位于users/models.py
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'users.login'
@login_manager.user_loader
def load_user(userid):
return find_by_id(userid)
以上是我的用户加载器。
@mod.route('/login/', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
pw_hash = hashlib.md5(form.password.data).hexdigest()
user = find_by_username(form.username.data)
if user is not None:
if user.password == pw_hash:
if login_user(user):
flash('Logged in successfully.')
return redirect(request.args.get('next') or url_for('users.test'))
else:
flash('Error')
else:
flash('Username or password incorrect')
else:
flash('Username or password incorrect')
return render_template('users/login.html', form=form)
没有明显的错误消息,但是当尝试访问任何用 装饰的视图时@login_required
,它会将我重定向到登录表单。据我所知,该login_user
函数实际上并没有工作,尽管它True
在我调用它时返回。任何建议表示赞赏。