Use the input configuration to instantiate and return
        a ldap3 Connection object.
336723
def _ldap_connection_factory(self, config):
        
        ldap_url = config['ldap_url']
        bind_dn = config['bind_dn']
        bind_password = config['bind_password']

        if not ldap_url:
            raise LdapAttributeStoreError("ldap_url is not configured")
        if not bind_dn:
            raise LdapAttributeStoreError("bind_dn is not configured")
        if not bind_password:
            raise LdapAttributeStoreError("bind_password is not configured")

        pool_size = config['pool_size']
        pool_keepalive = config['pool_keepalive']

        server = ldap3.Server(config['ldap_url'])

        satosa_logging(logger, logging.DEBUG, "Creating a new LDAP connection", None)
        satosa_logging(logger, logging.DEBUG, "Using LDAP URL {}".format(ldap_url), None)
        satosa_logging(logger, logging.DEBUG, "Using bind DN {}".format(bind_dn), None)
        satosa_logging(logger, logging.DEBUG, "Using pool size {}".format(pool_size), None)
        satosa_logging(logger, logging.DEBUG, "Using pool keep alive {}".format(pool_keepalive), None)

        try:
            connection = ldap3.Connection(
                            server,
                            bind_dn,
                            bind_password,
                            auto_bind=True,
                            client_strategy=ldap3.REUSABLE,
                            pool_size=pool_size,
                            pool_keepalive=pool_keepalive
                            )

        except LDAPException as e:
            msg = "Caught exception when connecting to LDAP server: {}".format(e)
            satosa_logging(logger, logging.ERROR, msg, None)
            raise LdapAttributeStoreError(msg)

        satosa_logging(logger, logging.DEBUG, "Successfully connected to LDAP server", None)

        return connection
38065
public static function fromDefaults() {
		$handler = new HandlerLDAP(
			config('ldap.host'),
			config('ldap.basedn'),
			config('ldap.dn'),
			config('ldap.password'),
			config('ldap.search_user_id'),
			config('ldap.search_username'),
			config('ldap.search_user_mail'),
			config('ldap.search_user_mail_array')
		);
		$handler->setVersion(config('ldap.version'));
		$handler->setOverlayDN(config('ldap.overlay_dn'));

		// configuration for add operations
		$handler->setAddBaseDN(config('ldap.add_base_dn'));
		$handler->setAddDN(config('ldap.add_dn'));
		$handler->setAddPassword(config('ldap.add_pw'));

		// configuration for modify operations
		$handler->setModifyMethod(config('ldap.modify_method'));
		$handler->setModifyBaseDN(config('ldap.modify_base_dn'));
		$handler->setModifyDN(config('ldap.modify_dn'));
		$handler->setModifyPassword(config('ldap.modify_pw'));

		return $handler;
	}
748669
def get_ldap(cls, global_options=None):
        
        if cls.ldap is None:
            import ldap.filter

            # Support for python-ldap < 2.0.6
            try:
                import ldap.dn
            except ImportError:
                from django_auth_ldap import dn
                ldap.dn = dn

            cls.ldap = ldap

        # Apply global LDAP options once
        if (not cls._ldap_configured) and (global_options is not None):
            for opt, value in global_options.items():
                cls.ldap.set_option(opt, value)

            cls._ldap_configured = True

        return cls.ldap
