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/ */
// 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
}
use Yiisoft\User\Method\WebAuth;
$authenticationMethod = new WebAuth();
// Returns a new instance with the specified authentication URL.
$authenticationMethod = $authenticationMethod->withAuthUrl('/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;
}