Authenticates the user into the system
@param  boolean $force 				Whether or not to bypass the login process (passwordless logins from HybridAuth)
@return UserIdentity::$errorCode 	The error code associated to the login process
174892
public function authenticate($force=false)
	{
        // Setup everything first
		$this->setup($force);

        // If something bad happened during the setup process, immediately bail with the error code
        if ($this->errorCode != NULL)
            return !$this->errorCode;

        // Validate the users password
        $this->validatePassword();

        // If this user has 5 or more failed password attempts
        if ($this->_attempts->value >= 5)
        {
            // And if they the updated time is still more than 15 minutes ago
            if ((strtotime($this->_attempts->updated) + strtotime("+15 minutes")) >= time())
            {
                // Resave the attempts model so that the updated time is reset
                $this->_attempts->save();

                // Throw an unknown identity error
                $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
            }
            else
            {
                // Automatically re-adjust the lockout time if this has passed.
                $this->_attempts->value = 0;
                $this->_attempts->save();
            }
        }

        // If the user needs two factor authentication
        if ($this->getUser()->needsTwoFactorAuth())
        {
            // If the code isn't supplied, throw an error
            if ($this->twoFactorCode === false)
               $this->errorCode = self::REQUIRE_TWO_FACTOR_AUTH;
            else
            {
                // If the 2fa code is supplied, verify it
                if (!$this->validateTwoFactorCode())
                    $this->errorCode = self::INVALID_TWO_FACTOR_AUTH;
            } 
        }

        // At this point, we should should know if the validation has succeeded or not. If the errorCode has been altered, immediately bail
        if ($this->errorCode != NULL)
            return !$this->errorCode;
        else
            $this->setIdentity();

        return !$this->errorCode;
    }
159356
private function authenticate()
    {
        $form = new RemoteIdentityForm;
        $form->attributes = array(
            'adapter'  => $this->getUserProfile(),
            'provider' => $this->getProvider()
        );

        return $form->login();
    }
352037
public function login($credentials) {
    if (!isset($credentials['login']) || !isset($credentials['password'])) {
      throw new IllegalArgumentException("The parameters 'login' and 'password' are required");
    }
    $config = ObjectFactory::getInstance('configuration');

    $login = $credentials['login'];
    $password = $credentials['password'];

    // try to receive the user with given credentials
    $user = $this->principalFactory->getUser($login, true);

    // check if user exists
    $loginOk = false;
    if ($user != null && $user->isActive()) {
      // check password
      $loginOk = $user->verifyPassword($password);
      if ($loginOk) {
        // load user config initially
        $userConfig = $user->getConfig();
        if (strlen($userConfig) > 0) {
          $config->addConfiguration($userConfig);
        }
        return $user;
      }
    }
    return null;
  }
810990
public function authenticate(): bool
	{
		try {
			$res = $this->request('account/verify_credentials', 'GET');
			return !empty($res->id);

		} catch (Exception $e) {
			if ($e->getCode() === 401) {
				return false;
			}
			throw $e;
		}
	}
219089
private function authBasic(Request $request) {
		$user = $this->findUser($request->getUser());
		if ($user !== null && $this->verifyUser($user, $request->getPassword())) {
			$session = $this->findSession($user);
			if ($session === null) {
				$session = $this->createSession($user);
			}
			$this->authenticated = true;

			return $session;
		}
		return null;
	}
1172921
public function login()
    {
        $identity = $this->getIdentity();

        if ($identity->authenticate($this->newPassword)) {
            return $this->webUser->login($identity, 0);
        }

        return false;
    }
150182
function authenticate($username,$password,$prevent_rebind=false){
        if ($username==NULL || $password==NULL){ return (false); } //prevent null binding
        
        //bind as the user		
        $this->_bind = @ldap_bind($this->_conn,$username.$this->_account_suffix,$password);
        $this->_bind_paged = @ldap_bind($this->_conn_paged,$username.$this->_account_suffix,$password);
        if (!$this->_bind){ return (false); }
        
        //once we've checked their details, kick back into admin mode if we have it
        if ($this->_ad_username!=NULL && !$prevent_rebind){
            $this->_bind = @ldap_bind($this->_conn,$this->_ad_username.$this->_account_suffix,$this->_ad_password);
            $this->_bind_paged = @ldap_bind($this->_conn_paged,$this->_ad_username.$this->_account_suffix,$this->_ad_password);
            if (!$this->_bind){
                // Modified by SysCo/al
                $this->_error = TRUE;
                $this->_error_message = 'FATAL: AD rebind failed.';
                exit();
            } //this should never happen in theory
        }
        
        return (true);
    }
