Python ldap.LDAPError() Examples

The following are 30 code examples of ldap.LDAPError(). 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: forms.py    From zentral with Apache License 2.0 7 votes vote down vote up
def clean(self):
        super().clean()
        host = self.cleaned_data.get("host")
        bind_dn = self.cleaned_data.get("bind_dn")
        bind_password = self.cleaned_data.get("bind_password")

        if host and bind_dn and bind_password:
            try:
                conn = get_ldap_connection(host)
            except ldap.LDAPError as e:
                e_dict = e.args[0]
                self.add_error("host", e_dict.get("desc", e_dict.get("info", str(e))))
            except Exception as e:
                self.add_error("host", str(e))
            else:
                try:
                    conn.simple_bind_s(bind_dn, bind_password)
                except ldap.LDAPError as e:
                    e_dict = e.args[0]
                    self.add_error("bind_password", e_dict.get("desc", e_dict.get("info", str(e))))
                except Exception as e:
                    self.add_error("bind_password", str(e)) 
Example #2
Source File: ldap_attr.py    From isam-ansible-roles with Apache License 2.0 7 votes vote down vote up
def _connect_to_ldap(self):
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
        connection = ldap.initialize(self.server_uri)

        if self.start_tls:
            try:
                connection.start_tls_s()
            except ldap.LDAPError:
                e = get_exception()
                self.module.fail_json(msg="Cannot start TLS.", details=str(e))

        try:
            if self.bind_dn is not None:
                connection.simple_bind_s(self.bind_dn, self.bind_pw)
            else:
                connection.sasl_interactive_bind_s('', ldap.sasl.external())
        except ldap.LDAPError:
            e = get_exception()
            self.module.fail_json(
                msg="Cannot bind to the server.", details=str(e))

        return connection 
Example #3
Source File: ldapadmin.py    From diting with GNU General Public License v2.0 7 votes vote down vote up
def ldap_update_user(self, uid, old, new):
        """
        修改dap用户
        :param uid: 用户名
        :param old: 原属性 {'mail': ['admin@example.com']}
        :param new  新属性 {'mail': ['root@example.com']}
        :return: True/None
        """
        result = None
        try:
            obj = self.ldapconn
            obj.protocal_version = ldap.VERSION3
            dn = "uid=%s,%s" % (uid, BASE_DN)
            ldif = modlist.modifyModlist(old, new)
            obj.modify_s(dn, ldif)
            obj.unbind_s()
            result = True
        except ldap.LDAPError as e:
            logger.error("修改用户%s 失败,原因为: %s" % (uid, str(e)))
        return result 
Example #4
Source File: __init__.py    From ssh-ldap-pubkey with MIT License 6 votes vote down vote up
def find_and_remove_pubkeys(self, login, password, pattern):
        """Find and remove public keys of the user with the ``login`` that maches the ``pattern``.

        Arguments:
            login (str): Login of the user to add the ``pubkey``.
            password (Optional[str]): The user's password to bind with, or None
                to not (re)bind with the user's credentials.
            pattern (str): The pattern specifying public keys to be removed.
        Raises:
            UserEntryNotFoundError: If the ``login`` is not found.
            NoPubKeyFoundError: If no public key matching the ``pattern`` is found.
            InsufficientAccessError: If the bind user doesn't have rights to add the pubkey.
            ldap.LDAPError:
        Returns:
            List[str]: A list of removed public keys.
        """
        dn = self.find_dn_by_login(login)
        if password:
            self._bind(dn, password)

        pubkeys = [key for key in self._find_pubkeys(dn) if pattern in key]
        for key in pubkeys:
            self._remove_pubkey(dn, key)

        return pubkeys 
Example #5
Source File: ldap_backend.py    From st2-auth-backend-ldap with Apache License 2.0 6 votes vote down vote up
def _ldap_connect(self):
        """
        Prepare ldap object for binding phase.
        """
        try:
            connection = ldap.initialize(self._ldap_uri)
            connection.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
            connection.set_option(ldap.OPT_REFERRALS,
                                  int(self._chase_referrals))

            if self._ldap_uri.startswith('ldaps://'):
                # Require server certificate but ignore it's validity. (allow self-signed)
                ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

            if self._use_tls:
                # Require TLS connection.
                ldap.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
                # Require server certificate but ignore it's validity. (allow self-signed)
                ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
                connection.start_tls_s()
                LOG.debug('Connection now using TLS')
            return connection
        except ldap.LDAPError as e:
            LOG.debug('(_ldap_connect) LDAP Error: %s : Type %s' % (str(e), type(e)))
            return False 
