Python ldap.SERVER_DOWN Examples

The following are 23 code examples of ldap.SERVER_DOWN(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ldap , or try the search function .
Example #1
Source File: user.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def _check_ldap_password(cn, password):
    """Checks that the given cn/password credentials work on the given CN.

    @param cn: Common name to log on
    @param password: Password for cn
    @return: True on success, False on failure
    """
    cnx = ldap.initialize(config['ckanext.ldap.uri'])
    try:
        cnx.bind_s(cn, password)
    except ldap.SERVER_DOWN:
        log.error('LDAP server is not reachable')
        return False
    except ldap.INVALID_CREDENTIALS:
        log.debug('Invalid LDAP credentials')
        return False
    # Fail on empty password
    if password == '':
        log.debug('Invalid LDAP credentials')
        return False
    cnx.unbind_s()
    return True 
Example #2
Source File: ldap_auth.py    From kansha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_password(self, uid, password):
        """Check if the specified couple user/password is correct

        In:
           - ``uid`` -- the user id
           - ``password`` -- the user password
        Return:
            - True if password is checked
        """
        c = self.connect()
        dn = self.get_user_dn(uid)
        # Try to authenticate
        try:
            c.simple_bind_s(dn, password.encode('UTF-8'))
            return True
        except ldap.INVALID_CREDENTIALS:
            log.info("Bad credentials for DN %r" % dn)
        except ldap.SERVER_DOWN:
            log.critical("LDAP server down")
        finally:
            c.unbind() 
Example #3
Source File: ldap_auth.py    From kansha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_password(self, uid, password):
        """Check if the specified couple user/password is correct

        In:
           - ``uid`` -- the user id
           - ``password`` -- the user password
        Return:
            - True if password is checked
        """
        c = self.connect()
        # Try to authenticate
        try:
            c.simple_bind_s(uid, password)
            return True
        except ldap.INVALID_CREDENTIALS:
            log.info("Bad credentials for uid %r" % uid)
        except ldap.SERVER_DOWN:
            log.critical("LDAP server down")
        finally:
            c.unbind() 
Example #4
Source File: views.py    From fame with GNU General Public License v3.0 6 votes vote down vote up
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        try:
            user = authenticate(request.form.get('email'), request.form.get('password'))
        except SERVER_DOWN:
            flash("LDAP Server down.", "danger")
            return render_template('login.html')
        except INVALID_CREDENTIALS:
            flash("Invalid credentials.", "danger")
            return render_template('login.html')
        except LdapSettingsNotPresentException:
            flash("LDAP Settings not present. Check server logs.", "danger")
            return render_template('login.html')

        if not user or not user_has_groups_and_sharing(user):
            flash("Access not allowed.", "danger")
            return render_template('login.html')

        redir = request.args.get('next', '/')
        return redirect(redir) 
Example #5
Source File: connect_python_ldap.py    From Learning-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def main():
	try:
		# Open a connection
		ldap_client = ldap.initialize(LDAP_SERVER)
		# Set LDAPv3 option
		ldap_client.set_option(ldap.OPT_PROTOCOL_VERSION,3)
		# Bind/authenticate with a user with appropriate rights
		ldap_client.simple_bind("admin",'Secret123')
		# Get user attributes defined in LDAP_ATTRS
		result = ldap_client.search_s(LDAP_BASE_DN,ldap.SCOPE_SUBTREE,LDAP_FILTER, LDAP_ATTRS)
		print(result)
	except ldap.INVALID_CREDENTIALS as exception:
		ldap_client.unbind()
		print('Wrong username or password. '+exception)
	except ldap.SERVER_DOWN as exception:
		print('LDAP server not available. '+exception) 
Example #6
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 6 votes vote down vote up
def _get_conn(self):
        self._log.debug('Setting up LDAP connection')
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

        try:
            conn = ldap.initialize(self._url)
            conn.set_option(ldap.OPT_NETWORK_TIMEOUT, 3)
            conn.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
            conn.simple_bind_s(self._binddn, self._bindpw)
        except (
            ldap.SERVER_DOWN,
            ldap.NO_SUCH_OBJECT,
            ldap.INVALID_CREDENTIALS
        ) as e:
            if hasattr(e, 'message') and 'desc' in e.message:
                msg = e.message['desc']
            else:
                msg = e.args[0]['desc']
            self._log.debug('%s (%s)' % (msg, self._url))
            return False

        self._log.debug('LDAP connection established')
        return conn 
Example #7
Source File: _helpers.py    From ckanext-ldap with GNU General Public License v3.0 6 votes vote down vote up
def check_ldap_password(cn, password):
    '''Checks that the given cn/password credentials work on the given CN.

    :param cn: Common name to log on
    :param password: Password for cn
    :returns: True on success, False on failure

    '''
    cnx = ldap.initialize(toolkit.config[u'ckanext.ldap.uri'], bytes_mode=False,
                          trace_level=toolkit.config[u'ckanext.ldap.trace_level'])
    try:
        cnx.bind_s(cn, password)
    except ldap.SERVER_DOWN:
        log.error(u'LDAP server is not reachable')
        return False
    except ldap.INVALID_CREDENTIALS:
        log.debug(u'Invalid LDAP credentials')
        return False
    # Fail on empty password
    if password == u'':
        log.debug(u'Invalid LDAP credentials')
        return False
    cnx.unbind_s()
    return True 
Example #8
Source File: ldap_example.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ldap_auth(self, username, password):
        if self.cert_path:
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path)

        connection = ldap.initialize(self.ldap_url)
        connection.set_option(ldap.OPT_REFERRALS, 0)

        if not password:
            return False

        auth_user = username + self.user_suffix
        try:
            if self.bind_user:
                # use search filter to find DN of username
                connection.simple_bind_s(self.bind_user, self.bind_password)
                sfilter = self.search_filter % username
                result = connection.search_s(self.base_dn, ldap.SCOPE_SUBTREE, sfilter, ['dn'])
                if len(result) < 1:
                    return False
                auth_user = result[0][0]

            connection.simple_bind_s(auth_user, password)

        except ldap.INVALID_CREDENTIALS:
            return False
        except (ldap.SERVER_DOWN, ldap.INVALID_DN_SYNTAX) as err:
            logger.warn("%s", err)
            return None
        return True 
