Flask-AppBuilder icon indicating copy to clipboard operation
Flask-AppBuilder copied to clipboard

Question: how to access userinfo or current user.

Open awsumco opened this issue 1 year ago • 2 comments

This is more of a question than issue and hopefully and add-on to your awesome docs, I would not normally if asked if I did not look and try before hand.

What I am trying to do is load a page baed on the role of the user when they are logged, however I am stamped at getting the current_user or the userinfo.

In short I am asking is there some global var or function to get the above info or do I pull it from the session cookies.

Pointing me in the right direction would be awesome.

awsumco avatar May 19 '23 15:05 awsumco

you can do this in multiple ways, g.user holds the current user session, you can pass that to jinja2 and render a custom page, or use a REST API to do it

dpgaspar avatar May 25 '23 10:05 dpgaspar

For test what roles the current user has, I found it convenient to get string names of the roles in a list...

with this function:

# in sec.py
from flask import g

def get_user_role_list() -> list:
    """
    :return: list of str of names of Roles of g.user, empty list if no login
    """
    if "user" not in g:
        return []
    try:
        if g.user.is_anonymous:
            return []
    except AttributeError:
        return []
    return [str(r) for r in g.user.roles]

available to jinja because:

# in app.py
app.add_template_global(name="get_user_role_list", f=sec.get_user_role_list)

then in a template:

{% if 'Registered' in get_user_role_list() %} . . .

soundmaking avatar May 28 '23 15:05 soundmaking