Example #6
Source File: ldap.py    From Adminset_Zabbix with Apache License 2.0 6 votes vote down vote up
def ldap_get_user(self,uid=None):
        obj = self.ldapconn
        obj.protocal_version = ldap.VERSION3
        searchScope = ldap.SCOPE_SUBTREE
        retrieveAttributes = None
        searchFilter = "cn=" + uid
        try:
            ldap_result_id = obj.search(self.base_dn, searchScope, searchFilter, retrieveAttributes)
            result_type, result_data = obj.result(ldap_result_id, 0)
            if result_type == ldap.RES_SEARCH_ENTRY:
                username = result_data[0][1]['cn'][0]
                email = result_data[0][1]['mail'][0]
                nick = result_data[0][1]['sn'][0]
                result = {'username':username,'email':email,'nick':nick}
                return result
            else:
                return None
        except ldap.LDAPError, e:
            print e

#用户验证,根据传递来的用户名和密码,搜索LDAP,返回boolean值 
Example #7
Source File: ldap_attr.py    From isam-ansible-roles with Apache License 2.0 6 votes vote down vote up
def exact(self):
        try:
            results = self.connection.search_s(
                self.dn, ldap.SCOPE_BASE, attrlist=[self.name])
        except ldap.LDAPError:
            e = get_exception()
            self.module.fail_json(
                msg="Cannot search for attribute %s" % self.name,
                details=str(e))

        current = results[0][1].get(self.name, [])
        modlist = []

        if frozenset(self.values) != frozenset(current):
            if len(current) == 0:
                modlist = [(ldap.MOD_ADD, self.name, self.values)]
            elif len(self.values) == 0:
                modlist = [(ldap.MOD_DELETE, self.name, None)]
            else:
                modlist = [(ldap.MOD_REPLACE, self.name, self.values)]

        return modlist 
Example #8
Source File: ldap.py    From Adminset_Zabbix with Apache License 2.0 6 votes vote down vote up
def ldap_search_dn(self,uid=None):
        obj = self.ldapconn
        obj.protocal_version = ldap.VERSION3
        searchScope = ldap.SCOPE_SUBTREE
        retrieveAttributes = None
        searchFilter = "cn=" + uid

        try:
            ldap_result_id = obj.search(self.base_dn, searchScope, searchFilter, retrieveAttributes)
            result_type, result_data = obj.result(ldap_result_id, 0)
#返回数据格式
#('cn=django,ou=users,dc=gccmx,dc=cn',
#    {  'objectClass': ['inetOrgPerson', 'top'],
#        'userPassword': ['{MD5}lueSGJZetyySpUndWjMBEg=='],
#        'cn': ['django'], 'sn': ['django']  }  )
#
            if result_type == ldap.RES_SEARCH_ENTRY:
                #dn = result[0][0]
                return result_data[0][0]
            else:
                return None
        except ldap.LDAPError, e:
            print e

#查询用户记录,返回需要的信息 
Example #9
Source File: __init__.py    From flask-simpleldap with MIT License 6 votes vote down vote up
def initialize(self):
        """Initialize a connection to the LDAP server.

        :return: LDAP connection object.
        """

        try:
            conn = ldap.initialize('{0}://{1}:{2}'.format(
                current_app.config['LDAP_SCHEMA'],
                current_app.config['LDAP_HOST'],
                current_app.config['LDAP_PORT']))
            conn.set_option(ldap.OPT_NETWORK_TIMEOUT,
                            current_app.config['LDAP_TIMEOUT'])
            conn = self._set_custom_options(conn)
            conn.protocol_version = ldap.VERSION3
            if current_app.config['LDAP_USE_TLS']:
                conn.start_tls_s()
            return conn
        except ldap.LDAPError as e:
            raise LDAPException(self.error(e.args)) 
Example #10
Source File: __init__.py    From flask-simpleldap with MIT License 6 votes vote down vote up
def bind(self):
        """Attempts to bind to the LDAP server using the credentials of the
        service account.

        :return: Bound LDAP connection object if successful or ``None`` if
            unsuccessful.
        """

        conn = self.initialize
        try:
            conn.simple_bind_s(
                current_app.config['LDAP_USERNAME'],
                current_app.config['LDAP_PASSWORD'])
            return conn
        except ldap.LDAPError as e:
            raise LDAPException(self.error(e.args)) 
