最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I restrict access to specific pages based on a role system in a flask webapp? - Stack Overflow

programmeradmin0浏览0评论

I saw that some people use Flask Principal for that matter and tried that. How ever I'm new to Webdevelopment and have problems to figure out how the extention works. here is what I got so far:

In the init document of my webapp i declared the decorater and loaded the Principal extention:

admin_required = Permission(RoleNeed("Administrator"))
mod_required = Permission(RoleNeed("Moderator"))
def create_app():
   #some code for the app config...
   Principal(app)

I have a auth document where i got the backend regarding the sign up and login through flask login and sql alchemy. I went on and added the following code in my login and logout function as well as the identity_loaded decorater:

#user is a database object with an attribute role which is a Enum class with the values "Benutzer"(user) "Moderator"(mod) and "Administrator"(admin)
@auth.route("/login", methods=['GET', 'POST'])
def login():
   #code for password check etc.
   login_user(user, remember=True)
   if (user.role.value != "Benutzer"):
      identity = Identity(user.role.value)
      identity_changed.send(current_app, identity=identity)

@auth.route("/logout")
@login_required
def logout():
   session.clear()
   logout_user()
   identity_changed.send(current_app, identity=AnonymousIdentity())

@identity_loaded.connect_via(current_app)
def on_identity_loaded(sender, identity):
    if identity.name == admin_required:
        identity.provides.add(RoleNeed("Administrator"))
    elif identity.name == mod_required:
        identity.provides.add(RoleNeed("Moderator"))

I than go on and use the Principal like this:

@restrictedArea.route("/benutzer", methods=["GET", "POST"])
@login_required
@admin_required.require(http_exception=403)

The decorater does work how ever I'm unable to get the required RoleNeed to access the pages even with useres that should have the rights to do so.

If someone could give me an explanation what all the classes and methodes regarding the Principal extention do that would be a big help as i just dont understand the documentation. Thank you in regard.

发布评论

评论列表(0)

  1. 暂无评论