How to use the ldap3.core.exceptions function in ldap3

To help you get started, we’ve selected a few ldap3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Morgan-Stanley / treadmill / lib / python / treadmill / admin / _ldap.py View on Github external
ldap = self.ldap

        if not ldap.result or 'result' not in ldap.result:
            return

        exception_type = None
        result_code = ldap.result['result']
        if result_code == 68:
            exception_type = ldap_exceptions.LDAPEntryAlreadyExistsResult
        elif result_code == 32:
            exception_type = ldap_exceptions.LDAPNoSuchObjectResult
        elif result_code == 50:
            exception_type =\
                ldap_exceptions.LDAPInsufficientAccessRightsResult
        elif result_code != 0:
            exception_type = ldap_exceptions.LDAPOperationResult

        if exception_type:
            raise exception_type(result=ldap.result['result'],
                                 description=ldap.result['description'],
                                 dn=ldap.result['dn'],
                                 message=ldap.result['message'],
                                 response_type=ldap.result['type'])
github nickw444 / flask-ldap3-login / flask_ldap3_login / __init__.py View on Github external
try:
            connection.bind()
            log.debug("Authentication was successful for user '{}'".format(username))
            response.status = AuthenticationResponseStatus.success
            # Get user info here.

            user_info = self.get_user_info(dn=bind_user, _connection=connection)
            response.user_dn = bind_user
            response.user_id = username
            response.user_info = user_info
            if self.config.get("LDAP_SEARCH_FOR_GROUPS"):
                response.user_groups = self.get_user_groups(
                    dn=bind_user, _connection=connection
                )

        except ldap3.core.exceptions.LDAPInvalidCredentialsResult:
            log.debug(
                "Authentication was not successful for user '{}'".format(username)
            )
            response.status = AuthenticationResponseStatus.fail
        except Exception as e:
            log.error(e)
            response.status = AuthenticationResponseStatus.fail

        self.destroy_connection(connection)
        return response
github frappe / frappe / frappe / integrations / doctype / ldap_settings / ldap_settings.py View on Github external
bind_type = ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.ssl_tls_mode == "StartTLS" else True

			conn = ldap3.Connection(
				server=server,
				user=base_dn,
				password=password,
				auto_bind=bind_type,
				read_only=True,
				raise_exceptions=True)

			return conn

		except ImportError:
			msg = _("Please Install the ldap3 library via pip to use ldap functionality.")
			frappe.throw(msg, title=_("LDAP Not Installed"))
		except ldap3.core.exceptions.LDAPInvalidCredentialsResult:
			frappe.throw(_("Invalid username or password"))
		except Exception as ex:
			frappe.throw(_(str(ex)))
github Karaage-Cluster / python-tldap / tldap / base.py View on Github external
modlist = tldap.modlist.addModlist(moddict)

        # what database should we be using?
        using = self._alias
        assert using is not None
        c = tldap.connections[using]

        # what to do if transaction is reversed
        def onfailure():
            self._alias = None
            self._db_values = None

        # do it
        try:
            c.add(self._dn, modlist, onfailure)
        except ldap3.core.exceptions.LDAPEntryAlreadyExistsResult:
            raise self.AlreadyExists(
                "Object with dn %r already exists doing add" % (self._dn,))

        # save new values
        self._alias = using
        self._db_values = tldap.helpers.CaseInsensitiveDict(moddict)
github Morgan-Stanley / treadmill / lib / python / treadmill / admin / __init__.py View on Github external
def wrapper(*args, **kwargs):
        """Wrapper that does the exception translation."""
        try:
            return func(*args, **kwargs)
        except ldap_exceptions.LDAPNoSuchObjectResult as err:
            raise exc.NoSuchObjectResult(err)
        except ldap_exceptions.LDAPEntryAlreadyExistsResult as err:
            raise exc.AlreadyExistsResult(err)
        except ldap_exceptions.LDAPBindError as err:
            raise exc.AdminConnectionError(err)
        except ldap_exceptions.LDAPInsufficientAccessRightsResult as err:
            raise exc.AdminAuthorizationError(err)
        except ldap_exceptions.LDAPOperationResult as err:
            raise exc.AdminBackendError(err)
github agdsn / sipa / sipa / model / wu / ldap_utils.py View on Github external
bind_user = "uid={},{}".format(self.username,
                                           CONF['search_user_base'])
            bind_password = self.password

        self.server = ldap3.Server(CONF['uri'],
                                   get_info=ldap3.SCHEMA,
                                   tls=None,  # accept any certificate
                                   connect_timeout=5)
        try:
            super().__init__(server=self.server,
                             user=bind_user,
                             password=bind_password,
                             check_names=True,
                             raise_exceptions=True,
                             auto_bind=ldap3.AUTO_BIND_TLS_BEFORE_BIND)
        except ldap3.core.exceptions.LDAPInvalidCredentialsResult:
            raise PasswordInvalid
        except ldap3.core.exceptions.LDAPUnwillingToPerformResult:
            # Empty password, treat as invalid
            raise PasswordInvalid
        except ldap3.core.exceptions.LDAPInsufficientAccessRightsResult:
            raise LDAPConnectionError