Example #9
Source File: ldapconn.py    From zabbix-ldap-sync with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect(self):
        """
        Establish a connection to the LDAP server.

        Raises:
            SystemExit

        """
        self.conn = ldap.initialize(self.uri)
        self.conn.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)

        try:
            self.conn.simple_bind_s(self.ldap_user, self.ldap_pass)
        except ldap.SERVER_DOWN as e:
            raise SystemExit('Cannot connect to LDAP server: %s' % e) 
Example #10
Source File: backend.py    From django-auth-ldap-ad with GNU General Public License v2.0 5 votes vote down vote up
def authenticate(self, username=None, password=None):
        if not hasattr(self, "ldap_settings"):
            self.ldap_settings = LDAPSettings()

        if isinstance(self.ldap_settings.SERVER_URI, six.string_types):
            servers_urls = [self.ldap_settings.SERVER_URI]
        else:
            servers_urls = self.ldap_settings.SERVER_URI

        # For all configured servers try to connect
        for server in servers_urls:
            # Use self.ldap_connection object if such is given for testing with
            # mockldap.
            if not hasattr(self, "ldap_connection"):
                try:
                    ldap_connection = self.ldap_open_connection(
                        server, username, password)
                except ldap.SERVER_DOWN:
                    continue
                except ldap.INVALID_CREDENTIALS:
                    return None
            else:  # end up here with mock
                ldap_connection = self.ldap_connection

            for key, value in self.ldap_settings.CONNECTION_OPTIONS.items():
                ldap_connection.set_option(key, value)

            # Do search
            try:
                ldap_user_info = self.ldap_search_user(
                    ldap_connection, username, password)
            except LDAPBackendException:
                return None

            return self.get_local_user(username, ldap_user_info)
        return None 
Example #11
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 5 votes vote down vote up
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE):
        self._log.debug('Search base: %s, filter: %s, attributes: %s, scope: %s' % (base, fltr, attrs, scope))
        try:
            results = self._conn.search_s(base, scope, fltr, attrs)
        except (ldap.NO_SUCH_OBJECT, ldap.SERVER_DOWN) as e:
            self._log.debug(self._get_ldap_msg(e))
            results = False
        except ldap.REFERRAL as e:
            self._log.critical("Replica %s is temporarily unavailable." % self._fqdn)
            self._log.debug("Replica redirected")
            self._log.debug(e.message['info'])
            exit(1)
        return results 