Example #11
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_auth_signal_ldap_error(self):
        self._init_settings(
            BIND_DN="uid=bob,ou=people,o=test",
            BIND_PASSWORD="bogus",
            USER_SEARCH=LDAPSearch(
                "ou=people,o=test", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
            ),
        )

        def handle_ldap_error(sender, **kwargs):
            raise kwargs["exception"]

        with catch_signal(ldap_error) as handler:
            handler.side_effect = handle_ldap_error
            with self.assertRaises(ldap.LDAPError):
                authenticate(username="alice", password="password")
        handler.assert_called_once()
        _args, kwargs = handler.call_args
        self.assertEqual(kwargs["context"], "authenticate") 
Example #12
Source File: ldap.py    From Adminset_Zabbix with Apache License 2.0 6 votes vote down vote up
def __init__(self,ldap_host=None,base_dn=None,user=None,password=None):
        if not ldap_host:
            ldap_host = LDAP_HOST
        if not base_dn:
            self.base_dn = BASE_DN
        if not user:
            user = USER
        if not password:
            password = PASSWORD
        try:
            self.ldapconn = ldap.open(ldap_host)
            self.ldapconn.simple_bind(user,password)
        except ldap.LDAPError,e:
            print e

#根据表单提交的用户名,检索该用户的dn,一条dn就相当于数据库里的一条记录。
#在ldap里类似cn=username,ou=users,dc=gccmx,dc=cn,验证用户密码,必须先检索出该DN 
Example #13
Source File: ldapadmin.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
def ldap_update_password(self, uid, new_password=None, old_password=None):
        """
        更新密码
        :param uid: 用户uid,新password
        :return: True|None
        """
        result = None
        try:
            obj = self.ldapconn
            obj.protocal_version = ldap.VERSION3
            modifyDN = "uid=%s,%s" % (uid, BASE_DN)
            new_password_encrypt = pass_encrypt(new_password)
            #有old_password情况下
            if old_password:
                obj.passwd_s(modifyDN, [str(old_password).encode('utf-8')], [new_password_encrypt.encode('utf-8')])
                result = True
            else:
                obj.modify_s(modifyDN, [(ldap.MOD_REPLACE, 'userPassword', [new_password_encrypt.encode('utf-8')])])
                result = True
            obj.unbind_s()
        except ldap.LDAPError as e:
            logger.error("%s 密码更新失败,原因为: %s" % (uid, str(e)))
            return False
        return result 
Example #14
Source File: ldapadmin.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
def check_user_status(self, uid):
        """
        验证用户状态
        :param uid: 用户uid
        :return: 200: 用户可用
                 404: 用户不存在
                 403: 用户被禁用
        """
        result = 404
        data = None
        try:
            target_cn = self.ldap_get_user(uid=uid)
            if target_cn is None:  # 如未查到用户,记录日志,但不算错误,后边有很多地方会验证用户是否存在
                result = 404
                logger.debug("%s uid未查询到" % uid)
            else:
                if self.check_user_belong_to_group(uid=uid, group_cn='黑名单'):
                    result = 403
                else:
                    result, data = 200, target_cn
        except ldap.LDAPError as e:
            logger.error("%s 检查用户状态失败,原因为: %s" % (uid, str(e)))
            return 500
        return result, data 
Example #15
Source File: ldapadmin.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
def __ldap_getgid(self, cn="员工"):
        """
        查询 组cn对应的gid
        :param cn: 组cn
        :return: 对应cn的gidNumber
        """
        obj = self.ldapconn
        obj.protocal_version = ldap.VERSION3
        searchScope = ldap.SCOPE_SUBTREE
        retrieveAttributes = None
        searchFilter = "cn=" + cn
        try:
            ldap_result_id = obj.search(
                base="%s" % self.base_dn,
                scope=searchScope,
                filterstr=searchFilter,
                attrlist=retrieveAttributes
            )
            result_type, result_data = obj.result(ldap_result_id, 0)
            if result_type == ldap.RES_SEARCH_ENTRY:
                return result_data[0][1].get('gidNumber')[0]
            else:
                return None
        except ldap.LDAPError as e:
            logger.error('获取gid失败,原因为: %s' % str(e)) 
