Login Authenticated User

- Sign user in environment and server
exp. store in session, store data in cache
sign user token in header, etc.

- logout current user if has

@throws \Exception no identity defined
@return $this
550355
function signIn()
    {
        if ( (null === $identity = $this->identity) || !$identity->isFulfilled() )
            throw new \Exception('Identity not exists or not fullfilled');

        $identity = serialize($identity);
        $this->_storage()->set(self::STORAGE_IDENTITY_KEY , $identity);
        return $this;
    }
584404
public function login()
    {

        // invoke the parent method
        if (parent::login()) {
            // if login has been successfully, setup our view of the user
            $name = new String($this->sharedState->get(SharedStateKeys::LOGIN_NAME));
            // query whether or not we alredy hava a principal
            if ($name instanceof PrincipalInterface) {
                $this->identity = name;
            } else {
                $name = $name->__toString();
                try {
                    $this->identity = $this->createIdentity($name);
                } catch (\Exception $e) {
                    throw new LoginException(sprintf('Failed to create principal: %s', $e->getMessage()));
                }
            }

            // return immediately
            return true;
        }

        // else, reset the login flag
        $this->loginOk = false;

        // array containing the username and password from the user's input
        list ($name, $password) = $this->getUsernameAndPassword();

        if ($name == null && $password == null) {
            $this->identity = $this->unauthenticatedIdentity;
        }

        if ($this->identity == null) {
            try {
                $this->identity = $this->createIdentity($name);
            } catch (\Exception $e) {
                throw new LoginException(sprintf('Failed to create principal: %s', $e->getMessage()));
            }

            // hash the user entered password if password hashing is in use
            if ($this->hashAlgorithm != null) {
                $password = $this->createPasswordHash($name, $password);
                // validate the password supplied by the subclass
                $expectedPassword = $this->getUsersPassword();
            }

            // validate the password
            if ($this->validatePassword($password, $expectedPassword) === false) {
                throw new FailedLoginException('Password Incorrect/Password Required');
            }
        }

        // query whether or not password stacking has been activated
        if ($this->getUseFirstPass()) {
            // add the username and password to the shared state map
            $this->sharedState->add(SharedStateKeys::LOGIN_NAME, $name);
            $this->sharedState->add(SharedStateKeys::LOGIN_PASSWORD, $this->credential);
        }

        $this->loginOk = true;
        return true;
    }
803343
public function authenticate()
    {
        $request = new Request($this->handler);
        $this->token = $request->execute(
            RequestMethods::HTTP_POST,
            $this->makeUrl(RequestMethods::DOMUSERP_API_PEDIDOVENDA . '/auth'),
            [
                'json' => [
                    'login'    => $this->username,
                    'password' => $this->password
                ]
            ]
        )->token;

        return $this;
    }
973967
public function logout()
    {
        if (is_null($userId = $this->getUserId())) {
            return null;
        }

        return $this->leave(static::USER_PREFIX . $userId);
    }
943606
public static function _init()
	{
		\Config::load('simpleauth', true);

		// setup the remember-me session object if needed
		if (\Config::get('simpleauth.remember_me.enabled', false))
		{
			static::$remember_me = \Session::forge(array(
				'driver' => 'cookie',
				'cookie' => array(
					'cookie_name' => \Config::get('simpleauth.remember_me.cookie_name', 'rmcookie'),
				),
				'encrypt_cookie' => true,
				'expire_on_close' => false,
				'expiration_time' => \Config::get('simpleauth.remember_me.expiration', 86400 * 31),
			));
		}
	}
962319
public function login() {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Your username or password is incorrect.'));
        }

        // Set signin layout from Builder.Layout
        $this->viewBuilder()->layout('signin');
        // Use the layout without Template 
        $this->render(false);
    }
249889
public login logout() throws Exception
	{
		if(sessionid == null || sessionid.length() <= 0)
			throw new Exception("User not logged-in");
		
		login logout_obj = new login();
		logout_obj.set_sessionid(sessionid);
		
		login result = login.delete(this, logout_obj);
		sessionid = null;
		user_name = null;
		password = null;
		return result;
	}
1093408
public function logoutAction()
    {
        $auth = $this->auth;
        $this->logger->info('User ' . ($auth->getUser()->getLogin()==''?$auth->getUser()->getInfo()->getDisplayName():$auth->getUser()->getLogin()) . ' logged out');
        $auth->clearIdentity();
        unset($_SESSION['HA::STORE']);

        $this->notification()->success(/*@translate*/ 'You are now logged out');
        return $this->redirect()->toRoute(
            'lang',
            array('lang' => $this->params('lang'))
        );
    }