Example #12
Source File: search.py    From ckanext-ldap with GNU General Public License v3.0 5 votes vote down vote up
def find_ldap_user(login):
    '''Find the LDAP user identified by 'login' in the configured ldap database

    :param login: The login to find in the LDAP database
    :returns: None if no user is found, a dictionary defining 'cn', 'username',
              'fullname' and 'email otherwise.

    '''
    cnx = ldap.initialize(toolkit.config[u'ckanext.ldap.uri'], bytes_mode=False,
                          trace_level=toolkit.config[u'ckanext.ldap.trace_level'])
    cnx.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
    if toolkit.config.get(u'ckanext.ldap.auth.dn'):
        try:
            if toolkit.config[u'ckanext.ldap.auth.method'] == u'SIMPLE':
                cnx.bind_s(toolkit.config[u'ckanext.ldap.auth.dn'],
                           toolkit.config[u'ckanext.ldap.auth.password'])
            elif toolkit.config[u'ckanext.ldap.auth.method'] == u'SASL':
                if toolkit.config[u'ckanext.ldap.auth.mechanism'] == u'DIGEST-MD5':
                    auth_tokens = ldap.sasl.digest_md5(toolkit.config[u'ckanext.ldap.auth.dn'],
                                                       toolkit.config[
                                                           u'ckanext.ldap.auth.password'])
                    cnx.sasl_interactive_bind_s(u'', auth_tokens)
                else:
                    log.error(u'SASL mechanism not supported: {0}'.format(
                        toolkit.config[u'ckanext.ldap.auth.mechanism']))
                    return None
            else:
                log.error(u'LDAP authentication method is not supported: {0}'.format(
                    toolkit.config[u'ckanext.ldap.auth.method']))
                return None
        except ldap.SERVER_DOWN:
            log.error(u'LDAP server is not reachable')
            return None
        except ldap.INVALID_CREDENTIALS:
            log.error(
                u'LDAP server credentials (ckanext.ldap.auth.dn and ckanext.ldap.auth.password) '
                u'invalid')
            return None
        except ldap.LDAPError, e:
            log.error(u'Fatal LDAP Error: {0}'.format(e))
            return None 
Example #13
Source File: ldap.py    From pyvac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _bind(self, dn, password):
        """ bind a user in ldap with given password

        ldap does not support unicode for binding
        so we must cast password to utf-8
        """
        log.debug('binding with dn: %s' % dn)
        try:
            self._conn.simple_bind_s(dn, password.encode('utf-8'))
        except SERVER_DOWN:
            self._conn = ldap.initialize(self._url)
            self._conn.simple_bind_s(dn, password.encode('utf-8')) 
Example #14
Source File: test_BackendLdap.py    From ldapcherry with MIT License 5 votes vote down vote up
def testConnectSSLWrongCA(self):
        cfg2 = cfg.copy()
        cfg2['uri'] = 'ldaps://ldap.ldapcherry.org:637'
        cfg2['checkcert'] = 'on'
        inv = Backend(cfg2, cherrypy.log, 'ldap', attr, 'uid')
        ldapc = inv._connect()
        try:
            ldapc.simple_bind_s(inv.binddn, inv.bindpassword)
        except ldap.SERVER_DOWN as e:
            assert e.args[0]['info'] == 'TLS: hostname does not match CN in peer certificate' or \
                    e.args[0]['info'] == '(unknown error code)'
        else:
            raise AssertionError("expected an exception") 
Example #15
Source File: test_BackendLdap.py    From ldapcherry with MIT License 5 votes vote down vote up
def testLdapUnavaible(self):
        cfg2 = cfg.copy()
        cfg2['uri'] = 'ldaps://notaldap:637'
        cfg2['checkcert'] = 'on'
        inv = Backend(cfg2, cherrypy.log, 'ldap', attr, 'uid')
        try:
            ldapc = inv._connect()
            ldapc.simple_bind_s(inv.binddn, inv.bindpassword)
        except ldap.SERVER_DOWN as e:
            return
        else:
            raise AssertionError("expected an exception") 
