Tyler
Tyler

Reputation: 47

Flask and Auth0 - How to check if user is authenticated in Jinja

I'm using Auth0 for authentication in my Flask application, and wondering how to check if the user is authenticated in the Jinja template.

I'm wondering if there's a way to do something similar to how LoginManager does it:

{% if current_user.is_anonymous %} #<-- This here
<li><a href="{{ url_for('login') }}">Login</a></li>
{% else %}
<li><a href="{{ url_for('user', username=current_user.username) }}">Profile</a></li>
<li><a href="{{ url_for('logout') }}">Logout</a></li>
{% endif %}

Upvotes: 0

Views: 1348

Answers (1)

cizario
cizario

Reputation: 4254

you have two options:

  • using the global g object which is automatically available in templates with the before_app_request hook, read more on the official Flask tutorial:
@bp.before_app_request
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.user``."""
    user_id = session.get("user_id")

    if user_id is None:
        g.user = None
    else:
        g.user = (
            get_db().execute("SELECT * FROM user WHERE id = ?", (user_id,)).fetchone()
        )

and then in your template :

{% if g.user %}
  <li><span>{{ g.user['username'] }}</span>
  <li><a href="{{ url_for('auth.logout') }}">Log Out</a>
{% else %}
  <li><a href="{{ url_for('auth.register') }}">Register</a>
  <li><a href="{{ url_for('auth.login') }}">Log In</a>
{% endif %}
  • inject your current_user object to the context processor, flask-login is your good inspiration (without decorator) :
[..]

def _get_user():
    if has_request_context() and not hasattr(_request_ctx_stack.top, 'user'):
        current_app.login_manager._load_user()

    return getattr(_request_ctx_stack.top, 'user', None)

[..]

def _user_context_processor():
    return dict(current_user=_get_user())

and then get the current app (maybe you'll need to import current_app object in your case)

[..]
    app.context_processor(_user_context_processor)

then you can use the current_user like :

{% if current_user.is_anonymous %} #<-- This here
<li><a href="{{ url_for('login') }}">Login</a></li>
{% else %}
<li><a href="{{ url_for('user', username=current_user.username) }}">Profile</a></li>
<li><a href="{{ url_for('logout') }}">Logout</a></li>
{% endif %}

Upvotes: 1

Related Questions