Python ldap.REFERRAL Examples

The following are 4 code examples of ldap.REFERRAL(). 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: externalldap.py    From quay with Apache License 2.0 6 votes vote down vote up
def _ldap_user_search_with_rdn(self, conn, username_or_email, user_search_dn, suffix=""):
        query = "(|({0}={2}{3})({1}={2}{3}))".format(
            self._uid_attr, self._email_attr, escape_filter_chars(username_or_email), suffix
        )
        query = self._add_user_filter(query)

        logger.debug("Conducting user search: %s under %s", query, user_search_dn)
        try:
            return (conn.search_s(user_search_dn, ldap.SCOPE_SUBTREE, query), None)
        except ldap.REFERRAL as re:
            referral_dn = self._get_ldap_referral_dn(re)
            if not referral_dn:
                return (None, "Failed to follow referral when looking up username")

            try:
                subquery = "(%s=%s)" % (self._uid_attr, username_or_email)
                subquery = self._add_user_filter(subquery)
                return (conn.search_s(referral_dn, ldap.SCOPE_BASE, subquery), None)
            except ldap.LDAPError:
                logger.debug("LDAP referral search exception")
                return (None, "Username not found")

        except ldap.LDAPError:
            logger.debug("LDAP search exception")
            return (None, "Username not found") 
Example #2
Source File: externalldap.py    From quay with Apache License 2.0 5 votes vote down vote up
def verify_credentials(self, username_or_email, password):
        """
        Verify the credentials with LDAP.
        """
        # Make sure that even if the server supports anonymous binds, we don't allow it
        if not password:
            return (None, "Anonymous binding not allowed")

        (found_user, err_msg) = self._ldap_single_user_search(username_or_email)
        if found_user is None:
            return (None, err_msg)

        found_dn, found_response = found_user
        logger.debug("Found user for LDAP username %s; validating password", username_or_email)
        logger.debug("DN %s found: %s", found_dn, found_response)

        # First validate the password by binding as the user
        try:
            with LDAPConnection(self._ldap_uri, found_dn, password, self._allow_tls_fallback):
                pass
        except ldap.REFERRAL as re:
            referral_dn = self._get_ldap_referral_dn(re)
            if not referral_dn:
                return (None, "Invalid username")

            try:
                with LDAPConnection(
                    self._ldap_uri, referral_dn, password, self._allow_tls_fallback
                ):
                    pass
            except ldap.INVALID_CREDENTIALS:
                logger.debug("Invalid LDAP credentials")
                return (None, "Invalid password")

        except ldap.INVALID_CREDENTIALS:
            logger.debug("Invalid LDAP credentials")
            return (None, "Invalid password")

        return self._build_user_information(found_response) 
Example #3
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 #4
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