2
votes

I'm building a Flask app and started using Flask-Login for authentication. What troubles me is that Flask-Login calls the load_user callback for every request that flask handles. Here is the example from https://flask-login.readthedocs.org/en/latest/#how-it-works:

@login_manager.user_loader
def load_user(userid):
    return User.get(userid)

To retrieve the user, I need to pass a session token a remote web service across a VPN, and the remote web service does a db query -- this results in noticeable latency on every web request. My load_user looks something like this:

@login_manager.user_loader
def load_user(userid):
    # notice that I don't even use the userid arg
    try:
        # have to get session_token from session; why not 
        # just get the entire user object from session???
        token = session.get('session_token')
        user_profile = RestClient().get_user_profile(token)
        return User(user_profile['LDAP_ID'])
    except:
        return None

Seems like maybe I'm subverting the framework. Could just store/retrieve user from session, so why bother to get it from the web service? This option also seems to subvert Flask-Login, but eliminates latency and makes good use of session.

1

1 Answers

0
votes

The best way to handle this is to cache session information using something like memcached or redis (look into Flask-Cache for help).

You should have a key-value cache store that structures the cache like so:

key: sessionID value: user object

This is what most frameworks do -- Flask-Login is a generic tool -- so you have to implement this yourself.

Incidentally, if you're looking for a way to abstract away that nasty LDAP stuff on the backend, you might want to check out https://stormpath.com -- they sync with LDAP servers, and provide a REST API on top of it. There's also a Flask library for interacting with it: Flask-Stormpath.