Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Security login and logout in menu bar

Currently I use the following code to display the login and logout links on the menu bar in my Flask-Admin project:

admin.add_link(MenuLink(name='Logout', category='', url="/logout"))
admin.add_link(MenuLink(name='Login', category='', url="/login"))

However, this will display both regardless of whether the current user is logged in or not. Is it possible to get it to display logout when logged in and login when logged out?


1 Answers

Looking at the menu template definitions in Flask-Admin (layout.html) :

{% macro menu_links(links=None) %}
  {% if links is none %}{% set links = admin_view.admin.menu_links() %}{% endif %}
  {% for item in links %}
    {% if item.is_accessible() and item.is_visible() %}
      <li>
        <a href="{{ item.get_url() }}">{{ menu_icon(item) }}{{ item.name }}</a>
      </li>
    {% endif %}
  {% endfor %}
{% endmacro %}

Notice the {% if item.is_accessible() and item.is_visible() %} line. Create inherited MenuLink classes and override is_accessible() or is_visible().

Example (un-tested) :

from flask_security import current_user
from flask_admin.menu import MenuLink
class LoginMenuLink(MenuLink):

    def is_accessible(self):
        return not current_user.is_authenticated 


class LogoutMenuLink(MenuLink):

    def is_accessible(self):
        return current_user.is_authenticated             

admin.add_link(LogoutMenuLink(name='Logout', category='', url="/logout"))
admin.add_link(LoginMenuLink(name='Login', category='', url="/login"))
like image 145
pjcunningham Avatar answered Jan 29 '26 18:01

pjcunningham