Flask-AppBuilder
Flask-AppBuilder copied to clipboard
Question: how to access userinfo or current user.
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.
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
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() %} . . .