Example #16
Source File: user.py    From PowerDNS-Admin with MIT License 6 votes vote down vote up
def ad_recursive_groups(self, groupDN):
        """
        Recursively list groups belonging to a group. It will allow checking deep in the Active Directory
        whether a user is allowed to enter or not
        """
        LDAP_BASE_DN = Setting().get('ldap_base_dn')
        groupSearchFilter = "(&(objectcategory=group)(member=%s))" % ldap.filter.escape_filter_chars(
            groupDN)
        result = [groupDN]
        try:
            groups = self.ldap_search(groupSearchFilter, LDAP_BASE_DN)
            for group in groups:
                result += [group[0][0]]
                if 'memberOf' in group[0][1]:
                    for member in group[0][1]['memberOf']:
                        result += self.ad_recursive_groups(
                            member.decode("utf-8"))
            return result
        except ldap.LDAPError as e:
            current_app.logger.exception("Recursive AD Group search error")
            return result 
Example #17
Source File: windapsearch.py    From windapsearch with GNU General Public License v3.0 6 votes vote down vote up
def getDefaultNamingContext(self):
        try:
            newCon = ldap.initialize('ldap://{}'.format(self.dc_ip))
            newCon.simple_bind_s('', '')
            res = newCon.search_s("", ldap.SCOPE_BASE, '(objectClass=*)')
            rootDSE = res[0][1]
        except ldap.LDAPError as e:
            print("[!] Error retrieving the root DSE")
            print("[!] {}".format(e))
            sys.exit(1)

        if 'defaultNamingContext' not in rootDSE:
            print("[!] No defaultNamingContext found!")
            sys.exit(1)

        defaultNamingContext = rootDSE['defaultNamingContext'][0].decode()

        self.domainBase = defaultNamingContext
        newCon.unbind()
        return defaultNamingContext 
Example #18
Source File: forms.py    From flask-ldap-login with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def validate_ldap(self):
        'Validate the username/password data against ldap directory'
        ldap_mgr = current_app.ldap_login_manager
        username = self.username.data
        password = self.password.data
        try:
            userdata = ldap_mgr.ldap_login(username, password)
        except ldap.INVALID_CREDENTIALS:
            flash("Invalid LDAP credentials", 'danger')
            return False
        except ldap.LDAPError as err:
            if isinstance(err.message, dict):
                message = err.message.get('desc', str(err))
            else:
                message = str(err.message)
            flash(message, 'danger')
            return False

        if userdata is None:
            flash("Invalid LDAP credentials", 'danger')
            return False

        self.user = ldap_mgr._save_user(username, userdata)
        return True 
Example #19
Source File: __init__.py    From OctoPrint-LDAP with GNU Affero General Public License v3.0 6 votes vote down vote up
def ldap_search(self, ldap_filter, base=None, scope=ldap.SCOPE_SUBTREE):
        if not base:
            base = self.plugin_settings().get(["search_base"])
        try:
            client = self.get_ldap_client()
            if client is not None:
                self._logger.debug("Searching LDAP, base: %s and filter: %s" % (base, ldap_filter))
                result = client.search_s(base, scope, ldap_filter)
                client.unbind_s()
                if result:
                    dn, data = result[0]
                    """
                    # Dump LDAP search query results to logger
                    self._logger.debug("dn: %s" % dn)
                    for key, value in data.iteritems():
                        self._logger.debug("%s: %s" % (key, value))
                    """
                    return dict(dn=dn, data=data)
        except ldap.LDAPError as e:
            self._logger.error(json.dumps(e.message))
        return None 
Example #20
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 #21
Source File: ldapadmin.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
def check_user_belong_to_group(self, uid, group_cn='员工'):
        """
        查询 用户 是否归属于某个组
        :param uid: 用户uid , Ex: 'ssoadmin'
        :param group_cn: 归属组cn , Ex: '黑名单'
        :return: True|None
        """
        result = None
        try:
            search = self.ldap_search_dn(value=group_cn, value_type='cn')
            if search is None:
                raise ldap.LDAPError('未查询到相应 id')

            member_list = search[0][1].get('memberUid', [])
            if uid in member_list:
                result = True
        except ldap.LDAPError as e:
            logger.error('获取用户%s与组%s关系失败,原因为: %s' % (uid, group_cn, str(e)))
        return result 