848546
def _bind(username, password, anonymous=False, opts=None):
    '''
    
    '''
    # Get config params; create connection dictionary
    basedn = _config('basedn', opts=opts)
    scope = _config('scope', opts=opts)
    connargs = {}
    # config params (auth.ldap.*)
    params = {
        'mandatory': ['uri', 'server', 'port', 'starttls', 'tls',
                      'no_verify', 'anonymous',
                      'accountattributename', 'activedirectory'],
        'additional': ['binddn', 'bindpw', 'filter', 'groupclass',
                       'auth_by_group_membership_only'],
    }

    paramvalues = {}

    for param in params['mandatory']:
        paramvalues[param] = _config(param, opts=opts)

    for param in params['additional']:
        paramvalues[param] = _config(param, mandatory=False, opts=opts)

    paramvalues['anonymous'] = anonymous
    if paramvalues['binddn']:
        # the binddn can also be composited, e.g.
        #   - {{ username }}@domain.com
        #   - cn={{ username }},ou=users,dc=company,dc=tld
        # so make sure to render it first before using it
        paramvalues['binddn'] = _render_template(paramvalues['binddn'], username)
        paramvalues['binddn'] = ldap.filter.escape_filter_chars(paramvalues['binddn'])

    if paramvalues['filter']:
        escaped_username = ldap.filter.escape_filter_chars(username)
        paramvalues['filter'] = _render_template(paramvalues['filter'], escaped_username)

    # Only add binddn/bindpw to the connargs when they're set, as they're not
    # mandatory for initializing the LDAP object, but if they're provided
    # initially, a bind attempt will be done during the initialization to
    # validate them
    if paramvalues['binddn']:
        connargs['binddn'] = paramvalues['binddn']
        if paramvalues['bindpw']:
            params['mandatory'].append('bindpw')

    for name in params['mandatory']:
        connargs[name] = paramvalues[name]

    if not paramvalues['anonymous']:
        if paramvalues['binddn'] and paramvalues['bindpw']:
            # search for the user's DN to be used for the actual authentication
            _ldap = _LDAPConnection(**connargs).ldap
            log.debug(
                'Running LDAP user dn search with filter:%s, dn:%s, '
                'scope:%s', paramvalues['filter'], basedn, scope
            )
            result = _ldap.search_s(basedn, int(scope), paramvalues['filter'])
            if not result:
                log.warning('Unable to find user %s', username)
                return False
            elif len(result) > 1:
                # Active Directory returns something odd.  Though we do not
                # chase referrals (ldap.set_option(ldap.OPT_REFERRALS, 0) above)
                # it still appears to return several entries for other potential
                # sources for a match.  All these sources have None for the
                # CN (ldap array return items are tuples: (cn, ldap entry))
                # But the actual CNs are at the front of the list.
                # So with some list comprehension magic, extract the first tuple
                # entry from all the results, create a list from those,
                # and count the ones that are not None.  If that total is more than one
                # we need to error out because the ldap filter isn't narrow enough.
                cns = [tup[0] for tup in result]
                total_not_none = sum(1 for c in cns if c is not None)
                if total_not_none > 1:
                    log.error('LDAP lookup found multiple results for user %s', username)
                    return False
                elif total_not_none == 0:
                    log.error('LDAP lookup--unable to find CN matching user %s', username)
                    return False

            connargs['binddn'] = result[0][0]
        if paramvalues['binddn'] and not paramvalues['bindpw']:
            connargs['binddn'] = paramvalues['binddn']
    elif paramvalues['binddn'] and not paramvalues['bindpw']:
        connargs['binddn'] = paramvalues['binddn']

    # Update connection dictionary with the user's password
    connargs['bindpw'] = password

    # Attempt bind with user dn and password
    if paramvalues['anonymous']:
        log.debug('Attempting anonymous LDAP bind')
    else:
        log.debug('Attempting LDAP bind with user dn: %s', connargs['binddn'])
    try:
        ldap_conn = _LDAPConnection(**connargs).ldap
    except Exception:
        connargs.pop('bindpw', None)  # Don't log the password
        log.error('Failed to authenticate user dn via LDAP: %s', connargs)
        log.debug('Error authenticating user dn via LDAP:', exc_info=True)
        return False
    log.debug('Successfully authenticated user dn via LDAP: %s', connargs['binddn'])
    return ldap_conn
401141
public function connect()
    {
        $this->connect = ldap_connect($this->hostname, $this->port);

        if (!$this->connect) {
            throw new ConnectionException($this);
        }

        // Set Ldap Version to 3
        ldap_set_option($this->connect, LDAP_OPT_PROTOCOL_VERSION, 3);

        if (!is_null($this->username) && !is_null($this->password)) {
            if (!@ldap_bind($this->connect, $this->username, $this->password)) {
                throw new BadIdentificationException($this);
            }
        }

        return new Client($this->connect);
    }
23275
protected function _connectLdap()
    {
        $config = $this->getConfig();

        $this->_ldap->connect(
            $config['host'],
            $config['port'],
            $this->getConfig('options')
        );
    }