Example #16
Source File: user.py    From daf-recipes with GNU General Public License v3.0 5 votes vote down vote up
def _find_ldap_user(login):
    """Find the LDAP user identified by 'login' in the configured ldap database

    @param login: The login to find in the LDAP database
    @return: None if no user is found, a dictionary defining 'cn', 'username', 'fullname' and 'email otherwise.
    """
    cnx = ldap.initialize(config['ckanext.ldap.uri'])
    if config.get('ckanext.ldap.auth.dn'):
        try:
            if config['ckanext.ldap.auth.method'] == 'SIMPLE':
                cnx.bind_s(config['ckanext.ldap.auth.dn'], config['ckanext.ldap.auth.password'])
            elif config['ckanext.ldap.auth.method'] == 'SASL':
                if config['ckanext.ldap.auth.mechanism'] == 'DIGEST-MD5':
                    auth_tokens = ldap.sasl.digest_md5(config['ckanext.ldap.auth.dn'], config['ckanext.ldap.auth.password'])
                    cnx.sasl_interactive_bind_s("", auth_tokens)
                else:
                    log.error("SASL mechanism not supported: {0}".format(config['ckanext.ldap.auth.mechanism']))
                    return None
            else:
                log.error("LDAP authentication method is not supported: {0}".format(config['ckanext.ldap.auth.method']))
                return None
        except ldap.SERVER_DOWN:
            log.error('LDAP server is not reachable')
            return None
        except ldap.INVALID_CREDENTIALS:
            log.error('LDAP server credentials (ckanext.ldap.auth.dn and ckanext.ldap.auth.password) invalid')
            return None
        except ldap.LDAPError, e:
            log.error("Fatal LDAP Error: {0}".format(e))
            return None 
Example #17
Source File: ldap.py    From iris with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ldap_auth(self, username, password):
        if self.cert_path:
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path)
        connection = ldap.initialize(self.ldap_url)
        connection.set_option(ldap.OPT_REFERRALS, 0)

        if not password:
            return False

        auth_user = username + self.user_suffix
        try:
            if self.bind_user:
                # use search filter to find DN of username
                connection.simple_bind_s(self.bind_user, self.bind_password)
                sfilter = self.search_filter % username
                result = connection.search_s(self.base_dn, ldap.SCOPE_SUBTREE, sfilter, ['dn'])
                if len(result) < 1:
                    return False
                auth_user = result[0][0]

            connection.simple_bind_s(auth_user, password)

        except ldap.INVALID_CREDENTIALS:
            return False
        except (ldap.SERVER_DOWN, ldap.INVALID_DN_SYNTAX) as err:
            logger.warning("%s", err)
            return None
        return True 
Example #18
Source File: test_service.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def test_server_down_auth(self):
        """
        Verify an ldap.SERVER_DOWN error will retry 2 more times and that
        the connection is closed if all attempts fail.
        """
        service = self.service()

        testStats = {}
        # Verify that without a SERVER_DOWN we don't need to retry, and we
        # still have a connection in the pool
        service._authenticateUsernamePassword_inThread(
            u"uid=wsanchez,cn=user,{0}".format(self.baseDN),
            u"zehcnasw",
            testStats=testStats
        )
        self.assertEquals(testStats["retryNumber"], 0)
        self.assertEquals(len(service.connectionPools["auth"].connections), 1)

        testStats["raise"] = ldap.SERVER_DOWN

        # Now try auth again
        try:
            service._authenticateUsernamePassword_inThread(
                u"uid=wsanchez,cn=user,{0}".format(self.baseDN),
                u"zehcnasw",
                testStats=testStats
            )
        except LDAPQueryError:
            # Verify the number of times we retried
            self.assertEquals(testStats["retryNumber"], 2)
        except:
            self.fail("Should have raised LDAPQueryError") 
Example #19
Source File: ldap_import.py    From oncall with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def ldap_auth(self, username, password):
        if self.cert_path:
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path)

        connection = ldap.initialize(self.ldap_url)
        connection.set_option(ldap.OPT_REFERRALS, 0)
        attrs = ['dn'] + list(self.attrs.values())
        ldap_contacts = {}

        if not password:
            return False

        auth_user = username + self.user_suffix
        try:
            if self.bind_user:
                # use search filter to find DN of username
                connection.simple_bind_s(self.bind_user, self.bind_password)
                sfilter = self.search_filter % username
                result = connection.search_s(self.base_dn, ldap.SCOPE_SUBTREE, sfilter, attrs)
                if len(result) < 1:
                    return False
                auth_user = result[0][0]
                ldap_attrs = result[0][1]
                for key, val in self.attrs.items():
                    if ldap_attrs.get(val):
                        if type(ldap_attrs.get(val)) == list:
                            ldap_contacts[key] = ldap_attrs.get(val)[0]
                        else:
                            ldap_contacts[key] = ldap_attrs.get(val)
                    else:
                        ldap_contacts[key] = val

            connection.simple_bind_s(auth_user, password)

        except ldap.INVALID_CREDENTIALS:
            return False
        except (ldap.SERVER_DOWN, ldap.INVALID_DN_SYNTAX) as err:
            logger.warn("%s", err)
            return None

        if self.import_user:
            connection = db.connect()
            cursor = connection.cursor(db.DictCursor)
            if user_exists(username, cursor):
                logger.info("user %s already exists, updating from ldap", username)
                update_user(username, ldap_contacts, cursor)
            else:
                logger.info("user %s does not exists. importing.", username)
                import_user(username, ldap_contacts, cursor)
            connection.commit()
            cursor.close()
            connection.close()

        return True 
