Role Based Access Control

2.0.1 2018-02-12 11:51 UTC

This package is not auto-updated.

Last update: 2024-12-20 19:54:06 UTC


README

Build Status Coverage Status Scrutinizer Code Quality Latest Stable Version License

Tiny flexible RBAC implementation with no dependencies.

Role-based-access-control (RBAC) is a policy neutral access control mechanism defined around roles and privileges. The components of RBAC such as role-permissions, user-role and role-role relationships make it simple to perform user assignments.

Installation

composer require web-complete/rbac

Usage

  • Initiate with resource object. Resource object can be a FileResource or a RuntimeResource. You can also create any necessary resource (Mysql, Redis, Bongo etc) by extending AbstractResource or implementing ResourceInterface.
$resource = new FileResource($path . '/rbac.data');
$rbac = new Rbac($resource);
  • Create permissions hierarchy
$p1 = $rbac->createPermission('post:create', 'Can create posts');
$p2 = $rbac->createPermission('post:moderate', 'Can moderate posts');
$p3 = $rbac->createPermission('post:update', 'Can update posts');
$p4 = $rbac->createPermission('post:delete', 'Can delete posts');
$p2->addChild($p3); // moderator can also update
$p2->addChild($p4); // and delete posts
  • Create role hierarchy
$adminRole = $rbac->createRole('admin');
$moderatorRole = $rbac->createRole('moderator');
$authorRole = $rbac->createRole('author');
$adminRole->addChild($moderatorRole); // admin has all moderator's rights
  • Bind roles and permissions
...
$moderatorRole->addPermission($p2);
...
  • Persist state
$rbac->save();
  • Checking access rights
if($rbac->getRole($user->role)->checkAccess('post:moderate') {
    ... // User can moderate posts
}
// or add to your user's class something like:
$user->can('post:moderate') 

Rules

Sometimes it's not enough to simple check the permission. For example, an author can edit and delete only his own posts. For that case you can create a rule by implementing RuleInterface with one method «execute»:

class AuthorRule implements WebComplete\rbac\entity\RuleInterface
{

    /**
     * @param array|null $params
     *
     * @return bool
     */
    public function execute($params): bool
    {
        // @var Post $post
        if($post = $params['post'] ?? null) {
            return $post->authorId === ($params['userId'] ?? null);
        }
        return false;
    }
}
  • Configure RBAC
$p5 = $rbac->createPermission('post:author:update', 'Author can update his posts');
$p6 = $rbac->createPermission('post:author:delete', 'Author can delete his posts');
$p5->setRuleClass(AuthorRule::class);
$p6->setRuleClass(AuthorRule::class);
$authorRole->addPermission($p5);
$authorRole->addPermission($p6);
  • And then check rights with parameters
if($rbac->checkAccess('post:author:delete', ['userId' => $userId, 'post' => $post]) {
    ... // The user is author of the post and can delete it
}