Yii 1.1: rbac-manager

Role-Based Access Control Manager with recursion protection, BizRule Manager, Code generation and more
13 followers
  • Manage RBAC System in intuitive Tree-View
  • Ceep cool with rekursion protection in RBAC Tree
  • Generate PHP Code
  • Full relational move, create, edit, delete support of RBAC Tree items.
  • Assign and eject multiple Roles to and from multiple Users
  • Create predefined buisness Rules for User Assignments
  • Assign Roles in Secure Mode
  • By Controller protected and not changeable Roles and Assignments
  • Use easy checkAccess() methods in your Controller
  • Create easy bizRule Code in your RBAC Roles and Assignments

Live Preview

There is currently a Projekt running where you can look and play around with: http://openrentstock-live.byto.de/rbac/rbac Login as admin:admin. It would be nice when you track bugs on sourceforge.

Download

Screenshots

Everybody loves Screenshots. Here are some Screenshots
and learn more about RBAC in Yii's Docu: Role-Based Access Control.

Requirements

RBAC Manager is preconfigured to run best with Yii-user
but it is even possible to use your own User Management.
Scroll down to Optional Step 3) and learn how to configure RBAC Manager with other User Tables.

Install

For first trys with RBAC Manager and very low Yii expirience it is recommended to have a fresh Yii App created with Yii-user Module running.
But with some Yii expirience it should be no problem to get RBAC Manager running.

Install Step 1)

Copy rabc folder to protected/modules/rbac.

Install Step 2)

Query the DB Schema rbac/data/schema.sql to your Database
an make sure you have a User with id 1 elso you can't
access the RBAC Manager.
If not, edit the second Field in the SQL Schema to your needs:
...
INSERT INTO AuthAssignment (itemname, userid, bizrule, data) VALUES
('SuperAdmin', '1', '', '');
...

Install Step 3)

Copy rbac/data/rbac.css to your Webdirectory where the other Yii-css Files are stored
eg. htdocs/css/rbac.css.
Open protected/views/layouts/main.php and add the Link in the HTML Head for the css File:

...
<link ..."/css/main.css" >;
<link ..."/css/form.css" >;
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/rbac.css" />;
...

Install Step 4)

Open File protected/config/main.php and add the Module to the Yii Config.

$config=array(
...
'modules'=>array(
...
// rbac configured to run with module Yii-User
'rbac'=>array(
    // Table where Users are stored. RBAC Manager use it as read-only
    'tableUser'=>'User', 
    // The PRIMARY column of the User Table
    'columnUserid'=>'id',
    // only for display name and could be same as id
    'columnUsername'=>'username',
    // only for display email for better identify Users
    'columnEmail'=>'email' // email (only for display)
    ),
...
),
...

Make sure you have a db connection and authManager running
and look at last both entrys
'defaultRoles' and 'showErrors' in 'authManager'.

'components'=>array(
    ...
    'db'=>array(
        'connectionString' => 'mysql:host=localhost;dbname=yourDatabase',
        'emulatePrepare' => true,
        'username' => 'yourDatabase',
        'password' => 'password',
        'charset' => 'utf8',
    ),
    ...
    'authManager'=>array(
            'class'=>'CDbAuthManager', // Database driven Yii-Auth Manager
            'connectionID'=>'db', // db connection as above
        'defaultRoles'=>array('registered'), // default Role for logged in users
        'showErrors'=>true, // show eval()-errors in buisnessRules
    ),
    ...
),

Install Step 5)

Open Base Controller of your Application and/or Module eg. protected/components/controller.php
and add attach the AccessVerifier Component.

public function behaviors()
{
    return array(
        'RBACAccessComponent'=>array(
            'class'=>'application.modules.rbac.components.RBACAccessVerifier',
            // optional default settings
            'checkDefaultIndex'=>'id', // used with buisness Rules if no Index given
            'allowCaching'=>false,  // cache RBAC Tree -- do not enable while development ;)
            'accessDeniedUrl'=>'/user/login',// used if User is logged in
            'loginUrl'=>'/user/login'// used if User is NOT logged in
        ),
    );
}

Optional Steps

Optional Step 1)

RBAC Manager supports protected Users and RBAC Items.
You find them in rbac/components/RBACBaseController.php.

class RBACBaseController extends CController
{
...
    /*
     * not changeable (protected) rbac items
     */
    public $protectedItems=array(
        'SuperAdmin', 
            'RbacAdmin',
                'RbacAssignmentEditor',
                    'RbacAssignmentViewer',
                'RbacEditor',
                    'RbacViewer');
    /*
     * protected users with not changeable assignments
     */
    public $protectedUsers=array(1); // from User Table collumn module->columnUserid
...

Optional Step 2)

If you want to temporaly disable any checkAccess effects
open rbac/components/RBACAccessVerifier and uncomment this Line:

