Flask-Admin + (Flask-Login and/or Flask-Principal) Flask-Admin + (Flask-Login and/or Flask-Principal) flask flask

Flask-Admin + (Flask-Login and/or Flask-Principal)


Flask-Admin provides another way of providing authentication - you simply subclass the AdminIndex and BaseIndex views (or views from contrib if you only need those) and implement the is_accessible method. See the documentation for more details. There is also an example provided in the repository.


Simple example how to use Flask-Admin with Flask-Principal

from functools import partialfrom flask.ext.admin import Admin as BaseAdmin, AdminIndexViewfrom flask.ext.principal import Permission, identity_loaded, Needfrom flask.ext.security import current_userPartnerAccessNeed = partial(Need, 'access')class PartnerAccessPermission(Permission):    def __init__(self, partner_id):        need = PartnerAccessNeed(partner_id)        super(PartnerAccessPermission, self).__init__(need)@identity_loaded.connectdef on_post_identity_loaded(sender, identity):      if hasattr(current_user, 'partner'):        identity.provides.add(PartnerAccessNeed(current_user.partner.id))class PartnerAdminIndexView(AdminIndexView):    def __init__(self, partner_id, *args, **kwargs):        self.partner_id = partner_id        super(PartnerAdminIndexView, self).__init__(*args, **kwargs)    def is_accessible(self):        if current_user.is_anonymous():            return redirect(url_for_security('login'))        if not current_user.is_partner():            return False        permission = PartnerAccessPermission(self.partner_id)        if permission.can():                return True        return Falseclass PartnerAdmin(BaseAdmin):    def __init__(self, partner_id, endpoint, name, subdomain, *args, **kwargs):        index = PartnerAdminIndexView(name=name,                                       endpoint=endpoint,                                      url='/dashboard',                                      partner_id=partner_id)        super(PartnerAdmin, self).__init__(base_template='mcnm/master.html', index_view=index, subdomain=subdomain)


This repository is a good example of how flask-login and flask-security can be connected with flask-admin.

In this reddit post the author of the boilerplate describes shortly the implementation logic.