1248138
public function user($authCode = null)
    {
        if ($this->hasInvalidState()) {
            throw new InvalidStateException();
        }

        $params = [
            'auth_code' => $authCode ?: $this->request->get('auth_code'),
        ];

        return $this->parseJSON('json', [self::API_GET_LOGIN_INFO, $params]);
    }
1248174
public function validateSecret(bool $force = false): self
    {
        // If we're running from CLI, secret isn't necessary.
        if ($force || 'cli' !== PHP_SAPI) {
            $secret     = $this->params->getBotParam('secret');
            $secret_get = $this->params->getScriptParam('s');
            if (!isset($secret, $secret_get) || $secret !== $secret_get) {
                throw new InvalidAccessException('Invalid access');
            }
        }

        return $this;
    }
433889
public function getUser($force = false)
    {
        if ($this->nb_user === null || $force) {
            $this->nb_user = null;
            if ($this instanceof CNabuDataObject &&
                $this->contains(NABU_USER_FIELD_ID) &&
                $this->isValueNumeric(NABU_USER_FIELD_ID)
            ) {
                $nb_user = new CNabuUser($this->getValue(NABU_USER_FIELD_ID));
                if ($nb_user->isFetched()) {
                    $this->nb_user = $nb_user;
                }
            }
        }

        return $this->nb_user;
    }
1047808
public function authenticateByCode($provider, string $code)
    {
        $provider_user = $provider->user();

        /** @var \Railken\Amethyst\Repositories\UserRepository */
        $repository = $this->manager->getRepository();

        $user = $repository->findOneByEmail($provider_user->getEmail());

        if (!$user) {
            $result = $this->manager->create([
                'name'     => $provider_user->getNickname() ? $provider_user->getNickname() : $provider_user->getName(),
                'role'     => 'user',
                'password' => str_random(32),
                'email'    => $provider_user->getEmail(),
            ]);

            if (!$result->ok()) {
                return $this->response(['errors' => $result->getSimpleErrors()], Response::HTTP_BAD_REQUEST);
            }

            $user = $result->getResource();
        }

        $token = Container::getInstance()->make(\Laravel\Passport\PersonalAccessTokenFactory::class)->make(
            $user->getKey(),
            'login',
            []
        );

        return $this->response([
            'token_type'   => 'Bearer',
            'expires_in'   => 0,
            'access_token' => $token->accessToken,
        ], Response::HTTP_OK);
    }
1135804
public function read($force = false)
	{
		// initialize the session
		$this->data = array();
		$this->keys = array();
		$this->flash = array();

		// get the session cookie
		$payload = $this->_get_cookie();

		// validate it
		if ($force)
		{
			// a forced session reset
		}
		elseif ($payload === false)
		{
			// no cookie found
		}
		elseif ( ! isset($payload[0]) or ! is_array($payload[0]))
		{
			logger('DEBUG', 'Error: not a valid cookie payload!');
		}
		elseif ($payload[0]['updated'] + $this->config['expiration_time'] <= $this->time->get_timestamp())
		{
			logger('DEBUG', 'Error: session id has expired!');
		}
		elseif ($this->config['match_ip'] and $payload[0]['ip_hash'] !== md5(\Input::ip().\Input::real_ip()))
		{
			logger('DEBUG', 'Error: IP address in the session doesn\'t match this requests source IP!');
		}
		elseif ($this->config['match_ua'] and $payload[0]['user_agent'] !== \Input::user_agent())
		{
			logger('DEBUG', 'Error: User agent in the session doesn\'t match the browsers user agent string!');
		}
		else
		{
			// session is valid, retrieve the payload
			if (isset($payload[0]) and is_array($payload[0])) $this->keys  = $payload[0];
			if (isset($payload[1]) and is_array($payload[1])) $this->data  = $payload[1];
			if (isset($payload[2]) and is_array($payload[2])) $this->flash = $payload[2];
		}

		return parent::read();
	}