Example #20
Source File: credentials.py    From pyvac with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def render(self):

        login_url = resource_url(self.request.context, self.request, 'login')
        referrer = self.request.url
        # never use the login form itself as came_from
        if referrer == login_url:
            referrer = '/'
        came_from = self.request.params.get('came_from', referrer)
        if came_from == '/':
            came_from = '/home'

        login = self.request.params.get('login', '')
        if 'submit' in self.request.params:
            password = self.request.params.get('password', '')
            if password:
                settings = self.request.registry.settings
                ldap = False
                if 'pyvac.use_ldap' in settings:
                    ldap = asbool(settings.get('pyvac.use_ldap'))

                try:
                    if login in self.blacklist_users:
                        raise INVALID_CREDENTIALS
                    user = User.by_credentials(self.session, login,
                                               password, ldap)
                    if user is not None:
                        log.info('login %r succeed' % user.login)
                        headers = remember(self.request, user.login)

                        # check for available users for sudo
                        sudoers = Sudoer.alias(self.session, user)
                        if sudoers:
                            location = route_url('sudo', self.request)
                            return HTTPFound(location=location,
                                             headers=headers)

                        return HTTPFound(location=came_from,
                                         headers=headers)
                    else:
                        msg = 'Invalid credentials.'
                        self.request.session.flash('error;%s' % msg)
                except SERVER_DOWN:
                    msg = 'Cannot reach ldap server.'
                    self.request.session.flash('error;%s' % msg)
                except INVALID_CREDENTIALS:
                    msg = 'Invalid credentials.'
                    self.request.session.flash('error;%s' % msg)
                except UnknownLdapUser:
                    msg = 'Unknown ldap user %s' % login
                    self.request.session.flash('error;%s' % msg)

        return {'came_from': came_from,
                'csrf_token': self.request.session.get_csrf_token(),
                } 
Example #21
Source File: __init__.py    From ssh-ldap-pubkey with MIT License 4 votes vote down vote up
def connect(self):
        """Connect to the LDAP server.
        This method must be called before any other methods of this object.

        Raises:
            ConfigError: If Base DN or LDAP URI is missing in the config.
            LDAPConnectionError: If can't connect to the LDAP server.
            ldap.LDAPError:
        """
        conf = self.conf

        if not conf.uris or not conf.base:
            raise ConfigError('Base DN and LDAP URI(s) must be provided.', 1)

        if conf.tls_require_cert:
            if conf.tls_require_cert not in [ldap.OPT_X_TLS_DEMAND, ldap.OPT_X_TLS_HARD]:
                print(BAD_REQCERT_WARNING, file=sys.stderr)
            # this is a global option!
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, conf.tls_require_cert)

        if conf.cacert_dir:
            # this is a global option!
            ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, conf.cacert_dir)

        if not conf.referrals:
            # this is a global option!
            ldap.set_option(ldap.OPT_REFERRALS, 0)

        # NOTE: The uri argument is passed directly to the underlying openldap
        # library that allows multiple URIs separated by a space for failover.
        self._conn = conn = ldap.initialize(' '.join(conf.uris))
        try:
            conn.protocol_version = conf.ldap_version
            conn.network_timeout = conf.bind_timeout
            conn.timeout = conf.search_timeout

            if conf.sasl == 'GSSAPI':
                self._bind_sasl_gssapi()
                return

            if conf.ssl == 'start_tls' and conf.ldap_version >= 3:
                conn.start_tls_s()

            if conf.bind_dn and conf.bind_pass:
                self._bind(conf.bind_dn, conf.bind_pass)
        except ldap.SERVER_DOWN:
            raise LDAPConnectionError('Can\'t contact LDAP server.', 3) 
