Attempts to bind to Active Directory

 If it works it returns the connection

 If it fails it raises and exception
768298
def bind
            conn = Net::LDAP.new :host => @config[:server],
                                 :port => @config[:port],
                                 :base => @config[:base]
            if @config[:encryption]
               conn.encryption @config[:encryption]
            end
            
            raise "Anonymous Bind is disabled" if @config[:password] == "" && !(@config[:anonymous_bind])
            
            conn.auth "#{@config[:username]}@#{@config[:domain]}", @config[:password]
            
            begin
                Timeout::timeout(10){
                    if conn.bind
                        return conn
                    else
                        raise 'Query User Rejected'
                    end
                }
            rescue Timeout::Error
                raise 'Unable to connect to LDAP Server'
            rescue Errno::ECONNRESET
              if @config[:allow_fallback]
                @config[:port] = @config[:allow_fallback]
                @config[:encryption] = false
                return Adauth::Connection.new(@config).bind
              end
            end
        end
1355820
def get_connection(self, *args, **kwargs):
        
        conn = super(SSLAdapter, self).get_connection(*args, **kwargs)
        if conn.assert_hostname != self.assert_hostname:
            conn.assert_hostname = self.assert_hostname
        return conn
536479
public void process(Connection connection, String directory) throws Exception
   {
      connection.setAutoCommit(true);

      //
      // Retrieve meta data about the connection
      //
      DatabaseMetaData dmd = connection.getMetaData();

      String[] types =
      {
         "TABLE"
      };

      FileWriter fw = new FileWriter(directory);
      PrintWriter pw = new PrintWriter(fw);

      pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      pw.println();
      pw.println("<database>");

      ResultSet tables = dmd.getTables(null, null, null, types);
      while (tables.next() == true)
      {
         processTable(pw, connection, tables.getString("TABLE_NAME"));
      }

      pw.println("</database>");

      pw.close();

      tables.close();
   }
704994
def get_new_connection(self, conn_params):
        """"""
        connection = ldap.ldapobject.ReconnectLDAPObject(
            uri=conn_params['uri'],
            retry_max=conn_params['retry_max'],
            retry_delay=conn_params['retry_delay'],
            bytes_mode=False)

        options = conn_params['options']
        for opt, value in options.items():
            if opt == 'query_timeout':
                connection.timeout = int(value)
            elif opt == 'page_size':
                self.page_size = int(value)
            else:
                connection.set_option(opt, value)

        if conn_params['tls']:
            connection.start_tls_s()

        connection.simple_bind_s(
            conn_params['bind_dn'],
            conn_params['bind_pw'],
        )
        return connection
1093694
protected function _bindLdapAdminUser()
    {
        $connect = $this->_getLinkId();
        if (!$connect) {
            jLog::log('ldapdao: impossible to connect to ldap', 'auth');
            return false;
        }

        if ($this->_params['adminUserDn'] == '') {
            $bind = ldap_bind($connect);
        } else {
            $bind = ldap_bind($connect, $this->_params['adminUserDn'], $this->_params['adminPassword']);
        }
        if (!$bind) {
            if ($this->_params['adminUserDn'] == '') {
                jLog::log('ldapdao: impossible to authenticate to ldap as anonymous admin user', 'auth');
            } else {
                jLog::log('ldapdao: impossible to authenticate to ldap with admin user '.$this->_params['adminUserDn'], 'auth');
            }
            ldap_close($connect);
            return false;
        }
        return $connect;
    }
200537
def auth(username, password):
    '''
    
    '''
    if not HAS_LDAP:
        log.error('LDAP authentication requires python-ldap module')
        return False

    bind = None

    # If bind credentials are configured, verify that we receive a valid bind
    if _config('binddn', mandatory=False) and _config('bindpw', mandatory=False):
        search_bind = _bind_for_search(anonymous=_config('anonymous', mandatory=False))

        # If username & password are not None, attempt to verify they are valid
        if search_bind and username and password:
            bind = _bind(username, password,
                         anonymous=_config('auth_by_group_membership_only', mandatory=False)
                         and _config('anonymous', mandatory=False))
    else:
        bind = _bind(username, password,
                     anonymous=_config('auth_by_group_membership_only', mandatory=False)
                     and _config('anonymous', mandatory=False))

    if bind:
        log.debug('LDAP authentication successful')
        return bind

    log.error('LDAP _bind authentication FAILED')
    return False
1303073
public function anonymous_bind()
	{
		if (!$this->isConnected())
		{
			if (!$this->connect())
			{
				return false;
			}
		}

		$this->isBound = ldap_bind($this->resource);

		return $this->isBound;
	}
