Bouni Bouni - 1 year ago 87
Python Question

Flask-Principal, Flask-Login, remember_me and identity_loaded

I work on a Flask app with Flask-Login and Flask-Principal and everything works fine so far except the remember me function of Flask-Login.

Actually the remember me function works on the Flask-Login side, but the idenity_loaded function of Flask-Principal doesn't get triggered.

When I log the calls of @login_manager.user_loader and @identity_loaded.connect is see both getting called when I log in, but when I close the browser and start it again, just the @login_manager.user_loader gets called. So my user gets basically logged in but gets no roles.

Flask-Login has a closed Issue #19 on GitHub but it actually doesn't answer my question :-/

Has anybody an idea how to react when the user get loaded from a cookie?


On before_request, flask-principal runs the identity_loaders one at a time until any identity is found. If it doesn't find any identity, identity_loaded won't be called.

The first identity_loader is always the session loader by default.

When you restart the browser, the session will be gone, so flask-principal can't load any identity thus your identity_loaded callback won't be called. But you're still logged in because flask-login's cookie 'remember_token' expires in 31 days.

So, to get rid of this idiosyncrasy, you can add new identity_loader, which will only run when session expires.

principal = Principal(app)

def load_identity_when_session_expires():
    if hasattr(current_user, 'id'):
        return Identity(