PHP code example of sirix / mezzio-rbac

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

    

sirix / mezzio-rbac example snippets


use Sirix\Mezzio\Rbac\Actor\Actor;

$actor = new Actor(['editor', 'moderator']);

use Sirix\Mezzio\Rbac\Contract\GuardInterface;

$guard->allows('posts.update');
$guard->denies('admin.panel');
$guard->authorize('posts.delete');

use Psr\Http\Message\ServerRequestInterface;
use Sirix\Mezzio\Rbac\Contract\RequestGuardInterface;

final readonly class PostHandler
{
    public function __construct(private RequestGuardInterface $guard) {}

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $this->guard->authorize($request, 'posts.update', [
            'postId' => $request->getAttribute('id'),
        ]);

        // ...
    }
}

use Sirix\Mezzio\Rbac\Contract\PermissionsInterface;
use Sirix\Mezzio\Rbac\Rule\ForbidRule;

$permissions->addRole('editor');
$permissions->associate('editor', 'posts.*');
$permissions->associate('editor', 'posts.delete', ForbidRule::class);

use Sirix\Mezzio\Rbac\Contract\ActorInterface;
use Sirix\Mezzio\Rbac\Contract\RuleInterface;

final class OwnPostRule implements RuleInterface
{
    public function allows(ActorInterface $actor, string $permission, array $context): bool
    {
        return ($context['ownerId'] ?? null) === ($context['userId'] ?? null);
    }
}

$permissions->associate('user', 'posts.update', OwnPostRule::class);

'rbac' => [
    'request_actor_attribute' => 'sirix.authentication.actor',
]

[
    'postId' => 'id', // context['postId'] = $request->getAttribute('id')
]

use Sirix\Mezzio\Rbac\Middleware\AuthorizeMiddleware;
use Sirix\Mezzio\Rbac\RbacAttribute;

$app->post('/posts/:id', [
    AuthorizeMiddleware::class,
    PostHandler::class,
], 'post.update')->setOptions([
    RbacAttribute::Permission->value => 'posts.update',
    RbacAttribute::Context->value => ['postId' => 'id'],
]);

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Sirix\Mezzio\Rbac\Attribute\Can;
use Sirix\Mezzio\Routing\Attributes\Attribute\Post;

#[Post('/posts/:id', name: 'post.update')]
#[Can('posts.update', ['postId' => 'id'])]
final class PostHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        // Authorization has already run before the handler.
    }
}

use Sirix\Mezzio\Authentication\Attribute\Authenticated;
use Sirix\Mezzio\Rbac\Attribute\Can;
use Sirix\Mezzio\Routing\Attributes\Attribute\Get;

#[Get('/admin', name: 'admin')]
#[Authenticated]
#[Can('admin.access')]
final class AdminHandler implements RequestHandlerInterface
{
    // ...
}

use Sirix\Mezzio\Rbac\Contract\GuardInterface;

final readonly class PostService
{
    public function __construct(private GuardInterface $guard) {}

    public function deletePost(string $postId): void
    {
        $this->guard->authorize('posts.delete', [
            'postId' => $postId,
        ]);
    }
}

use Sirix\Mezzio\Rbac\Actor\Actor;
use Sirix\Mezzio\Rbac\Contract\ActorInterface;
use Sirix\Mezzio\Rbac\Contract\ActorProviderInterface;

final readonly class MyActorProvider implements ActorProviderInterface
{
    public function __construct(private MyAuthService $auth) {}

    public function getActor(): ActorInterface
    {
        $user = $this->auth->getIdentity();

        return new Actor($user?->getRoles() ?? ['guest']);
    }
}

use Psr\Http\Message\ServerRequestInterface;
use Sirix\Mezzio\Rbac\Actor\Actor;
use Sirix\Mezzio\Rbac\Contract\ActorInterface;
use Sirix\Mezzio\Rbac\Contract\RequestActorProviderInterface;

final readonly class MyRequestActorProvider implements RequestActorProviderInterface
{
    public function getActor(ServerRequestInterface $request): ActorInterface
    {
        $user = $request->getAttribute('user');

        return new Actor($user?->roles() ?? ['guest']);
    }
}

'dependencies' => [
    'factories' => [
        RequestActorProviderInterface::class => MyRequestActorProviderFactory::class,
    ],
],

use Sirix\Mezzio\Rbac\Contract\PermissionAssociationInterface;
use Sirix\Mezzio\Rbac\Contract\PermissionStoreInterface;

final readonly class DatabasePermissionStore implements PermissionStoreInterface
{
    public function associationsForRole(string $role): array
    {
        // Fetch from DB and map to PermissionAssociation objects.
    }

    // ... implement other methods
}