简体   繁体   中英

Flask-Login How to check if a user has a certain attribute value

i am currently using flask-login for the Authentication of my website. My Model is a simple User (with id, mail etc) which has an admin(boolean) attribute. I dont need more than 2 Roles.

Is there any way to check after a route was called, if the current user has the value "True" at the admin attribute?

I tried solving this issue with trying out custom decorator, as well as accessing session['admin'] , but it did not work.

As @Agung Wiyono commented Flask-Login provides a current_user variable, see docs .

In your route you can do something like:

from flask_login import current_user

@app.route("/test")
@login_required
def test():

    if current_user.admin:
        print('user is admin')

    #  blah blah

If you don't want to use the login_required decorator:

@app.route("/test")
def test():

    if current_user.is_authenticated and current_user.admin:
        print('user is authenticated and is an admin')

    #  blah blah

If you want to use a decorator to check if the current_user admin value is True :

def admin_role_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if request.method in EXEMPT_METHODS:
            return func(*args, **kwargs)
        elif not current_user.admin:
            abort(403)
        return func(*args, **kwargs)
    return decorated_view

This code is more or less the code of @login_required , except it checks the state of the admin attribute - see source .

And use as below. Note the order of the decorators is important. @login_required is called first then @admin_role_required is called. Decorator admin_role_required assumes the current_user is already authenticated. If admin_role_required was called first then the current_user proxy would not have an attribute admin and you'd have an error.

@app.route("/test")
@admin_role_required
@login_required
def test():

    #  need to be logged in and admin be True to get here
    
    #  blah blah

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM