Complete RBAC and User Module with Authorization Solution

Hi Everyone …

I am Puneeth and new to yii framework so here are few lines why i wrote this article… I was recently assigned to new project and asked to implement project using Yii framework… Fortunately I am sole player for this project(fortunately because I can learn new things)

In fact I am fresher… So you all can imagine difficulty i am going through to implement hopefully… So I am learning and read dozens of article about implementing User Module with authorization…

Even downloads many extension went through the code… So i consumed lot of time reading and experimenting and few draw backs while implementing for my project…

So here is many articles at one place with addition to solutions for the problem i faced.

Here is the catch even i am also newbie for programming and it is my first article in my life so please correct if am wrong or if there a is efficient way to implement it…

My sincere thanks to many peoples who have written many Articles for people like me…

Finally i hope this article is going to be usefully for peoples like me atleast for some extend…

Lets get to Classes

1:User

2:Identity Class

3:DbManager

4:Rule

5:Role

6:Permission

7:AccessControl

8:AccessRule

1:User is class that is present in yii\web\User… This manage User status only not the actual implementation and you can access all the time using Yii::$app->user

2:Identity class contains actual implementation of user login and this call should implement IdentityInterface and we have to configure this as parameter in configuration file for user component

3:DbManager uses database for storing authorization for individual User using tables auth_item, and auth_assignement, auth_rule, auth_item_child

4:Role is set of Permission or in simple Authorization we give for User like admin, employee so on…

5:Permission addition privilege given to Role or in simple a special permission for only for our favourite Role

6:Rule is applied for both Permission and Role in simple like legal system rule is common for all

7:AccessControl is used inside behaviours method of Controller class to check Authorization of the users

8:AccessRule is used by AccessControl to check the Authorization and it is passed as parameter to AccessControl (ex ‘rules’=>[])

First Biggest Question Raises for many is where to write DbManager

1: For predefined Role and Permission the Rbac can be written as Separate Controller we can place this file inside commands folder for Basic template or inside console for Advanced Template

2: we define the authorization inside actionInit() method

3: If we have predefined User you can also assign role or permission inside Controller only




$auth = Yii::$app->authManager;

 $auth->assign($author, 2);  here $author is instance of $author role  and 2 is user id(primary key/Unique) 

	//we can also give role name as String 'author' instead of variable



4:Here role name should be unique and in fact it is primary key for auth_item tables so down the line we can insert same role name more than once

5:As mentioned our roles or permission are saved in auth_item table with name field as role/permission

6:Users assigned with role is saved inside auth_assignment table with item_name as role and user_id of the user

Sample code is from web


class RbacController extends Controller

{

    public function actionInit()

    {

        $auth = Yii::$app->authManager;


        // add "createPost" permission

        $createPost = $auth->createPermission('createPost');

        $createPost->description = 'Create a post';

        $auth->add($createPost);


        // add "updatePost" permission

        $updatePost = $auth->createPermission('updatePost');

        $updatePost->description = 'Update post';

        $auth->add($updatePost);


        // add "author" role and give this role the "createPost" permission

        $author = $auth->createRole('author');

        $auth->add($author);

        $auth->addChild($author, $createPost);


        // add "admin" role and give this role the "updatePost" permission

        // as well as the permissions of the "author" role

        $admin = $auth->createRole('admin');

        $auth->add($admin);

        $auth->addChild($admin, $updatePost);

        $auth->addChild($admin, $author);


        // Assign roles to users. 1 and 2 are IDs returned by IdentityInterface::getId()

        // usually implemented in your User model.

        $auth->assign($author, 2); 

        $auth->assign($admin, 1);

    }

}

Second Question how to insert inside database Table

1:well updating roles inside database tables is one time shot

2:we can go to command prompt and change directory to root project and type


yii/rbac init

3:how ever before type this command you have to configure authManager inside your Configuration File


'authManager'=>[

			'class'=>yii\rbac\DbManager;

		]

4:next you have to create tables inside your database in which ever convenient way you choose yii\migrate for Advanced template or copy paste for basic Template

Third Question How to Assign Roles for users

