import ldap
from config import LDAP_SERVER, LDAP_DOMAIN, LDAP_TRANSFER_GROUP, LDAP_ADMIN_GROUP, LDAP_BASE_DN
 
def login(username, password):
   """Verifies credentials for username and password.
   Returns None on success or a string describing the error on failure
   # Adapt to your needs
   """
   # fully qualified AD user name
   LDAP_USERNAME = '%s@%s' % (username, LDAP_DOMAIN)
   # your password
   LDAP_PASSWORD = password
   ldap_filter = 'userPrincipalName=%s@%s' % (username, LDAP_DOMAIN)
   attrs = ['memberOf']
   try:
       # build a client
       ldap_client = ldap.initialize(LDAP_SERVER)
       # perform a synchronous bind
       ldap_client.set_option(ldap.OPT_REFERRALS,0)
       ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
   except ldap.INVALID_CREDENTIALS:
       ldap_client.unbind()
       return False, 'Wrong username or password'
   except ldap.SERVER_DOWN:
       return False, 'AD server not awailable'
   # all is well so far
   # get all user groups and store it in cerrypy session for future use
   groups = str(ldap_client.search_s(LDAP_BASE_DN,
                   ldap.SCOPE_SUBTREE, ldap_filter, attrs)[0][1]['memberOf'])
   ldap_client.unbind()
   if LDAP_ADMIN_GROUP in groups:
       return True, True #Admin
   elif LDAP_TRANSFER_GROUP in groups:
       return True, False #Not admin
   else:
       return False, 'Not in transfer group'

if __name__ == "__main__":
    import getpass
    username = raw_input("Username: ")
    password = getpass.getpass("Password: ")
    print login(username, password)
