thenotsoft / rbac

Role based access control

Home Page:https://www.yiiframework.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Yii Role-Based Access Control Library


This library provides RBAC (Role-Based Access Control) library. It is used in Yii Framework but is supposed to be usable separately.

Latest Stable Version Total Downloads Code Coverage Build Status

Install:

composer require yiisoft/rbac

Basic usage:

create instance

$manager = new Manager($storage, new ClassNameRuleFactory());

In the directory config will contain permissions and rules.

create permissions

$manager->addPermission(new Permission('createPost'));
$manager->addPermission(new Permission('readPost'));
$manager->addPermission(new Permission('deletePost'));

After executing this code, this configuration will be saved in ../config/items.php

Create roles

$manager->addRule(new Role('author'));
$manager->addRule(new Role('reader'));

Attach permissions to roles

$manager->addChild(
    $manager->getRole('reader'),
    $manager->getPermission('readPost')
);

$manager->addChild(
    $manager->getRole('author'),
    $manager->getPermission('createPost')
);

$manager->addChild(
    $manager->getRole('author'),
    $manager->getRole('reader')
);

Assign role to user

$manager->assign($manager->getRole('author'), 100);

After executing this code, this configuration will be saved in ../config/assignments.php

Check permissions

if ($manager->userHasPermission(100, 'createPost')) {
    echo 'author has permission createPost';
}

Usage rules

$manager->addRule(new ActionRule());
$manager->addPermission(
    (new Permission('viewList'))->withRuleName('action_rule')
);

The role will also support the rules.

Rule example

class ActionRule extends Rule
{
    public function __construct()
    {
        parent::__construct('action_rule');
    }

    public function execute(string $userId, Item $item, array $parameters = []): bool
    {
        return isset($parameters['action']) && $parameters['action'] === 'home';
    }
}

Check permissions with rule

if (!$manager->userHasPermission(103, 'viewList', ['action' => 'home'])) {
    echo 'reader not has permission index';
}

Storage:

Storage Description
PhpStorage PHP file storage

About

Role based access control

https://www.yiiframework.com/

License:BSD 3-Clause "New" or "Revised" License


Languages

Language:PHP 100.0%