PHP code example of erdiko / authenticate

1. Go to this page and download the library: Download erdiko/authenticate library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

erdiko / authenticate example snippets


Class SessionStorage implements StorageInterface {

	public function persist(UserStorageInterface $user)
	{
		$this->startSession();
		$_SESSION["current_user"] = $user->marshall();
	}

	public function attemptLoad(UserStorageInterface $userModel)
	{
		$user = null;

		$sapi = php_sapi_name();
		if(!$this->contains('cli', $sapi)){
			$this->startSession();
		}

		if(array_key_exists("current_user", $_SESSION)){
			$_user = $_SESSION["current_user"];
			if(!empty($_user)){
				$user = $userModel::unmarshall($_user);
			}
		}
		return $user;
	}

	public function contains($needle, $haystack)
	{
		return strpos($haystack, $needle) !== false;
	}

	public function destroy()
	{
		$this->startSession();
		if(array_key_exists("current_user", $_SESSION)){
			unset($_SESSION["current_user"]);
		}
		@session_destroy();
	}

	private function startSession()
	{
		if(!file_exists(ERDIKO_VAR . "/session")) {
			mkdir(ERDIKO_VAR . "/session");
		}
		ini_set('session.save_path',ERDIKO_VAR . "/session");
		if(session_id() == '') {
			@session_start();
		} else {
			if (session_status() === PHP_SESSION_NONE) {
				@session_start();
			}
		}
	}
}

public function login($credentials = array(), $type = 'jwt_auth')
{
    $storage = $this->container["STORAGES"][$this->selectedStorage];
    $result = false;

    // checks if it's already logged in
    $user = $storage->attemptLoad($this->erdikoUser);
    if($user instanceof UserStorageInterface) {
        $this->logout();
    }

    $auth = $this->container["AUTHENTICATIONS"][$type];
    $result = $auth->login($credentials);
    if(isset($result->user))
        $user = $result->user;
    else
        throw new \Exception("User failed to load");

    if(!empty($user) && (false !== $user)) {
        $this->persistUser( $user );
        $response = true;
    }

    return $result;
}

public function persistUser(UserStorageInterface $user)
{
    $this->generateTokenStorage($user);
}

public function generateTokenStorage(UserStorageInterface $user)
{
    $entityUser = $user->getEntity();

    $userToken = new UsernamePasswordToken($entityUser->getEmail(),$entityUser->getPassword(),'main',$user->getRoles());
    $_SESSION['tokenstorage'] = $userToken;
}