public function checkAccess($role, $autoRedirect=false)
    {
        // return true; // uncomment this Line to disable any checkAccess effects
        if(is_array($role)){
        ...

Optional Step 3)

As shown in the Install Doc Step 4 have a look at the RBAC configuration.
There you will find Table- and Collumndefinitions.
Change them to fit with the User Table of your Usermanagment. Next have a look in the AuthAssignment Table of the RBAC Manager. There should be an Entry Role=>'SuperUser' with the PRIMARY id of one of your Users.

$config=array(
...
'modules'=>array(
...
// rbac configured to run with module Yii-User
'rbac'=>array(
    'tableUser'=>'User', // Table where Users are stored. RBAC Manager use it as read-only
    'columnUserid'=>'id', // The PRIMARY column of the User Table
    'columnUsername'=>'username', // used to display name and could be same as columnUserid
    'columnEmail'=>'email' // email (only for display)
    ),
...
),
...

Usage

Add first Roles.
A good practice is to have a SuperAdmin wich contains all Sub-Roles.
Feel free to add your application Roles as childRole to the predefined Role 'SuperAdmin'
or make your own Application Tree in the RBAC TopLevel.

A little Tutorial Part 1)

Feel free to have a look in the Class RBACAccessVerifier.php
Check access in your Controller:
There are only tree methods for checking access in the RBACAccessVerifier to work with.
checkAccess(string role[, boolean redirect=false])
checkAccessByValue(string role, mixed value[, boolean redirect=false])
checkAccessByData(string role, array(mixed index => mixed value[, ...])[, boolean redirect=false])
And there is one method you can use if you have made your checkAccess without redirect and got false as result:
denyAccess(void);

// For simple Check 
$this->checkAccess('anyRole'); 
 
// simple check with redirect
$this->checkAccess('anyRole', true);
 
// extended check with bizRule (will use default index)
$this->checkAccessByValue('anyRole', $mixedValue);
 
// extended check with bizRule with redirect (will use default index)
$this->checkAccessByValue('anyRole', 123, true);
 
// even more komplex check with more data 
$this->checkAccessByData('anyRole', array('pet'=>'doc', 'number'=>123));
 
// even more komplex check with more data and with redirect
$this->checkAccessByData('anyRole', array('pet'=>'doc', 'number'=>123), true);
 
// thats all you can do in your Controller

A little Tutorial Part 2)

Now bring them together with buisness Rules stored in your Database
at this point you should know, how the bizRules work:

After a Buisness Rule the AccessController ends with the Buisness Rule Result
and does not climp up to Parent any more.

Check Access steps in Detail:
1. if User has requested Item Assigned do 2. - else do 4.
2. if requested User Assignment Item has Buisness Rule check and end - else do 3.
3. if requested RBAC Item has Buisness Rule check and end - else end with true
4. if requested Item has parent do 1. with parent as requested Item - else end with false

The Data field is not used while checking access. Feel free to use it fore your needs.

There are only two methods for BizRules in the RBACAccessVerifier to work with:
bizRule([mixed value, ...])
bizParam(mixed index, array([mixed value, ...]))

And of course you have all other methods of Yii aviable like:
Yii::app()->...any value or method with any params

Let's go with BizRules (Buisness Rules):

// extended check with method bizRule (will use default index, normaly 'id')
$this->checkAccessByValue('anyRole', $mixedValue);
// should have bizRule:
Yii::app()->controller->bizRule($mixedValue, $mixedValue2, $mixedValue_n, $and_so_on);
 
// very extended check with bizParam (will use your index
$this->checkAccessByData('anyRole', array('name'=>'Peter'));
// should have bizRule:
Yii::app()->controller->bizParam('name', array('Peter', 'Lucy'));
// or:
Yii::app()->controller->bizParam('name', 'Peter');
 
// if your default index is 'id' this works too
$this->checkAccessByData('anyRole', array('id'=>$mixedValue));
// with bizRule
Yii::app()->controller->bizRule($mixedValue, $mixedValue2, $mixedValue_n, $and_so_on);
// or in opposide
$this->checkAccessByValue('anyRole', $mixedValue);
// with bizRule 
Yii::app()->controller->bizParam('id', $mixedValue);
 
// this will throw an error
$this->checkAccess('anyRole');
// with bizRule 
Yii::app()->controller->bizParam('id', $mixedValue);

If that all is not enougth, learn more in Yii's Docu: Role-Based Access Control.

Total 5 comments

#14236 report it
dudareviv at 2013/07/29 09:20am
Don't like this extension

The best part is the protection of recursion and informative design. I do not understand why you used the native build cgridview and it is hard to prevent the integration of your extension in the project.

#13381 report it
Néstor Acevedo at 2013/05/26 10:25pm
doesn't work

it doesn't work for me.

i follow the instructions, in my controller i put in adminView

$this->checkAccess('SuperAdmin')

and always i get a 403 error

#6549 report it
macdemac at 2012/01/17 09:07pm
Using RBAC for a Federated Data Model

Hi,

Firstly thanks for the great module. It must have taken a great deal of work.

I am investigating whether I can use RBAC-Manager in a federated data model, which I am designing to provide membership based services to different clubs. The basic problem is that I want to have a single instance of the database for all subscribed clubs with admins and members only able to see their own clubs data.

Being a novice using YII and PHP I am not certain as to whether your module will allow me to setup RBAC-Manager in this mode.

I would appreciate your feedback on my questions.

Thanks.

brettm

#6444 report it
YiieHR at 2012/01/11 02:23am
good job

maybe optimize the UI will greate

#3384 report it
Tudor Ilisoi at 2011/04/08 06:59am
Automate css publishing

here's what you can paste into RBACBaseController so it self-publishes the css:

protected function beforeAction($action) {
        $cs = Yii::app()->clientScript;
        $assets = Yii::getPathOfAlias('application.modules.rbac.data');
        $assets = str_replace("\\", '/', $assets);
        $aUrl = Yii::app()->getAssetManager()->publish($assets);
        $cs->registerCssFile($aUrl . "/rbac.css" );
        return parent::beforeAction($action);
    }

for the given structure it will also publish the sql and install files wich are in the data folder(this method publishes the entire folder into Yii::app()->baseUrl.'/assets'), wich is somewhat unwanted and insecure

Leave a comment

Please to leave your comment.

Create extension
Downloads
No downloadable files yet