Flask-login and LDAP

monoceres picture monoceres · Nov 9, 2012 · Viewed 12.5k times · Source

I'm developing a webapp with the flask framework as a backend and I need to provide authentication.

Since this is an in-house app to be used on our local domain I have chosen to authenticate user with their already present domain credentials.

The method I use is the win32security.LogonUser from pywin32 which returns a handle on successful login.

I have tried to understand how flask-login works, but the @login_manager.user_loader callback makes me confused.

It says I should provide an id which can be used to reload the user, however I have no database or persistent storage to provide this mapping from, since I'm only interesting in checking if the user pass authentication.

My User class looks like this:

class User(flask_login.UserMixin):
    def __init__(self,username):
        self.username = username
        self.id = ??? 

What to use an id, and how could this id map back to this instance?

Answer

1408786user picture 1408786user · Dec 14, 2012

You can do it in python with the LDAP module:

LDAP_SERVER = "yourldapserver"
LDAP_PORT = 390033 # your port
import ldap
def login(email, password):
    ld = ldap.open(LDAP_SERVER, port=LDAP_PORT)
    try:
        ld.simple_bind_s(email, password)
    except ldap.INVALID_CREDENTIALS:
        return False
    return True