PHP code example of yiisoft / user

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

    

yiisoft / user example snippets


/** 
 * @var \Psr\EventDispatcher\EventDispatcherInterface $eventDispatcher
 * @var \Yiisoft\Auth\IdentityRepositoryInterface $identityRepository
 */

$currentUser = new \Yiisoft\User\CurrentUser($identityRepository, $eventDispatcher);

$currentUser->getIdentity(); // \Yiisoft\User\Guest\GuestIdentity instance
$currentUser->getId(); // null
$currentUser->isGuest(); // bool

/** 
 * @var \Psr\EventDispatcher\EventDispatcherInterface $eventDispatcher
 * @var \Yiisoft\Auth\IdentityRepositoryInterface $identityRepository
 * @var \Yiisoft\User\Guest\GuestIdentityFactoryInterface $guestIdentityFactory
 */

$currentUser = new \Yiisoft\User\CurrentUser($identityRepository, $eventDispatcher, $guestIdentityFactory);

/** 
 * @var \Yiisoft\Auth\IdentityInterface $identity
 */

$currentUser->getIdentity(); // Original identity instance
$currentUser->overrideIdentity($identity);
$currentUser->getIdentity(); // Override identity instance
$currentUser->clearIdentityOverride();
$currentUser->getIdentity(); // Original identity instance

/**
 * @var \Yiisoft\Auth\IdentityInterface $identity
 */

$currentUser->getIdentity(); // GuestIdentityInterface instance

if ($currentUser->login($identity)) {
    $currentUser->getIdentity(); // $identity
    // Some actions
}

if ($currentUser->logout()) {
    $currentUser->getIdentity(); // GuestIdentityInterface instance
    // Some actions
}

/** 
 * @var \Yiisoft\Access\AccessCheckerInterface $accessChecker
 */
 
$currentUser = $currentUser->withAccessChecker($accessChecker);

// The name of the permission (e.g. "edit post") that needs access check.
$permissionName = 'edit-post'; // Required.

// Name-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user.
$params = ['postId' => 42]; // Optional. Default is empty array.

if ($currentUser->can($permissionName, $params)) {
    // Some actions
}

/** 
 * @var \Yiisoft\Session\SessionInterface $session
 */
 
$currentUser = $currentUser->withSession($session);

$currentUser = $currentUser->withAuthTimeout(3600);

$currentUser = $currentUser->withAbsoluteAuthTimeout(3600);

use Yiisoft\User\Method\WebAuth;

$authenticationMethod = new WebAuth();

// Returns a new instance with the specified authentication URL.
$authenticationMethod = $authenticationMethod->withAuthUrl('/auth');

// config/web/di/auth.php
return [
    WebAuth::class => [
        'withAuthUrl()' => ['/auth'],
    ],
];

// config/web/params.php
return [
    'yiisoft/user' => [
        'authUrl' => '/auth',
    ],
];

use Yiisoft\Auth\Middleware\Authentication;
use Yiisoft\User\Method\ApiAuth;

$authenticationMethod = new ApiAuth();

$middleware = new Authentication(
    $authenticationMethod,
    $responseFactory // PSR-17 ResponseFactoryInterface
);

// config/web/di/auth.php
use Yiisoft\Auth\AuthenticationMethodInterface;
use Yiisoft\User\Method\ApiAuth;

return [
    AuthenticationMethodInterface::class => ApiAuth::class,
];

use App\CookieLoginIdentity;
use Yiisoft\Auth\IdentityRepositoryInterface;

final class CookieLoginIdentityRepository implements IdentityRepositoryInterface
{
    private Storage $storage;

    public function __construct(Storage $storage)
    {
        $this->storage = $storage;
    }

    public function findIdentity(string $id): ?Identity
    {   
        return new CookieLoginIdentity($this->storage->findOne($id));
    }
}

public function login(
    \Psr\Http\Message\ServerRequestInterface $request,
    \Psr\Http\Message\ResponseFactoryInterface $responseFactory,
    \Yiisoft\User\Login\Cookie\CookieLogin $cookieLogin,
    \Yiisoft\User\CurrentUser $currentUser
): \Psr\Http\Message\ResponseInterface {
    $response = $responseFactory->createResponse();
    $body = $request->getParsedBody();
    
    // Get user identity based on body content.
    
    /** @var \Yiisoft\User\Login\Cookie\CookieLoginIdentityInterface $identity */
    
    if ($currentUser->login($identity) && ($body['rememberMe'] ?? false)) {
        $response = $cookieLogin->addCookie($identity, $response);
    }
    
    return $response;
}

return [
    'yiisoft/user' => [
        'authUrl' => '/login',
        'cookieLogin' => [
            'forceAddCookie' => true,
            'duration' => 'P5D', // 5 days
        ],
    ],
];

public function logout(
    \Psr\Http\Message\ResponseFactoryInterface $responseFactory,
    \Yiisoft\User\Login\Cookie\CookieLogin $cookieLogin,
    \Yiisoft\User\CurrentUser $currentUser
): \Psr\Http\Message\ResponseInterface {
    $response = $responseFactory
        ->createResponse(302)
        ->withHeader('Location', '/');
    
    // Regenerate cookie login key to `Yiisoft\User\Login\Cookie\CookieLoginIdentityInterface` instance.
    
    if ($currentUser->logout()) {
        $response = $cookieLogin->expireCookie($response);
    }
    
    return $response;
}