master
Raw Download raw file
 1import ldap
 2from config import LDAP_SERVER, LDAP_DOMAIN, LDAP_TRANSFER_GROUP, LDAP_ADMIN_GROUP, LDAP_BASE_DN
 3 
 4def login(username, password):
 5   """Verifies credentials for username and password.
 6   Returns None on success or a string describing the error on failure
 7   # Adapt to your needs
 8   """
 9   # fully qualified AD user name
10   LDAP_USERNAME = '%s@%s' % (username, LDAP_DOMAIN)
11   # your password
12   LDAP_PASSWORD = password
13   ldap_filter = 'userPrincipalName=%s@%s' % (username, LDAP_DOMAIN)
14   attrs = ['memberOf']
15   try:
16       # build a client
17       ldap_client = ldap.initialize(LDAP_SERVER)
18       # perform a synchronous bind
19       ldap_client.set_option(ldap.OPT_REFERRALS,0)
20       ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
21   except ldap.INVALID_CREDENTIALS:
22       ldap_client.unbind()
23       return False, 'Wrong username or password'
24   except ldap.SERVER_DOWN:
25       return False, 'AD server not awailable'
26   # all is well so far
27   # get all user groups and store it in cerrypy session for future use
28   groups = str(ldap_client.search_s(LDAP_BASE_DN,
29                   ldap.SCOPE_SUBTREE, ldap_filter, attrs)[0][1]['memberOf'])
30   ldap_client.unbind()
31   if LDAP_ADMIN_GROUP in groups:
32       return True, True #Admin
33   elif LDAP_TRANSFER_GROUP in groups:
34       return True, False #Not admin
35   else:
36       return False, 'Not in transfer group'
37
38if __name__ == "__main__":
39    import getpass
40    username = raw_input("Username: ")
41    password = getpass.getpass("Password: ")
42    print login(username, password)