447863
def get_or_connect(cls, **kwargs):
        
        try:
            inst = cls.get(**kwargs)
            created = False
        except DoesNotExist:
            inst = cls(**kwargs)
            created = True
        except Exception:
            raise
        return inst, created
1110033
public static function connect() :void {

		// configure the database and get the dns
		$dsn = self::configureAndGetDSN();

		// try to connect
		self::$_handle = new \PDO(
			$dsn, 
			self::$_config['username'] ?: null, 
			self::$_config['password'] ?: null
		);

		// check if connection the connexion failed
		if(!self::$_handle) {
			// throw an exception if it failed
			Throw new Exception('Database::connect() : Failed to connect', 500);
		}

		// if a before statement has to be executed
		if(self::$_config['before']) {
			// execute the before statement
			self::$_handle->query(self::$_config['before']);
		}
	}
235892
private boolean executeConnect() 
        throws IOException, HttpException {

        this.connectMethod = new ConnectMethod(this.hostConfiguration);
        this.connectMethod.getParams().setDefaults(this.hostConfiguration.getParams());
        String agent = (String) getParams().getParameter(PARAM_DEFAULT_USER_AGENT_CONNECT_REQUESTS);
        if (agent != null) {
            this.connectMethod.setRequestHeader("User-Agent", agent);
        }
        
        int code;
        for (;;) {
            if (!this.conn.isOpen()) {
                this.conn.open();
            }
            if (this.params.isAuthenticationPreemptive()
                    || this.state.isAuthenticationPreemptive()) {
                LOG.debug("Preemptively sending default basic credentials");
                this.connectMethod.getProxyAuthState().setPreemptive();
                this.connectMethod.getProxyAuthState().setAuthAttempted(true);
            }
            try {
                authenticateProxy(this.connectMethod);
            } catch (AuthenticationException e) {
                LOG.error(e.getMessage(), e);
            }
            applyConnectionParams(this.connectMethod);                    
            this.connectMethod.execute(state, this.conn);
            code = this.connectMethod.getStatusCode();
            boolean retry = false;
            AuthState authstate = this.connectMethod.getProxyAuthState(); 
            authstate.setAuthRequested(code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
            if (authstate.isAuthRequested()) {
                if (processAuthenticationResponse(this.connectMethod)) {
                    retry = true;
                }
            }
            if (!retry) {
                break;
            }
            if (this.connectMethod.getResponseBodyAsStream() != null) {
                this.connectMethod.getResponseBodyAsStream().close();
            }
        }
        if ((code >= 200) && (code < 300)) {
            this.conn.tunnelCreated();
            // Drop the connect method, as it is no longer needed
            this.connectMethod = null;
            return true;
        } else {
            return false;
        }
    }
1246503
private function connect()
    {
        if (!$this->isConnected) {
            parent::__construct(
                $this->dsn,
                $this->server->getUsername(),
                $this->server->getPassword(),
                $this->driverOptions
            );
            parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            parent::setAttribute(
                PDO::ATTR_STATEMENT_CLASS,
                [__NAMESPACE__ . '\\' . self::PDO_STATEMENT_CLASS, [$this]]
            );

            $this->isConnected = true;
        }
    }
1237125
def _authenticate_user_dn(self, password):
        
        if self.dn is None:
            raise self.AuthenticationFailed("failed to map the username to a DN.")

        try:
            sticky = self.settings.BIND_AS_AUTHENTICATING_USER

            self._bind_as(self.dn, password, sticky=sticky)
        except ldap.INVALID_CREDENTIALS:
            raise self.AuthenticationFailed("user DN/password rejected by LDAP server.")
71638
def get_conn(cls):
        """"""
        conn = cls._conn
        if conn is None or conn.closed:
            conn = ldap3.Connection(
                settings.CAS_LDAP_SERVER,
                settings.CAS_LDAP_USER,
                settings.CAS_LDAP_PASSWORD,
                client_strategy="RESTARTABLE",
                auto_bind=True
            )
            cls._conn = conn
        return conn
1194055
public function bind($username = null, $password = null, $nosub = 0)
	{
		if (!$this->isConnected())
		{
			if (!$this->connect())
			{
				return false;
			}
		}

		if ($username === null)
		{
			$username = $this->username;
		}

		if ($password === null)
		{
			$password = $this->password;
		}

		$this->setDn($username, $nosub);

		$this->isBound = ldap_bind($this->resource, $this->getDn(), $password);

		return $this->isBound;
	}
874445
public void connect() throws Exception {
        adminClients = new ArrayList<AdminClient>(urls.size());
        // bootstrap from two urls
        Map<String, Cluster> clusterMap = new HashMap<String, Cluster>(urls.size());
        Map<String, StoreDefinition> storeDefinitionMap = new HashMap<String, StoreDefinition>(urls.size());

        for(String url: urls) {
            /* connect to cluster through admin port */
            if(logger.isInfoEnabled()) {
                logger.info("Connecting to bootstrap server: " + url);
            }
            AdminClient adminClient = new AdminClient(url);
            adminClients.add(adminClient);
            /* get Cluster */
            Cluster cluster = adminClient.getAdminClientCluster();
            clusterMap.put(url, cluster);

            Integer nodeId = cluster.getNodeIds().iterator().next();
            /* get StoreDefinition */
            Versioned<List<StoreDefinition>> storeDefinitions = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId);
            StoreDefinition storeDefinition = StoreDefinitionUtils.getStoreDefinitionWithName(storeDefinitions.getValue(),
                    storeName);
            storeDefinitionMap.put(url, storeDefinition);
        }

        /* confirm same number of partitions in all clusters. */
        int partitionCount = 0;
        for(Entry<String, Cluster> entry: clusterMap.entrySet()) {
            int currentPartitionCount = entry.getValue().getNumberOfPartitions();
            if(partitionCount == 0) {
                partitionCount = currentPartitionCount;
            }
            if(partitionCount != currentPartitionCount) {
                logger.error("Partition count of different clusters is not the same: "
                        + partitionCount + " vs " + currentPartitionCount);
                throw new VoldemortException("Will not connect because partition counts differ among clusters.");
            }
        }

        /* calculate nodes to scan */
        for(String url: urls) {
            StoreDefinition storeDefinition = storeDefinitionMap.get(url);
            Cluster cluster = clusterMap.get(url);
            Map<Integer, Integer> partitionToNodeMap = cluster.getPartitionIdToNodeIdMap();

            /* find list of nodeId hosting partition */
            List<Integer> partitionList = new RoutingStrategyFactory().updateRoutingStrategy(storeDefinition,
                    cluster)
                    .getReplicatingPartitionList(partitionId);
            for(int partition: partitionList) {
                Integer nodeId = partitionToNodeMap.get(partition);
                Node node = cluster.getNodeById(nodeId);
                clusterNodeList.add(new ClusterNode(urls.indexOf(url), node));
            }
        }

        /* print config info */
        if(logger.isInfoEnabled()) {
            StringBuilder configInfo = new StringBuilder();
            configInfo.append("TYPE,Store,PartitionId,Node,ZoneId,BootstrapUrl\n");
            for(ClusterNode clusterNode: clusterNodeList) {
                configInfo.append("CONFIG,");
                configInfo.append(storeName + ",");
                configInfo.append(partitionId + ",");
                configInfo.append(clusterNode.getNode().getId() + ",");
                configInfo.append(clusterNode.getNode().getZoneId() + ",");
                configInfo.append(urls.get(clusterNode.getPrefixId()) + "\n");
            }
            for(String line: configInfo.toString().split("\n")) {
                logger.info(line);
            }
        }

        /* calculate retention days and more */
        for(String url: urls) {
            StoreDefinition storeDefinition = storeDefinitionMap.get(url);
            /* retention */
            int storeRetentionDays = 0;
            if(storeDefinition.getRetentionDays() != null) {
                storeRetentionDays = storeDefinition.getRetentionDays().intValue();
            }
            if(retentionDays == null) {
                retentionDays = storeRetentionDays;
            }
            if(retentionDays != storeRetentionDays) {
                if(storeRetentionDays != 0 && (storeRetentionDays < retentionDays)) {
                    retentionDays = storeRetentionDays;
                }
                logger.warn("Retention-days is not consistent between clusters by urls. Will use the shorter.");
            }

            /* replication writes */
            replicationFactor += storeDefinition.getReplicationFactor();

            /* required writes */
            requiredWrites += storeDefinition.getRequiredWrites();
        }
        if(replicationFactor != clusterNodeList.size()) {
            logger.error("Replication factor is not consistent with number of nodes routed to.");
            throw new VoldemortException("Will not connect because replication factor does not accord with number of nodes routed to.");
        }
        retentionChecker = new RetentionChecker(retentionDays);
    }
432165
public function afterMemberLoggedIn()
    {
        if ($this->owner->GUID) {
            try {
                Injector::inst()->get(LDAPService::class)->updateMemberFromLDAP($this->owner);
            } catch (Exception $e) {
                // If the failure is acceptable, then ignore it and return. Otherwise, re-throw the exception
                if ($this->owner->config()->get('allow_update_failure_during_login')) {
                    return;
                }
                throw $e;
            }
        }
    }
846925
def authenticate(self, dn='', password=''):
        
        try:
            self.connection.simple_bind_s(dn, password)
        except tuple(self.failed_authentication_exceptions):
            return False
        else:
            return True