1145118
public InitializeResult initialize() throws WIMApplicationException {
        final String METHODNAME = "initialize";
        iEnvironment = new Hashtable<String, Object>();
        iEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_SUN_SPI);

        String urlPrefix = null;
        if (iSSLEnabled) {
            iEnvironment.put(LDAP_ENV_PROP_FACTORY_SOCKET, WAS_SSL_SOCKET_FACTORY);
            iEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
            urlPrefix = LDAP_URL_SSL_PREFIX;
        } else {
            urlPrefix = LDAP_URL_PREFIX;
        }

        List<String> urlList = new ArrayList<String>();

        /*
         * Add the primary server to the URL list.
         */
        if (iPrimaryServer == null || iPrimaryServer.hostname == null || iPrimaryServer.hostname.trim().isEmpty()) {
            return InitializeResult.MISSING_PRIMARY_SERVER;
        }
        String mainHost = iPrimaryServer.hostname;
        int mainPort = iPrimaryServer.port;
        urlList.add(urlPrefix + mainHost.trim() + ":" + mainPort);

        /*
         * Add the fail-over servers to the URL list.
         */
        for (HostPort failoverServer : iFailoverServers) {
            String ldapHost = failoverServer.hostname;
            if (ldapHost == null || ldapHost.trim().isEmpty()) {
                continue;
            }

            if (!(ldapHost.startsWith("[") && ldapHost.endsWith("]"))) {
                if (isIPv6Addr(ldapHost)) {
                    ldapHost = formatIPv6Addr(ldapHost);
                }
            }

            if (failoverServer.port != null) {
                urlList.add(urlPrefix + ldapHost.trim() + ":" + failoverServer.port);
            }
        }

        if (urlList != null && urlList.size() > 0) {
            String url = urlList.get(0);
            iEnvironment.put(ENVKEY_URL_LIST, urlList);
            iEnvironment.put(ENVKEY_ACTIVE_URL, url);
            iEnvironment.put(Context.PROVIDER_URL, url);
        }

        /*
         * If no administrative credentials, allow anonymous bind.
         */
        if (iBindDN != null && !iBindDN.isEmpty()) {
            iEnvironment.put(Context.SECURITY_PRINCIPAL, iBindDN);
            SerializableProtectedString sps = iBindPassword;
            String password = sps == null ? "" : new String(sps.getChars());
            String decodedPassword = PasswordUtil.passwordDecode(password.trim());

            /*
             * A password is required if we had a bind DN.
             */
            if (decodedPassword == null || decodedPassword.length() == 0) {
                return InitializeResult.MISSING_PASSWORD;
            }
            iEnvironment.put(Context.SECURITY_CREDENTIALS, new ProtectedString(decodedPassword.toCharArray()));
        }

        /*
         * Set the LDAP connection time out
         */
        if (iConnectTimeout != null) {
            iEnvironment.put(LDAP_ENV_PROP_CONNECT_TIMEOUT, iConnectTimeout.toString());
        } else {
            iEnvironment.put(LDAP_ENV_PROP_CONNECT_TIMEOUT, String.valueOf(DEFAULT_CONNECT_TIMEOUT));
        }

        /*
         * Set the LDAP read time out.
         */
        if (iReadTimeout != null) {
            iEnvironment.put(LDAP_ENV_PROP_READ_TIMEOUT, iReadTimeout.toString());
        } else {
            iEnvironment.put(LDAP_ENV_PROP_READ_TIMEOUT, String.valueOf(DEFAULT_READ_TIMEOUT));
        }

        /*
         * TODO Support different authentication mechanisms.
         *
         * String authen = (String) configProps.get(ConfigConstants.CONFIG_PROP_AUTHENTICATION);
         * iEnvironment.put(Context.SECURITY_AUTHENTICATION, authen);
         */

        /*
         * Determine referral handling behavior.
         */
        iEnvironment.put(Context.REFERRAL, iReferral);

        /*
         * TODO Support dereferencing aliases.
         *
         * String derefAliases = (String) configProps.get(ConfigConstants.CONFIG_PROP_DEREFALIASES);
         * if (!"always".equalsIgnoreCase(derefAliases)) {
         * iEnvironment.put(LdapConstants.LDAP_ENV_PROP_DEREF_ALIASES, derefAliases);
         * }
         */

        /*
         * Add binary attribute names
         */
        if (iBinaryAttributeNames != null && iBinaryAttributeNames.length() > 0) {
            iEnvironment.put(LDAP_ENV_PROP_ATTRIBUTES_BINARY, iBinaryAttributeNames);
        }

        /*
         * TODO Support other environment properties.
         *
         * // Initialize additional environment properties. These environ props will overwrite the above settings.
         * List envProps = server.getList(CONFIG_PROP_ENVIRONMENT_PROPERTIES);
         * for (int i = 0; i < envProps.size(); i++) {
         * DataObject envProp = (DataObject) envProps.get(i);
         * String name = envProp.getString(CONFIG_PROP_NAME);
         * String value = envProp.getString(CONFIG_PROP_VALUE);
         * iEnvironment.put(name, value);
         * }
         */

        /*
         * Create Context Pool
         */
        try {
            createContextPool(iInitPoolSize, null);
        } catch (NamingException e) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, METHODNAME + " Can not create context pool: " + e.toString(true));
            }
        }

        if (tc.isDebugEnabled()) {
            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\nLDAP Server(s): ").append(urlList).append("\n");
            strBuf.append("\tBind DN: ").append(iBindDN).append("\n");
            // strBuf.append("\tAuthenticate: ").append(authen).append("\n");
            strBuf.append("\tReferral: ").append(iReferral).append("\n");
            strBuf.append("\tBinary Attributes: ").append(iBinaryAttributeNames).append("\n");
            // strBuf.append("\tAdditional Evn Props: ").append(envProps);

            if (iContextPoolEnabled) {
                strBuf.append("\nContext Pool is enabled: ").append("\n");
                strBuf.append("\tInitPoolSize: ").append(iInitPoolSize).append("\n");
                strBuf.append("\tMaxPoolSize: ").append(iMaxPoolSize).append("\n");
                strBuf.append("\tPrefPoolSize: ").append(iPrefPoolSize).append("\n");
                strBuf.append("\tPoolTimeOut: ").append(iPoolTimeOut).append("\n");
                strBuf.append("\tPoolWaitTime: ").append(iPoolWaitTime);
            } else {
                strBuf.append("\nContext Pool is disabled");
            }
            Tr.debug(tc, METHODNAME + strBuf.toString());
        }

        return InitializeResult.SUCCESS;
    }
