<s> from __future__ import print_function , unicode_literals <EOL> import sys <EOL> import re <EOL> try : <EOL> import ldap <EOL> except ImportError : <EOL> LDAP_AVAILABLE = False <EOL> else : <EOL> LDAP_AVAILABLE = True <EOL> from weblab . core . exc import DbInvalidUserAuthConfigurationError <EOL> import voodoo . log as log <EOL> import weblab . core . login . exc as LoginErrors <EOL> from weblab . core . login . simple import SimpleAuthnUserAuth <EOL> if LDAP_AVAILABLE : <EOL> class _LdapProvider ( object ) : <EOL> def __init__ ( self ) : <EOL> self . ldap_module = ldap <EOL> def get_module ( self ) : <EOL> return self . ldap_module <EOL> _ldap_provider = _LdapProvider ( ) <EOL> class LdapUserAuth ( SimpleAuthnUserAuth ) : <EOL> NAME = '<STR_LIT>' <EOL> REGEX = '<STR_LIT>' <EOL> def __init__ ( self , auth_configuration , user_auth_configuration ) : <EOL> mo = re . match ( LdapUserAuth . REGEX , auth_configuration ) <EOL> if mo is None : <EOL> raise DbInvalidUserAuthConfigurationError ( <EOL> "<STR_LIT>" % auth_configuration <EOL> ) <EOL> ldap_uri , domain , base = mo . groups ( ) <EOL> self . ldap_uri = ldap_uri <EOL> self . domain = domain <EOL> self . base = base <EOL> self . auth_configuration = auth_configuration <EOL> def authenticate ( self , login , password ) : <EOL> if not LDAP_AVAILABLE : <EOL> msg = "<STR_LIT>" % login <EOL> print ( msg , file = sys . stderr ) <EOL> log . log ( self , log . level . Error , msg ) <EOL> return False <EOL> if not password : <EOL> return False <EOL> password = str ( password ) <EOL> ldap_module = _ldap_provider . get_module ( ) <EOL> try : <EOL> ldapobj = ldap_module . initialize ( <EOL> self . ldap_uri <EOL> ) <EOL> except Exception as e : <EOL> raise LoginErrors . LdapInitializingError ( <EOL> "<STR_LIT>" % e <EOL> ) <EOL> dn = "<STR_LIT>" % ( login , self . domain ) <EOL> pw = password <EOL> try : <EOL> ldapobj . simple_bind_s ( dn , pw ) <EOL> except ldap . INVALID_CREDENTIALS as e : <EOL> return False <EOL> except Exception as e : <EOL> raise LoginErrors . LdapBindingError ( <EOL> "<STR_LIT>" % e <EOL> ) <EOL> else : <EOL> ldapobj . unbind_s ( ) <EOL> return True <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT>" % ( self . domain , self . ldap_uri , self . base ) <EOL> def __repr__ ( self ) : <EOL> return "<STR_LIT>" % ( self . auth_configuration ) </s>