980640
protected function GetCurrentUser()
	{
		if (!$this->_cu)
		{
			require_once("verysimple/Authentication/Authenticator.php");
			
			$this->Phreezer->Observe("Loading CurrentUser from Session");
			$this->_cu = Authenticator::GetCurrentUser($this->GUID);

			if ($this->_cu )
			{
				if (get_class($this->_cu) == "__PHP_Incomplete_Class")
				{
					// this happens if the class used for authentication was not included before the session was started
					$tmp = print_r($this->_cu,1);
					$parts1 = explode("__PHP_Incomplete_Class_Name] => ",$tmp);
					$parts2 = explode("[",$parts1[1]);
					$name = trim($parts2[0]);

					Authenticator::ClearAuthentication($this->GUID);
					throw new Exception("The class definition used for authentication '$name' must be defined (included) before the session is started, for example in _app_config.php.");
				}
				else
				{
					// refresh the current user if the object supports it
					if (method_exists($this->_cu, 'Refresh')) $this->_cu->Refresh($this->Phreezer);
				}
			}
		}
		else
		{
			$this->Phreezer->Observe("Using previously loaded CurrentUser");
		}

		return $this->_cu;
	}
1281541
private function authenticateWithPassword()
    {
        if ($this->credentials->havePassword()) {
            $authCommand = new Auth();
            $authCommand->setArguments([$this->credentials->getPassword()]);
            $authResponse = $this->connection->execute($authCommand);
            $response = $authCommand->parse($authResponse);
            if ($response !== self::AUTH_SUCCESS_MESSAGE) {
                throw new AuthenticationException();
            }
        }
    }
95896
protected static function authenticate() :void {
		// if we did not authenticate before
		if(!self::$_account) {
			// search for an enabled account with that session key and a non expired session
			$account = \Models\Accounts::getFirstEnabledWithNonExpiredSession(
				// the session key
				Cook::get(Config::get('security', 'cookie'))
			);
			// if the cookie session key doesn't match any existing account session, we deny access
			$account ?: 
				self::refuse(
					'Your session is no longer valid', 
					403, true);
			// if the stored key and dynamically generated mismatch, we deny access
			$account->hasMatchingDynamicKey() ?: 
				self::refuse(
					'Your signature has changed since your last visit, please log-in again', 
					403, true);
			// if account has expired, we deny access
			!$account->hasItsValidityExpired() ?:
				self::refuse(
					"Your account has expired, it was valid until {$account->get('account_expiration_date')}", 
					403, true);
			// update our credentials
			self::$_account = $account;
			// set access as granted
			self::$_granted = true;
		}	
	}
1356712
public function authenticate(array $credentials): Identity
	{
		list($username, $password) = $credentials;

		$user = $this->orm->users->getByUsername($username);

		if (!$user) {
			throw new AuthenticationException('The username is incorrect.', self::IDENTITY_NOT_FOUND);
		} elseif (!Passwords::verify($password, $user->password)) {
			throw new AuthenticationException('The password is incorrect.', self::INVALID_CREDENTIAL);
		} elseif (!$user->active) {
			throw new AuthenticationException('Account is deactivated.', self::NOT_APPROVED);
		} elseif (Passwords::needsRehash($user->password)) {
			$user->setPassword($password);
			$this->orm->persistAndFlush($user);
		}

		return new Identity($user->id);
	}
190074
public function logout()
    {
        // Token from Clef.io
        if (isset($_POST['logout_token'])) {
            // Verif token
            $clef = \Aperdia\Clef::logout($_POST['logout_token']);

            if (!$clef) {
                // Verif in Authentication table
                $auth = Authentication::whereprovider("clef")->whereprovider_uid($clef)->first();

                if (!empty($auth)) {
                    $user = User::find($auth->user_id);

                    if (!empty($user)) {
                        $user->logout = 1;
                        $user->save();
                    }
                }
            }
        }
    }
529111
public static function is_login(){
        $user = self::sessionGet('user');
        if (empty($user)) {
            return false;
        } else {
            return  self::sessionGet('user_sign') == self::data_auth_sign($user) ? $user : false;
        }
    }
510155
public function currentUser()
    {
        try {
            if (!array_key_exists('tokenstorage',$_SESSION)) {
                throw new \Exception('Token storage not found.');
            }
            $storage = $_SESSION['tokenstorage'];
            $username = $storage->getToken()->getUsername();
            // echo print_r($storage->getToken()->getId(), true);
            $users = $this->erdikoUser->getByParams(['email' => $username]);
            if (!count($users)) {
                throw new \Exception('User not found.');
            }
            $user = $users[0];
        } catch (\Exception $e) {
            $user = $this->erdikoUser->getGeneral();
        }
        return $user;
    }
146626
protected function authenticate()
    {
        $authClass = $this->config()->authenticator;
        $member = $authClass::authenticate();
        Security::setCurrentUser($member);
        return $member;
    }
1214981
public function logout()
		{

			// Am I authenticated?
			if ($this->isAuthenticated() == false) {

				// Cannot logout!
				return false;

			}

			// Destroy my session
			$this->_authenticated = false;
			unset($_SESSION[self::$_sessionPrefix . $this->name]);
			$this->_user = null;
			return true;

		}