Authenticates a user using the specified credentials.

@param string $username      The users AD username
@param string $password      The users AD password
@param bool   $preventRebind

@return bool

@throws AdldapException
779973
public function authenticate($username, $password, $preventRebind = false)
    {
        $auth = false;

        try {
            if ($this->getUseSSO()) {
                // If SSO is enabled, we'll try binding over kerberos
                $remoteUser = $this->getRemoteUserInput();
                $kerberos = $this->getKerberosAuthInput();

                /*
                 * If the remote user input equals the username we're
                 * trying to authenticate, we'll perform the bind
                 */
                if ($remoteUser == $username) {
                    $auth = $this->bindUsingKerberos($kerberos);
                }
            } else {
                // Looks like SSO isn't enabled, we'll bind regularly instead
                $auth = $this->bindUsingCredentials($username, $password);
            }
        } catch (AdldapException $e) {
            if ($preventRebind === true) {
                /*
                 * Binding failed and we're not allowed
                 * to rebind, we'll return false
                 */
                return $auth;
            }
        }

        // If we're allowed to rebind, we'll rebind as administrator
        if ($preventRebind === false) {
            $adminUsername = $this->getAdminUsername();
            $adminPassword = $this->getAdminPassword();

            $this->bindUsingCredentials($adminUsername, $adminPassword);

            if (!$this->ldapConnection->isBound()) {
                throw new AdldapException('Rebind to Active Directory failed. AD said: '.$this->ldapConnection->getLastError());
            }
        }

        return $auth;
    }
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
620286
public function logIn($username,$password) {
		session_regenerate_id(true);
		$sql = "SELECT id,password FROM {$this->primaryTable} WHERE username=:username AND inactive=0";
		if ($result = $this->executeQuery($sql,array(":username"=>$username))) {
			if (password_verify($password,$result[0]['password'])) {
				$this->setSessionUserId($result[0]['id']);
				return true;			
			}
		}
		return false;
	}
54815
function user_activate($username) {
        $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);

        $ldapconnection = $this->ldap_connect();

        $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
        switch ($this->config->user_type)  {
            case 'edir':
                $newinfo['loginDisabled'] = 'FALSE';
                break;
            case 'rfc2307':
            case 'rfc2307bis':
                // Remember that we add a '*' character in front of the
                // external password string to 'disable' the account. We just
                // need to remove it.
                $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
                                array('userPassword'));
                $info = ldap_get_entries($ldapconnection, $sr);
                $info[0] = array_change_key_case($info[0], CASE_LOWER);
                $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
                break;
            case 'ad':
                // We need to unset the ACCOUNTDISABLE bit in the
                // userAccountControl attribute ( see
                // http://support.microsoft.com/kb/305144 )
                $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
                                array('userAccountControl'));
                $info = ldap_get_entries($ldapconnection, $sr);
                $info[0] = array_change_key_case($info[0], CASE_LOWER);
                $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
                                                 & (~AUTH_AD_ACCOUNTDISABLE);
                break;
            default:
                print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
        }
        $result = ldap_modify($ldapconnection, $userdn, $newinfo);
        $this->ldap_close();
        return $result;
    }
296763
public static function login($username, $password) {
		if ($user = user::find($username, $password)) {
			self::$user           = $user;
			self::$isGuest        = false;
			$_SESSION["username"] = $username;

			return true;
		}

		return false;
	}
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;
	}
441913
public function getUser($username, $password)
    {
        $authHash = $this->hashUserNameAndPassword($username, $password);
        $body     = json_encode(['clientType' => 'wp-plugin']);

        try {
            $response = $this->client->post(
              $this->loginurl, [
                'headers' => ['Authorization' => 'Basic ' . $authHash],
                'verify'  => $this->certFile,
                'body'    => $body //wp-plugin value makes session not expire
              ]);
            $this->response = $response->getBody();

        } catch (ClientException $e) {
            $response       = [
              'code'     => $e->getCode(),
              'response' => $e->getMessage(),
              'error'    => true
            ];
            $this->response = json_encode($response);

        } catch (ConnectException $e) {
            $message = 'Can not connect to Leadpages Server:';
            $response = $this->parseException($e, $message);
            $this->response = $response;
        }

        return $this;
    }
1190852
public function authentication($username, $password)
    {
        $endpoint = sprintf('authentication?username=%s', urlencode($username));
        $parameters['value'] = $password;
        return $this->apiClient->callEndpoint(
            $endpoint,
            $parameters,
            null,
            HttpMethod::REQUEST_POST
        );
    }
