Binds to the LDAP server with AUTH_LDAP_BIND_DN and
        AUTH_LDAP_BIND_PASSWORD.
970355
def _bind(self):
        
        self._bind_as(self.settings.BIND_DN, self.settings.BIND_PASSWORD, sticky=True)
1261471
def bind(cls, app, *paths, methods=None, name=None, view=None):
        """"""
        # Register self in admin
        if view is None:
            app.ps.admin.register(cls)
            if not paths:
                paths = ('%s/%s' % (app.ps.admin.cfg.prefix, name or cls.name),)
            cls.url = paths[0]
        return super(AdminHandler, cls).bind(app, *paths, methods=methods, name=name, view=view)
117202
public function boot()
    {
        // Register the lDAP auth provider.
        Auth::provider('ldap', function ($app, array $config) {
            return $this->makeUserProvider($app['hash'], $config);
        });

        if ($this->app->runningInConsole()) {
            $config = __DIR__ . '/Config/auth.php';

            $this->publishes([
                $config => config_path('ldap_auth.php'),
            ]);
        }

        // Register the import command.
        $this->commands(Import::class);
    }
577450
def to_h
      {
          enable_db_auth: enable_db_auth?,
          enable_ldap_auth: enable_ldap_auth?,
          ldap_host: ldap_host.to_s,
          ldap_port: ldap_port.to_s.to_i,
          ldap_ssl: ldap_ssl?,
          ldap_base_dn: ldap_base_dn.to_s,
          ldap_browse_user: ldap_browse_user.to_s,
          ldap_browse_password: ldap_browse_password.to_s,
          ldap_auto_activate: ldap_auto_activate?,
          ldap_system_admin_groups: ldap_system_admin_groups.to_s,
      }
    end
634190
public function connect($server, $user = null, $password = null, $isAuthentication = false)
    {
        if ($server && isset($server['host'])) {
            if (isset($server['port']) && is_numeric($server['port'])) {
                $this->connect = ldap_connect($server['host'], $server['port']);
            } else {
                $this->connect = ldap_connect($server['host']);
            }

            ldap_set_option($this->connect, LDAP_OPT_PROTOCOL_VERSION, $server['protocol_version']);

            try {
                if ($isAuthentication && $this->connect && $user && $password) {
                    $user = $this->findDnFromUserName($server, $user);

                    return (false === $user) ? $user : ldap_bind($this->connect, $user, $password);
                } elseif ($this->connect) {
                    return ldap_bind($this->connect);
                }
            } catch (\Exception $e) {
                throw new InvalidLdapCredentialsException();
            }
        }
    }
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
1303073
public function anonymous_bind()
	{
		if (!$this->isConnected())
		{
			if (!$this->connect())
			{
				return false;
			}
		}

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

		return $this->isBound;
	}
533179
function _connect( $host, $username, $password, $ldapbase)
	{
		global $LDAP_CONNECT_OPTIONS;

		if ( !function_exists( 'ldap_connect' ) ) return null;

		if (strpos($host,'ldap://') === 0 || strpos($host,'ldaps://') === 0) {
			$this->_connectionID = @ldap_connect($host);
		} else {
			$conn_info = array( $host,$this->port);

			if ( strstr( $host, ':' ) ) {
				$conn_info = explode( ':', $host );
			}

			$this->_connectionID = @ldap_connect( $conn_info[0], $conn_info[1] );
		}
		if (!$this->_connectionID) {
			$e = 'Could not connect to ' . $conn_info[0];
			$this->_errorMsg = $e;
			if ($this->debug) ADOConnection::outp($e);
			return false;
		}
		if( count( $LDAP_CONNECT_OPTIONS ) > 0 ) {
			$this->_inject_bind_options( $LDAP_CONNECT_OPTIONS );
		}

		if ($username) {
			$bind = @ldap_bind( $this->_connectionID, $username, $password );
		} else {
			$username = 'anonymous';
			$bind = @ldap_bind( $this->_connectionID );
		}

		if (!$bind) {
			$e = sprintf($this->_bind_errmsg,ldap_error($this->_connectionID));
			$this->_errorMsg = $e;
			if ($this->debug) ADOConnection::outp($e);
			return false;
		}
		$this->_errorMsg = '';
		$this->database = $ldapbase;
		return $this->_connectionID;
	}
1316055
public void authenticate(String username, String password) {
        ldapTemplate.authenticate(query().where("objectClass").is("simpleSecurityObject").and("cn").is(username), password);
        LOGGER.info("Successfully authenticated " + username);
    }