Example #22
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 #23
Source File: __init__.py    From ssh-ldap-pubkey with MIT License 5 votes vote down vote up
def find_dn_by_login(self, login):
        """Returns Distinguished Name (DN) of the user with the given ``login``.

        Arguments:
            login (str): The login name of the user to find.
        Returns:
            str: User's DN.
        Raises:
            UserEntryNotFoundError: If the ``login`` is not found.
            ldap.LDAPError:
        """
        conf = self.conf
        filter_s = conf.filter
        # RFC4515 requires filters to be wrapped with parenthesis '(' and ')'.
        # Over-wrapped filters are invalid! e.g. '((uid=x))'
        #
        # OpenLDAP permits simple filters to omit parenthesis entirely:
        # e.g. 'uid=x' is automatically treated as '(uid=x)'
        #
        # The OpenLDAP behavior is taken as a given in many uses, which can
        # lead to bad assumptions merging filters, because over-wrapped filters
        # ARE still rejected.
        #
        # To cope with these cases, only wrap the incoming filter in
        # parenthesis if it does NOT already have them.
        if filter_s[0] != '(':
            filter_s = '(%s)' % filter_s
        filter_s = "(&%s(%s=%s))" % (filter_s, conf.login_attr, login)

        result = self._conn.search_s(conf.base, conf.scope, filter_s, ['dn'])
        if not result:
            raise UserEntryNotFoundError("No user with login '%s' found." % login, 2)

        return result[0][0] 
Example #24
Source File: __init__.py    From ssh-ldap-pubkey with MIT License 5 votes vote down vote up
def find_pubkeys(self, login):
        """Return public keys of the user with the given ``login``.

        Arguments:
            login (str): The login name of the user.
        Returns:
            List[str]: A list of public keys.
        Raises:
            UserEntryNotFoundError: If the ``login`` is not found.
            ldap.LDAPError:
        """
        return self._find_pubkeys(self.find_dn_by_login(login)) 
Example #25
Source File: ldap.py    From zoe with Apache License 2.0 5 votes vote down vote up
def auth(self, username, password):
        """Authenticate the user or raise an exception."""
        search_filter = "uid=" + username
        try:
            if self.sasl:
                self.connection.sasl_interactive_bind_s('', self.sasl_auth)
            else:
                self.connection.bind_s(get_conf().ldap_bind_user, get_conf().ldap_bind_password)
        except ldap.LDAPError:
            log.error('Unknown LDAP BIND user or wrong password.')
            raise zoe_api.exceptions.ZoeAuthException('Unknown LDAP BIND user or wrong password.')

        try:
            result = self.connection.search_s(self.base_dn, ldap.SCOPE_SUBTREE, search_filter)
            if len(result) == 0:
                raise zoe_api.exceptions.ZoeAuthException('Unknown user or wrong password.')
            result = self.connection.compare_s(search_filter + ',' + self.base_dn, 'userPassword', password)
            if result == 0:
                raise zoe_api.exceptions.ZoeAuthException('Unknown user or wrong password.')
        except ldap.LDAPError as ex:
            if ex.args[0]['desc'] == 'Invalid credentials':
                raise zoe_api.exceptions.ZoeAuthException('Unknown user or wrong password.')
            else:
                log.exception("LDAP exception")
                zoe_api.exceptions.ZoeAuthException('LDAP error.')
        finally:
            self.connection.unbind_s()
        return True 
Example #26
Source File: forms.py    From docassemble with MIT License 5 votes vote down vote up
def da_unique_email_validator(form, field):
    if daconfig['ldap login'].get('enable', False) and daconfig['ldap login'].get('base dn', None) is not None and daconfig['ldap login'].get('bind email', None) is not None and daconfig['ldap login'].get('bind password', None) is not None:
        ldap_server = daconfig['ldap login'].get('server', 'localhost').strip()
        base_dn = daconfig['ldap login']['base dn'].strip()
        search_filter = daconfig['ldap login'].get('search pattern', "mail=%s") % (form.email.data,)
        connect = ldap.initialize('ldap://' + ldap_server)
        try:
            connect.simple_bind_s(daconfig['ldap login']['bind email'], daconfig['ldap login']['bind password'])
            if len(connect.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter)) > 0:
                raise ValidationError(word("This Email is already in use. Please try another one."))
        except ldap.LDAPError:
            pass
    if daconfig.get('confirm registration', False):
        return True
    return unique_email_validator(form, field) 