1284506
protected function _bindUser($username, $password)
    {
        $config = $this->getConfig();
        try {
            $ldapBind = $this->_ldap->bind($config['bindDN']($username), $password);
            if ($ldapBind === true) {
                $this->_ldap->unbind();

                return new ArrayObject([
                    $config['fields'][self::CREDENTIAL_USERNAME] => $username
                ]);
            }
        } catch (ErrorException $e) {
            $this->_handleLdapError($e->getMessage());
        }
        $this->_ldap->unbind();

        return null;
    }
1017305
protected function validateData(User $user, $username, $password, $passwordConfirmed)
    {
        $errors = array();
        
        // Username
        if ($this->isUsernameInUse($username, $user)) {
            $errors[] = new Error(Error::GENERAL_ERROR, $this->translate('The username is already in use.', '\\Zepi\\Web\\AccessControl'));
        }        
        
        // If the user is new or the password is not empty we need to validate
        // the password.
        if ($this->shouldValidatePassword($user, $password)) {
            // Password
            if (strlen($password) < 8) {
                $errors[] = new Error(Error::WRONG_INPUT, $this->translate('The password needs at least 8 characters.', '\\Zepi\\Web\\AccessControl'));
            }
            
            if ($password != $passwordConfirmed) {
                $errors[] = new Error(Error::WRONG_INPUT, $this->translate('The passwords are not equal.', '\\Zepi\\Web\\AccessControl'));
            }
        }
        
        if (count($errors) > 0) {
            return $errors;
        }
        
        return true;
    }
139925
public function authenticate($username, $password) {

    // Get some things.
    $client = $this->getClient();
    $parameters = $this->getAuthParams();
    $endpoint = $this->getEndpoint();
    $code = NULL;

    $response = $client->get($endpoint,
      ['query' => $parameters, 'auth' => [$username, $password]]
    );

    $code = $response->getStatusCode();
    $this->setLastResponse($response);

    // @todo: handle non 200 responses with error logging.
    switch ($code) {
      case '200':
        $body = $response->getBody();
        $json = json_decode($body->getContents());
        if (empty($json)) {
          throw new \Exception("Could not get JSON from body.");
        }
        $this->setAuthApiToken($json->access_token);
        $this->setAuthApiTokenExpires($json->expires_in);
        break;
    }

    return $this;
  }
934189
public function login($username, $password)
    {
        $args = array($username, $password);
        $token = $this->_soapAdapter->call('login', $args);
        $this->setToken($token);
        return $token;
    }
277073
public function checkUserCredentials($username, $password)
    {
        $userDetails = $this->getUserDetails($username);

        return $userDetails && $userDetails['password'] && $userDetails['password'] === $password;
    }
903262
public function login($username, $password) {
        $credentials = array(
            'lgname' => $username,
            'lgpassword' => $password
        );
        $firstlogin = $this->client->login($credentials);
        $this->failOnError("Wiki login failed.", $firstlogin);
        $resultMsg = $firstlogin['login']['result'];
        if ($resultMsg != "NeedToken" && $resultMsg != "Success") {
            throw new SessionException("Wiki login failed: $resultMsg");
        }
        
        if ($resultMsg == "NeedToken") {
            $secondLogin = $this->client->login(array_merge(array(
                'lgtoken' => $firstlogin['login']['token']
            ), $credentials));
            $this->failOnError("Wiki login failed.", $secondLogin);
            $resultMsg = $secondLogin['login']['result'];
            if ($resultMsg != "Success") {
                throw new SessionException("Wiki login failed: $resultMsg");
            }
            $this->tokencache['login'] =  $firstlogin['login']['token'];
        }
    }
761506
public function checkUserCredentials($username, $password)
    {
        if ($user = $this->getUser($username)) {
            return $this->checkPassword($user, $password);
        }

        return false;
    }
176668
public function authenticate($username, $password)
    {
        try {
            $response = $this->client->adminInitiateAuth([
                'AuthFlow' => 'ADMIN_NO_SRP_AUTH',
                'AuthParameters' => [
                    'USERNAME' => $username,
                    'PASSWORD' => $password,
                    'SECRET_HASH' => $this->cognitoSecretHash($username),
                ],
                'ClientId' => $this->appClientId,
                'UserPoolId' => $this->userPoolId,
            ]);

            return $this->handleAuthenticateResponse($response->toArray());
        } catch (CognitoIdentityProviderException $e) {
            throw CognitoResponseException::createFromCognitoException($e);
        }
    }
492290
public function checkUserCredentials($username, $password)
    {
        $user = $this->getUserDetails($username);

        return $user && $user['password'] === $password;
    }