903460
protected function initializeLdapAuthenticationHandler() {
        $ldapSettings = $this->_passwordAuthenticationPlatformSettings;
        $ldapAuthenticationHandler = new MultiotpWrapper();
        
        $ldapAuthenticationHandler->SetLdapServerPassword($this->getCurrentPassword());
        $ldapAuthenticationHandler->SetLdapBindDn($this->getCurrentUsername());
        $ldapAuthenticationHandler->SetLdapAccountSuffix($ldapSettings['ldap_account_suffix']);
        $ldapAuthenticationHandler->SetLdapBaseDn($ldapSettings['base_dn']);
        $ldapAuthenticationHandler->SetLdapCnIdentifier($ldapSettings['cn_identifier']);
        $ldapAuthenticationHandler->SetLdapDomainControllers($ldapSettings['domain_controllers']);
        $ldapAuthenticationHandler->SetLdapGroupAttribute($ldapSettings['group_attribute']);
        $ldapAuthenticationHandler->SetLdapGroupCnIdentifier($ldapSettings['group_cn_identifier']);
        $ldapAuthenticationHandler->SetLdapServerType($ldapSettings['ldap_server_type']);
        $ldapAuthenticationHandler->SetLdapNetworkTimeout($ldapSettings['network_timeout']);
        $ldapAuthenticationHandler->SetLdapPort($ldapSettings['port']);
        $ldapAuthenticationHandler->SetLdapRecursiveGroups($ldapSettings['recursive_groups']);
        $ldapAuthenticationHandler->SetLdapTimeLimit($ldapSettings['time_limit']);
        $ldapAuthenticationHandler->SetLdapSsl($ldapSettings['use_ssl']);
        $ldapAuthenticationHandler->SetLdapCacheOn($ldapSettings['cache_support']);
        $ldapAuthenticationHandler->SetLdapCacheFolder($ldapSettings['cache_folder']);
        $ldapAuthenticationHandler->SetLdapExpiredPasswordValid($ldapSettings['expired_password_valid']);
        
        $this->ldapAuthenticationHandler = $ldapAuthenticationHandler;
    }
951817
def ldap_login(self, username, password):
        
        self.connect()

        if self.config.get('USER_SEARCH'):
            result = self.bind_search(username, password)
        else:
            result = self.direct_bind(username, password)
        return result
427399
def _bind_for_search(anonymous=False, opts=None):
    '''
    
    '''
    # Get config params; create connection dictionary
    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

    # 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
            return _LDAPConnection(**connargs).ldap
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
1217873
def _get_anon_bind(self):
        
        r = self._search(
            'cn=config',
            '(objectClass=*)',
            ['nsslapd-allow-anonymous-access'],
            scope=ldap.SCOPE_BASE
        )
        dn, attrs = r[0]
        state = attrs.get('nsslapd-allow-anonymous-access')[0].decode('utf-8', 'ignore')
        if state in ['on', 'off', 'rootdse']:
            r = state
        else:
            r = None
        self._anon_bind = r
577058
def bind(self, source, dest, destmeth):
        
        self.connect(source, getattr(dest, destmeth))