Example #27
Source File: externalldap.py    From quay with Apache License 2.0 5 votes vote down vote up
def ping(self):
        try:
            with self._ldap.get_connection():
                pass
        except ldap.INVALID_CREDENTIALS:
            return (False, "LDAP Admin dn or password is invalid")
        except ldap.LDAPError as lde:
            logger.exception("Exception when trying to health check LDAP")
            return (False, str(lde))

        return (True, None) 
Example #28
Source File: externalldap.py    From quay with Apache License 2.0 5 votes vote down vote up
def at_least_one_user_exists(self):
        logger.debug("Checking if any users exist in LDAP")
        try:
            with self._ldap.get_connection():
                pass
        except ldap.INVALID_CREDENTIALS:
            return (None, "LDAP Admin dn or password is invalid")

        has_pagination = not self._force_no_pagination
        with self._ldap.get_connection() as conn:
            for user_search_dn in self._user_dns:
                search_flt = "(objectClass=*)"
                search_flt = self._add_user_filter(search_flt)

                lc = ldap.controls.libldap.SimplePagedResultsControl(
                    criticality=True, size=1, cookie=""
                )
                try:
                    if has_pagination:
                        msgid = conn.search_ext(
                            user_search_dn, ldap.SCOPE_SUBTREE, search_flt, serverctrls=[lc]
                        )
                        _, rdata, _, serverctrls = conn.result3(msgid)
                    else:
                        msgid = conn.search(user_search_dn, ldap.SCOPE_SUBTREE, search_flt)
                        _, rdata = conn.result(msgid)

                    for entry in rdata:  # Handles both lists and iterators.
                        return (True, None)

                except ldap.LDAPError as lde:
                    return (False, str(lde) or "Could not find DN %s" % user_search_dn)

        return (False, None) 
Example #29
Source File: user.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def ldap_search(self, searchFilter, baseDN):
        searchScope = ldap.SCOPE_SUBTREE
        retrieveAttributes = None

        try:
            conn = self.ldap_init_conn()
            if Setting().get('ldap_type') == 'ad':
                conn.simple_bind_s(
                    "{0}@{1}".format(self.username,
                                     Setting().get('ldap_domain')),
                    self.password)
            else:
                conn.simple_bind_s(Setting().get('ldap_admin_username'),
                                   Setting().get('ldap_admin_password'))
            ldap_result_id = conn.search(baseDN, searchScope, searchFilter,
                                         retrieveAttributes)
            result_set = []

            while 1:
                result_type, result_data = conn.result(ldap_result_id, 0)
                if (result_data == []):
                    break
                else:
                    if result_type == ldap.RES_SEARCH_ENTRY:
                        result_set.append(result_data)
            return result_set

        except ldap.LDAPError as e:
            current_app.logger.error(e)
            current_app.logger.debug('baseDN: {0}'.format(baseDN))
            current_app.logger.debug(traceback.format_exc()) 
Example #30
Source File: sync_ldap_groups_to_svn_authz.py    From sync-ldap-groups-to-svn-authz with MIT License 5 votes vote down vote up
def main():
  """This function is the entry point for this script."""
  
  parser = None

  # If all necessary options are not properly set in the current script file
  # (see at the top of the script)
  if not are_properties_set():
    # Attempt to load them from the command line parameters
    parser = create_cli_parser()
    load_cli_properties(parser)

  # if some properties are not set at this point, there is an error
  if not are_properties_set():
    sys.stderr.write("There is not enough information to proceed.\n")
    
    for prop in get_unset_properties():
      sys.stderr.write("'%s' was not passed\n" % prop)

    sys.stderr.write("\n")
    if parser != None:
      parser.print_help()
      parser.exit()

  # Allow user to type in password if missing
  global bind_password

  if bind_password == None:
    bind_password = getpass.getpass("Please provide the bind DN password: ")

  ldapobject = None
  groups = None
  memberships = None

  try:
    ldapobject = bind()
  except ldap.LDAPError, error_message:
    sys.stderr.write("Could not connect to %s. Error: %s \n" % (url, error_message))
    sys.exit(1)