776822
def create_connection():
    """"""
    # REDIS_URL is defined in .env and loaded into the environment by Honcho
    redis_url = os.getenv('REDIS_URL')
    # If it's not defined, use the Redis default
    if not redis_url:
        redis_url = 'redis://localhost:6379'
    urlparse.uses_netloc.append('redis')
    url = urlparse.urlparse(redis_url)
    return redis.StrictRedis(
        host=url.hostname,
        port=url.port,
        db=0,
        password=url.password
    )
79953
def _begin(self, connection, filterargs=(), escape=True):
        
        if escape:
            filterargs = self._escape_filterargs(filterargs)

        try:
            filterstr = self.filterstr % filterargs
            msgid = connection.search(force_str(self.base_dn),
                                      self.scope, force_str(filterstr))
        except ldap.LDAPError as e:
            msgid = None
            logger.error(u"search('%s', %d, '%s') raised %s" %
                         (self.base_dn, self.scope, filterstr, pprint.pformat(e)))

        return msgid
747952
def _connect(**kwargs):
    '''
    
    '''
    connargs = {}
    for name in ['uri', 'server', 'port', 'tls', 'no_verify', 'binddn',
                 'bindpw', 'anonymous']:
        connargs[name] = _config(name, **kwargs)

    return _LDAPConnection(**connargs).ldap
312320
def from_config(cls, config):
        """"""
        auth_key = None
        password_file = config["authentication.passwordFile"]
        if password_file is not None:
            try:
                auth_key = open(config["authentication.passwordFile"]).read()
                auth_key = re.sub(r"\s", "", auth_key)
            except IOError:
                LOG.error("Could not load password file!")
                sys.exit(1)
        password = config["authentication.password"]
        if password is not None:
            auth_key = password
        connector = Connector(
            mongo_address=config["mainAddress"],
            doc_managers=config["docManagers"],
            oplog_checkpoint=os.path.abspath(config["oplogFile"]),
            collection_dump=config["onlyDump"] or not config["noDump"],
            only_dump=config["onlyDump"],
            batch_size=config["batchSize"],
            continue_on_error=config["continueOnError"],
            auth_username=config["authentication.adminUsername"],
            auth_key=auth_key,
            fields=config["fields"],
            exclude_fields=config["exclude_fields"],
            ns_set=config["namespaces.include"],
            ex_ns_set=config["namespaces.exclude"],
            dest_mapping=config["namespaces.mapping"],
            namespace_options=config["namespaces.namespace_options"],
            gridfs_set=config["namespaces.gridfs"],
            ssl_certfile=config["ssl.sslCertfile"],
            ssl_keyfile=config["ssl.sslKeyfile"],
            ssl_ca_certs=config["ssl.sslCACerts"],
            ssl_cert_reqs=config["ssl.sslCertificatePolicy"],
            tz_aware=config["timezoneAware"],
        )
        return connector
