Search code examples
flaskflask-loginflask-admin

flask-admin secure the whole admin site but not just the index view


I can secure the index view by having my own CustomeIndexView and check whether is authenticated there. But this won't secure a model view, for example, the URL /admin/MyModel/ is still not secured. Is there a way to secure the whole site, basically any url like /admin/xxx/?

one way to do this is by customizing is_accessible in ModelView. But i still feel it's more straight-forward if it can be done by limiting access by the root url

By the way, i'm using flask-login


Solution

  • You can use before_request to check if current_user.is_authenticated and return 401 response if not, as in:

    @app.before_request
    def before_request():
        if request.full_path.startswith('/admin/'):
            if not current_user.is_authenticated:
                abort(401, 'Please log in')
    

    You can also use this to redirect to login page, for example.