PHP code example of starbug / auth

1. Go to this page and download the library: Download starbug/auth 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/ */

    

starbug / auth example snippets


// The provided repository implementations Interface");

// Now the good stuff.
$idRepository = new Starbug\Auth\Repository\IdentityRepository($db);
$cookieSessionExchange = new Starbug\Auth\Http\CookieSessionExchange("secretkey");
$sessionRepository = new Starbug\Auth\Repository\SessionRepository($db, $idRepository);
$sessionStorage = new Starbug\Auth\SessionStorage($sessionRepository, $cookieSessionExchange);
// et voila!
$sessionHandler = new Starbug\Auth\SessionHandler($sessionStorage, $idRepository);

// Start the session. Do this to load any existing session.
$sessionHandler->startSession();

// Hash a password for user registration.
$hashedPassword = $sessionHandler->hashPassword("mypassword");

// Authenticate a user and create a session to login.
if ($id = $sessionHandler->authenticate($userIdOrCriteria, "mypassword")) {
  $session = $sessionHandler->createSession($id);
}

// Check if user is logged in
if ($sessionHandler->loggedIn()) {
  echo "Hello, your user ID is ".$sessionHandler->getUserId();
}

// Custom attributes
if ($sessionHandler->loggedIn()) {
  // Store custom data attributes
  $id = $sessionHandler->getSession()->getIdentity();
  $id->setData(["first_name" => "Ali"]);
  $id->addData(["last_name" => "Gangji"]);

  // Retrieve all data as an array
  $data = $id->getData();
  // Retrieve specific properties
  $firstName = $id->getData("first_name");

  //Retrieval can be done from session handler.
  $data = $sessionHandler->getData();
  $firstName = $sessionHandler->getData("first_name");
}

// Identity loaded directly from repository
// can be used to create sessions without authentication.
$id = $idRepository->getIdentity($userIdOrCriteria);
// Passing false prevents session from being persisted.
$sessionHandler->createSession($id, false);

$csrfExchanger = new Starbug\Auth\Http\CookieCsrfExchange();
$csrfHandler = new Starbug\Auth\Http\CsrfHandler($csrfExchanger, "secretkey");
$sessionHandler->addHook($csrfHandler);

// Check a request token. Do this after the session has started.
$csrfHandler->checkRequestToken($_POST["csrfToken"]);

// Obtain the request to 

$sessionMiddleware = new Starbug\Auth\Http\AuthenticationMiddleware($sessionHandler);

$csrfMiddleware = new Starbug\Auth\Http\CsrfMiddleware($csrfHandler);