Flask-Security login and logout in menu bar

☆樱花仙子☆ 提交于 2019-12-04 06:43:34

问题


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:


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

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"))


来源:https://stackoverflow.com/questions/41617339/flask-security-login-and-logout-in-menu-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!