157410
public function getKeyAuthClient($forceNew = false)
    {
        if ( ! isset($this->instances[self::CLIENT_KEY]) || $forceNew) {
            $this->instances[self::CLIENT_KEY] = MeetupKeyAuthClient::factory($this->config);
        }

        return $this->instances[self::CLIENT_KEY];
    }
446144
public function checkAdmin($user = NULL, $pass = NULL, $force = false)
    {
        Logger::log('Checking admin session');
        if ((!$this->authorized && !$this->checked) || $force) {
            $admins = $this->getAdmins();
            if (null !== $admins) {
                $request = Request::getInstance();
                //Sacamos las credenciales de la petición
                $user = $user ?: $request->getServer('PHP_AUTH_USER');
                $pass = $pass ?: $request->getServer('PHP_AUTH_PW');
                if (NULL === $user || (array_key_exists($user, $admins) && empty($admins[$user]))) {
                    list($user, $pass) = $this->getAdminFromCookie();
                }
                if (!empty($user) && !empty($admins[$user])) {
                    $auth = $admins[$user]['hash'];
                    $this->authorized = ($auth === sha1($user . $pass));
                    if ($this->authorized) {
                        $this->updateAdmin($user , $admins[$user]['profile']);
                        ResponseHelper::setCookieHeaders([
                            [
                                'name' => $this->getHash(),
                                'value' => base64_encode("$user:$pass"),
                                'http' => true,
                                'domain' => '',
                            ]
                        ]);
                        $this->setSessionKey(self::LOGGED_USER_TOKEN, base64_encode("{$user}:{$pass}"));
                    }
                } else {
                    $this->admin = null;
                    $this->setSessionKey(self::ADMIN_ID_TOKEN, null);
                }
                $this->checked = true;
            }
        }

        return $this->authorized || self::isTest();
    }
385049
public function authenticate()
    {
        if (!empty($this->hashedPassword)) {
            return $this->authenticateWithPassword($this->login, $this->getTokenAuthSecret());
        } elseif (is_null($this->login)) {
            return $this->authenticateWithToken($this->token_auth);
        } elseif (!empty($this->login)) {
            return $this->authenticateWithLoginAndToken($this->token_auth, $this->login);
        }

        return new AuthResult(AuthResult::FAILURE, $this->login, $this->token_auth);
    }
476587
public function authenticate(array $data, HTTPRequest $request, ValidationResult &$result = null)
    {
        $result = $result ?: ValidationResult::create();
        /** @var LDAPService $service */
        $service = Injector::inst()->get(LDAPService::class);
        $login = trim($data['Login']);
        if (Email::is_valid_address($login)) {
            if (Config::inst()->get(self::class, 'allow_email_login') != 'yes') {
                $result->addError(
                    _t(
                        __CLASS__ . '.PLEASEUSEUSERNAME',
                        'Please enter your username instead of your email to log in.'
                    )
                );
                return null;
            }
            $username = $service->getUsernameByEmail($login);

            // No user found with this email.
            if (!$username) {
                if (Config::inst()->get(self::class, 'fallback_authenticator') === 'yes') {
                    if ($fallbackMember = $this->fallbackAuthenticate($data, $request)) {
                        {
                            return $fallbackMember;
                        }
                    }
                }

                $result->addError(_t(__CLASS__ . '.INVALIDCREDENTIALS', 'Invalid credentials'));
                return null;
            }
        } else {
            $username = $login;
        }

        $serviceAuthenticationResult = $service->authenticate($username, $data['Password']);
        $success = $serviceAuthenticationResult['success'] === true;

        if (!$success) {
            /*
             * Try the fallback method if admin or it failed for anything other than invalid credentials
             * This is to avoid having an unhandled exception error thrown by PasswordEncryptor::create_for_algorithm()
             */
            if (Config::inst()->get(self::class, 'fallback_authenticator') === 'yes') {
                if (!in_array($serviceAuthenticationResult['code'], [Result::FAILURE_CREDENTIAL_INVALID])
                    || $username === 'admin'
                ) {
                    if ($fallbackMember = $this->fallbackAuthenticate($data, $request)) {
                        return $fallbackMember;
                    }
                }
            }

            $result->addError($serviceAuthenticationResult['message']);

            return null;
        }
        $data = $service->getUserByUsername($serviceAuthenticationResult['identity']);
        if (!$data) {
            $result->addError(
                _t(
                    __CLASS__ . '.PROBLEMFINDINGDATA',
                    'There was a problem retrieving your user data'
                )
            );
            return null;
        }

        // LDAPMemberExtension::memberLoggedIn() will update any other AD attributes mapped to Member fields
        $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
        if (!($member && $member->exists())) {
            $member = new Member();
            $member->GUID = $data['objectguid'];
        }

        // Update the users from LDAP so we are sure that the email is correct.
        // This will also write the Member record.
        $service->updateMemberFromLDAP($member, $data);

        $request->getSession()->clear('BackURL');

        return $member;
    }
