为什么我的current_user不通过flask-login进行身份验证? [英] Why isn't my current_user authenticated in flask-login?
问题描述
我的目标是使主视图(/
)成为登录页面.用户登录后,将根据其角色呈现另一个页面.登录(/auth
)时,看到正确输入了用户名和密码.然后,它尝试呈现/
,它告诉我我的用户未通过身份验证并呈现/login
.以下是描述此情况的视图:
My goal is to make my home view (/
) a login page. Once the user logs in, a different page is render depending on its role. When I login (/auth
), I see that the username and password are correctly entered. It then attempts to render /
, where it tells me that my user is not authenticated and renders /login
. Here are the views that describe this:
@app.route("/login")
def login():
return flask.render_template('login.html')
@app.route("/", methods=["GET"])
def home():
if current_user.is_authenticated:
if current_user.is_admin():
return flask.render_template('admin_index.html')
return flask.render_template('user_index.html')
logger.info("Not authenticated. Going back to login.")
return flask.render_template('login.html')
@app.route("/auth", methods=["POST"])
def auth():
username = request.form['username']
password = request.form['password']
user = db.session.query(User).filter(User.username == username).first()
logger.info(user)
logger.info("{0}: {1}".format(username, password))
print("user exists? {0}".format(str(user != None)))
print("password is correct? " + str(user.check_password(password)))
if user and user.check_password(password):
user.is_authenticated = True
login_user(user)
return flask.redirect(url_for('home'))
return flask.redirect(url_for('login'))
问题是我尝试登录后flask-login的current_user.is_authenticated
始终返回False
.我创建的用户已正确创建并提交到数据库.以下是我的用户模型,根据烧瓶登录提供了必要的方法:
The problem is that flask-login's current_user.is_authenticated
is always returning False
after I attempt to login. My created user is correctly created and committed to the database. Below is my User model with the necessary methods as per flask-login:
class User(db.Model):
"""
A user. More later.
"""
__tablename__ = 'User'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(128), unique=True)
hashed_password = db.Column(db.String(160))
admin = db.Column(db.Boolean)
def __init__(self, username, password="changeme123", admin=False):
self.username = username
self.set_password(password)
self.admin = admin
self.is_authenticated = False
def is_active(self):
return True
def is_authenticated(self):
return self.is_authenticated
def is_anonymous(self):
return False
def is_admin(self):
return self.admin
def get_id(self):
return self.id
def __repr__(self):
return '<User {0}>'.format(self.username)
def set_password(self, password):
self.hashed_password = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.hashed_password, password)
这是load_user
函数:
@login_manager.user_loader
def load_user(user_id):
try:
return User.query.get(User.id==user_id)
except:
return None
为什么current_user.is_authenticated
返回False
?我以为login_user(user)
会成为current_user == user
,即正在/auth
中进行身份验证的人,但似乎并非如此.
Why is current_user.is_authenticated
returning False
? I presumed that login_user(user)
would make current_user == user
, i.e., the one who is being authenticated in /auth
, but it seems this is not the case.
推荐答案
您有一个名为User.is_authenticated
的方法.但是,在User.__init__
内部,您设置了一个具有相同名称的属性.
You have a method named User.is_authenticated
. Inside User.__init__
, though, you set an attribute with the same name.
self.is_authenticated = False
这将覆盖方法.然后,每当您选择current_user.is_authenticated
时,您都将访问始终为false的属性.
This overrides the method. Then, whenever you check current_user.is_authenticated
, you are accessing the attribute that's always false.
您应从__init__
中删除分配,然后将is_authenticated
更改为以下内容:
You should remove the assignment from __init__
and change is_authenticated
to the following:
def is_authenticated(self):
return True
如果出于某种原因需要动态设置,请重命名属性,以免影响方法.
If you need it to be dynamic for some reason, rename the attribute so it doesn't shadow the method.
def is_authenticated(self):
return self._authenticated
另一个问题是您的load_user
函数.
Another problem is with your load_user
function.
您正在get
对其进行替换,而不是User.id==user_id
的filter
.未返回用户,因为load_user
返回的是User.query.get(True)
而不是User.query.get(user_id)
.
Instead of filter
ing for User.id==user_id
, you are get
ting it. The user wasn't being returned because load_user
is returning User.query.get(True)
instead of User.query.get(user_id)
.
如果进行以下更改,它将起作用:
If you make the following change, it will work:
@login_manager.user_loader
def load_user(user_id):
try:
return User.query.get(user_id)
except:
return None
这篇关于为什么我的current_user不通过flask-login进行身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!