1:Dynamic Assignment happens when we create/ register user inside LoginForm Class after saving the data




 $auth = Yii::$app->authManager;

 $auth->assign(RoleName, lastInsertedId);

Fourth Question Checking Authorization

1: we can check user Authorization by using using two components of Application


Yii::$app->user->can('rolename') return boolean 

Yii::$app->authManager->x methods 

Rule

This class honestly even at the moment i dont know what it does even after reading many specification also no idea how is implement it… hopefully some can shed some light on it even for me so i can take advantage of this class Here is what i know so for About Rule

Sample Code from web




namespace app\rbac;


use yii\rbac\Rule;




class AuthorRule extends Rule

{

    public $name = 'isAuthor';


    public function execute($user, $item, $params)

    {

        return isset($params['post']) ? $params['post']->createdBy == $user : false;

    }

}


Inside Rbac Controller  

---------------------------


$auth = Yii::$app->authManager;


// add the rule

$rule = new \app\rbac\AuthorRule;

$auth->add($rule);



So when do this and run command


Yii\rbac init 

this obviously update the table auth_rule and insert data in bizarre way specially data field

What is use of this table no idea when to use it no idea so please share your knowledge on this please

auth_child

I think most of know what this is and how it works by now

let make a fast track of this topic

1:We can add child for each Role in simple Every Manager as number of team leader and every team leader as number of team member so here if manage is Main role then his children are TL and Team member

2:So for Obvious reasons Manager as more power then TL and Team Member and vice versa is not true

3:Manager can do both TL and Team Member works but Team Member can’t do manager works

End of this topic

Fifth Question is all about Controller

1: we can check weather the user as authorization for this Controller and any Action inside the Controller by using the method


public function behaviours(){


  return [

	'as access'=>[

	'only'=>[specify your action here that this filter should apply]

	'rules'=>[

		'actions'=>[]

		'controllers'=>[]

		'roles'=>[Now we can change beautiful yet simple @ and ? character and place your roles here ] // 

		'allow'=>true

		'denyCallBack'=>specify your function if role does not match

		

			]

	

		]

	

	];


}

Its All About User Now

Since the Topic say Rbac and ! User Module so lets talks about few things for User implementation wrt DbManager

As mentioned above User class only manages User status but for real world we need more than that

1:To check weather the user is blocked or pending

2:If it SOA ex: Your Application is used for some multiple organization and you want to block some organization

3:Organization want to block the one of its employee

4: so on so on…

1:For these things you can write you own User class

2:Custom User class should yii\web\User class so in this you we dont have code from scratch

3:Configure your custom class in Configuration File


'user'=>[

		'class'=>MyUserClass

		'identityClass'

	]



4:Since User class does not extends From Model or ActiveRecords we can have add Custom error like Account Blocked

5:Rest is explain Using Two class for understanding LoginForm class that extends Model and MyUserClass

6:Here MyUserClass contains Logic or methods pertaining to validations like user blocked or organization blocked

7:LoginForm class uses MyUserClass methods to check validation and if validation fails we can send custom error back to user

1:The Flow (These should execute before validataion/ rules())

1:User enter username and password

2:Get Username and find where the User exists first method like is User::findByUsername(‘username’)

3:get User id or primary key of that username User::findByUsername(‘username’)->getId();

4:we need id of username so can we get role for that user from auth_assignement table this is in case if we are have multiple tables for multiple role

2:Validate the user before login() methods

1:here we use rules methods to check validation


public function rules(){

 

	return [

		['username', 'required']

		['username' function(attribute){

			if($user !== null){ //: if this condition is not there and above 4 points is not executed and  mainly the user didnt exits you keep getting fatal error here

				//do some sql queries  here or call methods defined in this class or User class

				if(check role exits){

				

				}

				if(Organization is blocked){

				

				 $this->addError($att, 'Organization Blocked')

				

				}else if(check if user blocked ){

				

					if blocked 

					$this->addError($att, 'Accout Blocked')

				

				}

			

			

			}

		

		}

	

	]

 

 

 }

3:Login




	if(!hasErrors()){

	

	login();

	

	}

End of this Article…

if any typo error sorry about that… if anything wrong correct me… i am open for learning and implementing in new ways