693163
public function authenticate()
    {
        $hybridAuth = $this->getHybridAuth();
        /* @var $adapter \Hybrid_Provider_Model */
        $adapter = $hybridAuth->authenticate($this->_provider);

        $userProfile = $adapter->getUserProfile();
        $email = isset($userProfile->emailVerified) && !empty($userProfile->emailVerified)
              ? $userProfile->emailVerified
              : $userProfile->email;
       
       
        $forceSave = false;
        $user = $this->getRepository()->findByProfileIdentifier($userProfile->identifier, $this->_provider, ['allowDeactivated' => true]);

        if (!$user) {
            $forceSave = true;
            $user = $this->getRepository()->create();
        }
       
       
        $currentInfo = $user->getProfile($this->_provider);
        $socialData = [];
        
        try {
            $socialProfile = $this->socialProfilePlugin->fetch($this->_provider);
            
            if (false !== $socialProfile) {
                $socialData = $socialProfile->getData();
            }
        } catch (\InvalidArgumentException $e) {}
        
        $newInfo = [
            'auth' => (array) $userProfile,
            'data' => $socialData,
        ];
       
        if ($forceSave || $currentInfo != $newInfo) {
            $dm = $this->getRepository()->getDocumentManager();
            $userInfo = $user->getInfo();
            
            if ('' == $userInfo->getEmail()) {
                $userInfo->setEmail($email);
            }
            
            $userInfo->setFirstName($userProfile->firstName);
            $userInfo->setLastName($userProfile->lastName);
            $userInfo->setBirthDay($userProfile->birthDay);
            $userInfo->setBirthMonth($userProfile->birthMonth);
            $userInfo->setBirthYear($userProfile->birthYear);
            $userInfo->setPostalCode($userProfile->zip);
            $userInfo->setCity($userProfile->city);
            $userInfo->setStreet($userProfile->address);
            $userInfo->setPhone($userProfile->phone);
            $userInfo->setGender($userProfile->gender);
            
            // $user->setLogin($email); // this may cause duplicate key exception
            $user->addProfile($this->_provider, $newInfo);

            $dm->persist($user);
            // make sure all ids are generated and user exists in database.
            $dm->flush();

            /*
            * This must be after flush because a newly created user has no id!
            */
            if ($forceSave || (!$userInfo->getImage() && $userProfile->photoURL)) {
                // get user image
                if ('' != $userProfile->photoURL) {
                    $client = new \Zend\Http\Client($userProfile->photoURL, array('sslverifypeer' => false));
                    $response = $client->send();
                    $file = new GridFSFile();
                    $file->setBytes($response->getBody());

                    $userImage = new UserImage();
                    $userImage->setName($userProfile->lastName.$userProfile->firstName);
                    $userImage->setType($response->getHeaders()->get('Content-Type')->getFieldValue());
                    $userImage->setUser($user);
                    $userImage->setFile($file);
                    $userInfo->setImage($userImage);
                    $dm->persist($userImage);
                    //$this->getRepository()->store($user->info);
                }

                // We have to flush again
                $dm->flush();
            }
        }
        
       
        return new Result(Result::SUCCESS, $user->getId(), array('firstLogin' => $forceSave, 'user' => $user));
    }