github Morgan-Stanley / treadmill / lib / python / treadmill / admin / _ldap.py View on Github external
"""
        if ldap is None:
            ldap = self.ldap

        if not ldap.result or 'result' not in ldap.result:
            return

        exception_type = None
        result_code = ldap.result['result']
        if result_code == 68:
            exception_type = ldap_exceptions.LDAPEntryAlreadyExistsResult
        elif result_code == 32:
            exception_type = ldap_exceptions.LDAPNoSuchObjectResult
        elif result_code == 50:
            exception_type =\
                ldap_exceptions.LDAPInsufficientAccessRightsResult
        elif result_code != 0:
            exception_type = ldap_exceptions.LDAPOperationResult

        if exception_type:
            raise exception_type(result=ldap.result['result'],
                                 description=ldap.result['description'],
                                 dn=ldap.result['dn'],
                                 message=ldap.result['message'],
                                 response_type=ldap.result['type'])
github DataDog / integrations-core / openldap / datadog_checks / openldap / openldap.py View on Github external
def _handle_threads_entry(self, entry, tags):
        cn = self._extract_common_name(entry.entry_dn)
        try:
            value = entry["monitoredInfo"].value
        except ldap3.core.exceptions.LDAPKeyError:
            return
        if cn in ["max", "max_pending"]:
            self.gauge("{}.threads.{}".format(self.METRIC_PREFIX, cn), value, tags=tags)
        elif cn in ["open", "starting", "active", "pending", "backload"]:
            self.gauge("{}.threads".format(self.METRIC_PREFIX), value, tags=tags + ["status:{}".format(cn)])
github SecureAuthCorp / impacket / examples / addcomputer.py View on Github external
user = '%s\\%s' % (self.__domain, self.__username)
            tls = ldap3.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2)
            try:
                ldapServer = ldap3.Server(connectTo, use_ssl=True, port=self.__port, get_info=ldap3.ALL, tls=tls)
                if self.__doKerberos:
                    ldapConn = ldap3.Connection(ldapServer)
                    self.LDAP3KerberosLogin(ldapConn, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,
                                                 self.__aesKey, kdcHost=self.__kdcHost)
                elif self.__hashes is not None:
                    ldapConn = ldap3.Connection(ldapServer, user=user, password=self.__hashes, authentication=ldap3.NTLM)
                    ldapConn.bind()
                else:
                    ldapConn = ldap3.Connection(ldapServer, user=user, password=self.__password, authentication=ldap3.NTLM)
                    ldapConn.bind()

            except ldap3.core.exceptions.LDAPSocketOpenError:
                #try tlsv1
                tls = ldap3.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1)
                ldapServer = ldap3.Server(connectTo, use_ssl=True, port=self.__port, get_info=ldap3.ALL, tls=tls)
                if self.__doKerberos:
                    ldapConn = ldap3.Connection(ldapServer)
                    self.LDAP3KerberosLogin(ldapConn, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,
                                                 self.__aesKey, kdcHost=self.__kdcHost)
                elif self.__hashes is not None:
                    ldapConn = ldap3.Connection(ldapServer, user=user, password=self.__hashes, authentication=ldap3.NTLM)
                    ldapConn.bind()
                else:
                    ldapConn = ldap3.Connection(ldapServer, user=user, password=self.__password, authentication=ldap3.NTLM)
                    ldapConn.bind()
github Karaage-Cluster / python-tldap / tldap / database / __init__.py View on Github external
assert dn is not None

    if create:
        # Add new entry
        mod_list = _python_to_mod_new(changes)
        try:
            connection.add(dn, mod_list)
        except ldap3.core.exceptions.LDAPEntryAlreadyExistsResult:
            raise ObjectAlreadyExists(
                "Object with dn %r already exists doing add" % dn)
    else:
        mod_list = _python_to_mod_modify(changes)
        if len(mod_list) > 0:
            try:
                connection.modify(dn, mod_list)
            except ldap3.core.exceptions.LDAPNoSuchObjectResult:
                raise ObjectDoesNotExist(
                    "Object with dn %r doesn't already exist doing modify" % dn)

    # get new values
    python_data = table(changes.src.to_dict())
    python_data = python_data.merge(changes.to_dict())
    python_data = python_data.on_load(python_data, database)
    return python_data