PHP code example of web-complete / rbac

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

    

web-complete / rbac example snippets


$resource = new FileResource($path . '/rbac.data');
$rbac = new Rbac($resource);

$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

$adminRole = $rbac->createRole('admin');
$moderatorRole = $rbac->createRole('moderator');
$authorRole = $rbac->createRole('author');
$adminRole->addChild($moderatorRole); // admin has all moderator's rights

...
$moderatorRole->addPermission($p2);
...

$rbac->save();

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') 


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;
    }
}

$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);

if($rbac->checkAccess('post:author:delete', ['userId' => $userId, 'post' => $post]) {
    ... // The user is author of the post and can delete it
}