gpt4 book ai didi

python - Flask-Login & Flask-Principle 认证用户掉落到 flask_login.AnonymousUserMixin

转载 作者:行者123 更新时间:2023-11-28 19:23:46 25 4
gpt4 key购买 nike

我有两个问题

  1. 我的经过身份验证的用户不断下降到 flask_login.AnonymousUserMixin
  2. 我使用 Flask-Login 和 Flask-Principal 收到意外信号

尝试获取 protected /projects/10 URL@admin_permission.require(http_exception=403)

这是我的控制台输出:

127.0.0.1 - - [30/Jul/2013 16:22:58] "GET /projects/10 HTTP/1.1" 302 -
127.0.0.1 - - [30/Jul/2013 16:22:58] "GET /login HTTP/1.1" 200 -

进入登录表单(到目前为止一切正常)。输入有效的登录名和密码并获得疯狂的信号和行为不是我所期望的:

127.0.0.1 - - [30/Jul/2013 16:24:06] "POST /login HTTP/1.1" 302 -
<Employee('103','Dmitry Semenov')>
<Identity id="103" auth_type="None" provides=set([Need(method='role', value='manager'), Need(method='id', value=103L), Need(method='role', value='admin')])>
<flask_login.AnonymousUserMixin object at 0x03258790>
<Identity id="103" auth_type="None" provides=set([])>
127.0.0.1 - - [30/Jul/2013 16:24:06] "GET /projects/10 HTTP/1.1" 302 -
<flask_login.AnonymousUserMixin object at 0x03342AF0>
<Identity id="103" auth_type="None" provides=set([])>
127.0.0.1 - - [30/Jul/2013 16:24:06] "GET /login HTTP/1.1" 200 -
<flask_login.AnonymousUserMixin object at 0x03342E90>
<Identity id="103" auth_type="None" provides=set([])>

如您所见,我得到 current_user 指向有效的 Employee 实例(类)和身份 id=103,但由于某种原因它立即变成了 flask_login.AnonymousUserMixin,然后身份验证系统通过了该用户并且不允许我打开/projects/10 网址。

任何想法有什么问题吗?以及为什么我收到那么多信号 - 根据代码,它们应该只在成功登录时发生。我错过了什么?

源代码:

# flask-principal
principals = Principal()
normal_role = RoleNeed('normal')
normal_permission = Permission(normal_role)
admin_permission = Permission(RoleNeed('admin'))
principals._init_app(app)

login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(userid):
return mysqlsess.query(Employee).get(userid)


@app.route("/")
@app.route("/dashboard")
def vDashboard():
return render_template('dashboard.html')

@app.route('/projects')
def vPojects():
return "Projects"


@app.route('/projects/<ID>')
@admin_permission.require(http_exception=403)
def vProject(ID):
return current_user.roles[1]

# somewhere to login
@app.route('/login', methods=['GET', 'POST'])
def login():
# A hypothetical login form that uses Flask-WTF
form = LoginForm()

# Validate form input
if form.validate_on_submit():
# Retrieve the user from the hypothetical datastore
user = mysqlsess.query(Employee).get(form.email.data)

# Compare passwords (use password hashing production)
if form.password.data == str(user.ID):
# Keep the user info in the session using Flask-Login
login_user(user)
# Tell Flask-Principal the identity changed
identity_changed.send(app,
identity=Identity(user.ID))
return redirect(session['redirected_from'] or '/')
else:
return abort(401)

return render_template('login.html', form=form)


# somewhere to logout
@app.route("/logout")
def logout():
logout_user()

for key in ['identity.name', 'identity.auth_type', 'redirected_from']:
try:
del session[key]
except:
pass
return Response('<p>Logged out</p>')


# handle login failed
@app.errorhandler(401)
def page_not_found(e):
return Response('<p>Login failed</p>')


@app.errorhandler(403)
def page_not_found(e):
session['redirected_from'] = request.url
return redirect(url_for('login'))


@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
identity.user = current_user
print identity.user


if hasattr(current_user, 'ID'):
identity.provides.add(UserNeed(current_user.ID))

if hasattr(current_user, 'roles'):
for role in current_user.roles:
identity.provides.add(RoleNeed(role))

print identity


class LoginForm(Form):
email = TextField()
password = PasswordField()

if __name__ == "__main__":
app.run()

还有我的 Employee SQLAlchemy 类

class Employee(Base):

__tablename__ = "Employees"

# Properties
ID = Column(BigInteger, primary_key=True)
name = Column(VARCHAR(255), nullable=False)
created = Column(DateTime, nullable=False, default=datetime.now())
updated = Column(DateTime)
deleted = Column(DateTime)
branchID = Column(BigInteger, ForeignKey('Branches.ID'), nullable=False)
departmentID = Column(BigInteger, ForeignKey('Departments.ID'), nullable=False)
utilization = Column(SmallInteger, nullable=False, default=1)
statusID = Column(Enum('active', 'fired', 'vacation'), default='active')
birthday = Column(Date)

# Relationships
Branch = relationship("Branch")
Department = relationship("Department")
ProjectStat = relationship("ProjectStat", lazy="dynamic")

roles = ["admin", "manager"]

# Methods
def zzz(self):
session = object_session(self)

stats = self.ProjectStat.filter(and_(ProjectStat.metricID=='hb', ProjectStat.metricValue>=6)).all()
for s in stats:
print s.metricValue

# Constructor
def __init__(self, ID, name):
self.ID = ID
self.name = name

# Friendly Print
def __repr__(self):
return "<Employee('%s','%s')>" % (self.ID, self.name)

def is_active(self):
return True

def get_id(self):
return unicode(self.ID)

def is_authenticated(self):
return True

def is_anonymous(self):
return False

最佳答案

登录后需要实例化原理

这是一个重复问题,请参阅此处 Flask Login and Principal - current_user is Anonymous even though I'm logged in

关于python - Flask-Login & Flask-Principle 认证用户掉落到 flask_login.AnonymousUserMixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17959320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com