Example #22
Source File: test_service.py    From ccs-twistedextensions with Apache License 2.0 4 votes vote down vote up
def test_server_down(self):
        """
        Verify an ldap.SERVER_DOWN error will retry 2 more times and that
        the connection is closed if all attempts fail.
        """

        service = self.service()

        testStats = {}
        # Verify that without a SERVER_DOWN we don't need to retry, and we
        # still have a connection in the pool
        service._recordsFromQueryString_inThread("(this=that)", testStats=testStats)
        self.assertEquals(testStats["retryNumber"], 0)
        self.assertEquals(len(service.connectionPools["query"].connections), 1)

        service._recordWithDN_inThread("cn=test", testStats=testStats)
        self.assertEquals(testStats["retryNumber"], 0)
        self.assertEquals(len(service.connectionPools["query"].connections), 1)

        # Force a search to raise SERVER_DOWN
        def raiseServerDown(*args, **kwds):
            raise ldap.SERVER_DOWN
        self.patch(LDAPObject, "search_ext", raiseServerDown)
        self.patch(LDAPObject, "search_s", raiseServerDown)

        # Now try recordsFromQueryString
        try:
            service._recordsFromQueryString_inThread("(this=that)", testStats=testStats)
        except LDAPQueryError:
            # Verify the number of times we retried
            self.assertEquals(testStats["retryNumber"], 2)
        except:
            self.fail("Should have raised LDAPQueryError")

        # Verify the connections are all closed
        self.assertEquals(len(service.connectionPools["query"].connections), 0)

        # Now try recordWithDN
        try:
            service._recordWithDN_inThread("cn=test", testStats=testStats)
        except LDAPQueryError:
            # Verify the number of times we retried
            self.assertEquals(testStats["retryNumber"], 2)
        except:
            self.fail("Should have raised LDAPQueryError")

        # Verify the connections are all closed
        self.assertEquals(len(service.connectionPools["query"].connections), 0) 
Example #23
Source File: user.py    From daf-recipes with GNU General Public License v3.0 4 votes vote down vote up
def _ldap_search(cnx, filter_str, attributes, non_unique='raise'):
    """Helper function to perform the actual LDAP search

    @param cnx: The LDAP connection object
    @param filter_str: The LDAP filter string
    @param attributes: The LDAP attributes to fetch. This *must* include self.ldap_username
    @param non_unique: What to do when there is more than one result. Can be either 'log' (log an error
                       and return None - used to indicate that this is a configuration problem that needs
                       to be address by the site admin, not by the current user) or 'raise' (raise an
                       exception with a message that will be displayed to the current user - such
                       as 'please use your unique id instead'). Other values will silently ignore the error.
    @return: A dictionary defining 'cn', self.ldap_username and any other attributes that were defined
             in attributes; or None if no user was found.
    """
    try:
        res = cnx.search_s(config['ckanext.ldap.base_dn'], ldap.SCOPE_SUBTREE, filterstr=filter_str, attrlist=attributes)
    except ldap.SERVER_DOWN:
        log.error('LDAP server is not reachable')
        return None
    except ldap.OPERATIONS_ERROR as e:
        log.error('LDAP query failed. Maybe you need auth credentials for performing searches? Error returned by the server: ' + e.info)
        return None
    except (ldap.NO_SUCH_OBJECT, ldap.REFERRAL) as e:
        log.error('LDAP distinguished name (ckanext.ldap.base_dn) is malformed or does not exist.')
        return None
    except ldap.FILTER_ERROR:
        log.error('LDAP filter (ckanext.ldap.search) is malformed')
        return None
    if len(res) > 1:
        if non_unique == 'log':
            log.error('LDAP search.filter search returned more than one entry, ignoring. Fix the search to return only 1 or 0 results.')
        elif non_unique == 'raise':
            raise MultipleMatchError(config['ckanext.ldap.search.alt_msg'])
        return None
    elif len(res) == 1:
        cn = res[0][0]
        attr = res[0][1]
        ret = {
            'cn': cn,
        }

        # Check required fields
        for i in ['username', 'email']:
            cname = 'ckanext.ldap.' + i
            if config[cname] not in attr or not attr[config[cname]]:
                log.error('LDAP search did not return a {}.'.format(i))
                return None
        # Set return dict
        for i in ['username', 'fullname', 'email', 'about']:
            cname = 'ckanext.ldap.' + i
            if cname in config and config[cname] in attr:
                v = attr[config[cname]]
                if v:
                    ret[i] = v[0]
        return ret
    else:
        return None