289415
def load_ldap_config(self):  # pragma: no cover
        """"""
        try:
            with open('{}/ldap_info.yaml'.format(self.config_dir),
                      'r') as FILE:
                config = yaml.load(FILE)
                self.host = config['server']
                self.user_dn = config['user_dn']
                self.port = config['port']
                self.basedn = config['basedn']
                self.mail_domain = config['mail_domain']
                self.service_ou = config['service_ou']
        except OSError as err:
            print('{}: Config file ({}/ldap_info.yaml) not found'.format(
                type(err), self.config_dir))
1267538
def create_ip(self):
        """"""
        return Ip(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
649842
def connection(self, name=None):
        
        name, type = self._parse_connection_name(name)

        if name not in self._connections:
            logger.debug("Initiating connection %s" % name)
            connection = self._make_connection(name)

            self._set_connection_for_type(connection, type)

            self._connections[name] = self._prepare(connection)

        return self._connections[name]
126239
def populate_user(self):
        
        user = None

        try:
            # self.attrs will only be non-None if we were able to load this user
            # from the LDAP directory, so this filters out nonexistent users.
            if self.attrs is not None:
                self._get_or_create_user(force_populate=True)

            user = self._user
        except ldap.LDAPError as e:
            results = ldap_error.send(
                self.backend.__class__,
                context="populate_user",
                user=self._user,
                exception=e,
            )
            if len(results) == 0:
                logger.warning(
                    "Caught LDAPError while authenticating {}: {}".format(
                        self._username, pprint.pformat(e)
                    )
                )
        except Exception as e:
            logger.warning("{} while authenticating {}".format(e, self._username))
            raise

        return user
11605
public void initialize() {
        /*
         * Use a set to ensure we ignore duplicates.
         */
        val attributes = new HashSet<String>();
        LOGGER.debug("Initializing LDAP attribute configuration...");
        if (StringUtils.isNotBlank(this.principalIdAttribute)) {
            LOGGER.debug("Configured to retrieve principal id attribute [{}]", this.principalIdAttribute);
            attributes.add(this.principalIdAttribute);
        }
        if (this.principalAttributeMap != null && !this.principalAttributeMap.isEmpty()) {
            val attrs = this.principalAttributeMap.keySet();
            attributes.addAll(attrs);
            LOGGER.debug("Configured to retrieve principal attribute collection of [{}]", attrs);
        }
        if (authenticator.getReturnAttributes() != null) {
            val authenticatorAttributes = CollectionUtils.wrapList(authenticator.getReturnAttributes());
            if (!authenticatorAttributes.isEmpty()) {
                LOGGER.debug("Filtering authentication entry attributes [{}] based on authenticator attributes [{}]", authenticatedEntryAttributes, authenticatorAttributes);
                attributes.removeIf(authenticatorAttributes::contains);
            }
        }
        this.authenticatedEntryAttributes = attributes.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
        LOGGER.debug("LDAP authentication entry attributes for the authentication request are [{}]", (Object[]) this.authenticatedEntryAttributes);
    }
430195
def _get_connection(self):
        
        if self._connection is None:
            uri = self.settings.SERVER_URI
            if callable(uri):
                if func_supports_parameter(uri, "request"):
                    uri = uri(self._request)
                else:
                    warnings.warn(
                        "Update AUTH_LDAP_SERVER_URI callable %s.%s to accept "
                        "a positional `request` argument. Support for callables "
                        "accepting no arguments will be removed in a future "
                        "version." % (uri.__module__, uri.__name__),
                        DeprecationWarning,
                    )
                    uri = uri()

            self._connection = self.backend.ldap.initialize(uri, bytes_mode=False)

            for opt, value in self.settings.CONNECTION_OPTIONS.items():
                self._connection.set_option(opt, value)

            if self.settings.START_TLS:
                logger.debug("Initiating TLS")
                self._connection.start_tls_s()

        return self._connection