Search code examples
pythonflaskflask-admin

Flask-Admin Role Based Access - Modify access based on role


I took the Flask-Admin auth example from here and changed it slightly.

I added the following block to the view below, but it doesn't show the export button. I was expecting it to add the export option to the admin views. It does print ---superuser to the console.

        if current_user.has_role('superuser'):
            can_export = True
            print ' ---- superuser '

I have used the export feature many times before. It will work if I put the statement can_export = True just below class MyModelView(sqla.ModelView): I am using this as an example of controlling access to creating/editing/etc based on the user role. For example, I will want to have a readonly role where can_create=False, can_edit=False, etc.

Can someone help? Can someone tell me what I am doing wrong?

==

This is the entire view.

# Create customized model view class
class MyModelView(sqla.ModelView):

    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False

        if current_user.has_role('superuser'):
            return True

        return False

    def _handle_view(self, name, **kwargs):
        """
        Override builtin _handle_view in order to redirect users when a view is not accessible.
        """
        if current_user.has_role('superuser'):
            can_export = True
            print ' ---- superuser '

        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))

==

For reference: I put the all the code here.


Solution

  • Per @dirn's comment above, adding the self. fixed it.

    self.can_export = True
    

    Thanks @dirn