617214
private function _connect()
    {
        $rcube = rcube::get_instance();

        if ($this->ready) {
            return true;
        }

        if (!is_array($this->prop['hosts'])) {
            $this->prop['hosts'] = array($this->prop['hosts']);
        }

        // try to connect + bind for every host configured
        // with OpenLDAP 2.x ldap_connect() always succeeds but ldap_bind will fail if host isn't reachable
        // see http://www.php.net/manual/en/function.ldap-connect.php
        foreach ($this->prop['hosts'] as $host) {
            // skip host if connection failed
            if (!$this->ldap->connect($host)) {
                continue;
            }

            // See if the directory is writeable.
            if ($this->prop['writable']) {
                $this->readonly = false;
            }

            $bind_pass = $this->prop['bind_pass'];
            $bind_user = $this->prop['bind_user'];
            $bind_dn   = $this->prop['bind_dn'];

            $this->base_dn        = $this->prop['base_dn'];
            $this->groups_base_dn = $this->prop['groups']['base_dn'] ?: $this->base_dn;

            // User specific access, generate the proper values to use.
            if ($this->prop['user_specific']) {
                // No password set, use the session password
                if (empty($bind_pass)) {
                    $bind_pass = $rcube->get_user_password();
                }

                // Get the pieces needed for variable replacement.
                if ($fu = ($rcube->get_user_email() ?: $this->prop['username'])) {
                    list($u, $d) = explode('@', $fu);
                }
                else {
                    $d = $this->mail_domain;
                }

                $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string

                // resolve $dc through LDAP
                if (!empty($this->prop['domain_filter']) && !empty($this->prop['search_bind_dn']) &&
                        method_exists($this->ldap, 'domain_root_dn')) {
                    $this->ldap->bind($this->prop['search_bind_dn'], $this->prop['search_bind_pw']);
                    $dc = $this->ldap->domain_root_dn($d);
                }

                $replaces = array('%dn' => '', '%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);

                // Search for the dn to use to authenticate
                if ($this->prop['search_base_dn'] && $this->prop['search_filter']
                    && (strstr($bind_dn, '%dn') || strstr($this->base_dn, '%dn') || strstr($this->groups_base_dn, '%dn'))
                ) {
                    $search_attribs = array('uid');
                     if ($search_bind_attrib = (array)$this->prop['search_bind_attrib']) {
                         foreach ($search_bind_attrib as $r => $attr) {
                             $search_attribs[] = $attr;
                             $replaces[$r] = '';
                         }
                     }

                    $search_bind_dn = strtr($this->prop['search_bind_dn'], $replaces);
                    $search_base_dn = strtr($this->prop['search_base_dn'], $replaces);
                    $search_filter  = strtr($this->prop['search_filter'], $replaces);

                    $cache_key = 'DN.' . md5("$host:$search_bind_dn:$search_base_dn:$search_filter:"
                        .$this->prop['search_bind_pw']);

                    if ($this->cache && ($dn = $this->cache->get($cache_key))) {
                        $replaces['%dn'] = $dn;
                    }
                    else {
                        $ldap = $this->ldap;
                        if (!empty($search_bind_dn) && !empty($this->prop['search_bind_pw'])) {
                            // To protect from "Critical extension is unavailable" error
                            // we need to use a separate LDAP connection
                            if (!empty($this->prop['vlv'])) {
                                $ldap = new rcube_ldap_generic($this->prop);
                                $ldap->config_set(array('cache' => $this->cache, 'debug' => $this->debug));
                                if (!$ldap->connect($host)) {
                                    continue;
                                }
                            }

                            if (!$ldap->bind($search_bind_dn, $this->prop['search_bind_pw'])) {
                                continue;  // bind failed, try next host
                            }
                        }

                        $res = $ldap->search($search_base_dn, $search_filter, 'sub', $search_attribs);
                        if ($res) {
                            $res->rewind();
                            $replaces['%dn'] = key($res->entries(TRUE));

                            // add more replacements from 'search_bind_attrib' config
                            if ($search_bind_attrib) {
                                $res = $res->current();
                                foreach ($search_bind_attrib as $r => $attr) {
                                    $replaces[$r] = $res[$attr][0];
                                }
                            }
                        }

                        if ($ldap != $this->ldap) {
                            $ldap->close();
                        }
                    }

                    // DN not found
                    if (empty($replaces['%dn'])) {
                        if (!empty($this->prop['search_dn_default']))
                            $replaces['%dn'] = $this->prop['search_dn_default'];
                        else {
                            rcube::raise_error(array(
                                'code' => 100, 'type' => 'ldap',
                                'file' => __FILE__, 'line' => __LINE__,
                                'message' => "DN not found using LDAP search."), true);
                            continue;
                        }
                    }

                    if ($this->cache && !empty($replaces['%dn'])) {
                        $this->cache->set($cache_key, $replaces['%dn']);
                    }
                }

                // Replace the bind_dn and base_dn variables.
                $bind_dn              = strtr($bind_dn, $replaces);
                $this->base_dn        = strtr($this->base_dn, $replaces);
                $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);

                // replace placeholders in filter settings
                if (!empty($this->prop['filter']))
                    $this->prop['filter'] = strtr($this->prop['filter'], $replaces);

                foreach (array('base_dn','filter','member_filter') as $k) {
                    if (!empty($this->prop['groups'][$k]))
                        $this->prop['groups'][$k] = strtr($this->prop['groups'][$k], $replaces);
                }

                if (is_array($this->prop['group_filters'])) {
                    foreach ($this->prop['group_filters'] as $i => $gf) {
                        if (!empty($gf['base_dn']))
                            $this->prop['group_filters'][$i]['base_dn'] = strtr($gf['base_dn'], $replaces);
                        if (!empty($gf['filter']))
                            $this->prop['group_filters'][$i]['filter'] = strtr($gf['filter'], $replaces);
                    }
                }

                if (empty($bind_user)) {
                    $bind_user = $u;
                }
            }

            if (empty($bind_pass)) {
                $this->ready = true;
            }
            else {
                if (!empty($bind_dn)) {
                    $this->ready = $this->ldap->bind($bind_dn, $bind_pass);
                }
                else if (!empty($this->prop['auth_cid'])) {
                    $this->ready = $this->ldap->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
                }
                else {
                    $this->ready = $this->ldap->sasl_bind($bind_user, $bind_pass);
                }
            }

            // connection established, we're done here
            if ($this->ready) {
                break;
            }

        }  // end foreach hosts

        if (!is_resource($this->ldap->conn)) {
            rcube::raise_error(array('code' => 100, 'type' => 'ldap',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => "Could not connect to any LDAP server, last tried $host"), true);

            return false;
        }

        return $this->ready;
    }
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.")