Yii Framework Forum: RBAC on Yii 2.0 advanced template - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

RBAC on Yii 2.0 advanced template

#1 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 18 May 2017 - 08:12 AM

Hi,

I use Yii 2.0 advanced template and I created my tables 'RBAC' and
I try implant the Building Authorization Data by according to followings articles
http://www.yiiframew...th-rbac-system/
http://www.yiiframew...horization.html


So I have some urls like these:
localhost/index.php?r=admin/permission
localhost/index.php?r=admin/role
localhost/index.php?r=admin/assignment
localhost/index.php?r=admin/route

here is my resume :

I create, for example, two permission on following URL : index.php?r=admin/permission
(on the table of MySql : auth_item)
  • Name : createDepartment
    Description : create Departement
    Rule Name : empty / nothing
    Data : empty / nothing
  • Name : superAdmin
    Description : superAdmin can create
    Rule Name : empty / nothing
    Data : empty / nothing


And I can give a permission at superAdmin to createDepartment on index.php?r=admin%2Fpermission%2Fview&id=superAdmin
(on the table of MySql : auth_item_child)
  • parent : superAdmin
  • child : createDepartment


and I assign admin right [superAdmin] to a user : on /index.php?r=admin%2Fassignment%2Fview&id=2
(on the table of MySql : auth_assignment)
  • item_name: superAdmin
  • user_id: 2


And I rectified DepartmentController.php [yii2-app-advanced\backend\controllers]
by adding if condition :
if (Yii::$app->user->can('createDepartment'))
else
		{
			throw new ForbiddenHttpException;
		}

like this :
	if (Yii::$app->user->can('createDepartment'))
	{
		$model = new Department();

		if ($model->load(Yii::$app->request->post()) && $model->save()) {
			return $this->redirect(['view', 'id' => $model->id]);
		} else {
			return $this->render('create', [
				'model' => $model,
			]);
		}
	}
	else
	{
		throw new ForbiddenHttpException;
	}


etc... So now only "superAdmin" can create a department.
It's works. :) ;D ::) :rolleyes:

So here is all my questiion on RBAC

1- what is it a Data fields when I create a permission/role (auth_item) index.php?r=admin/permission ?
  • 1.1 on the mySql table [auth_item], what is 'type' field ?
  • 1.1.1 I have always 2 (value) at this field [type]. Why ?


2- What is it exactly a rule with RBAC ?
  • 2.1 how can I create a rule ?
  • 2.1.1 by which url : ?
  • 2.2 can I create a rule when I create a permission by filling 'Rule Name' field ?



3- What is it exactly a role with RBAC [/index.php?r=admin/role]?
  • 3.1 can you give me a exemple ?
  • 3.1.1 How and where can I use a role ?


4- Must I change MANUALLY all my controllers for assign admin right by adding if condition [Yii::$app->user->can] :blink: or are there an automatisation by RBAC ? ???
  • 4.1 if yes, how I can implant this automatisation ?


Thanks
0

#2 User is offline   aspkiddy 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 19-May 17

  Posted 19 May 2017 - 12:35 PM

Hi Tonton,

It's cool your post.
I used your explanation, step by step and I have some questions like you.
In fact, I have not found clear and understandable documents on the web about RBAC
I think It is a new young modulus.Nobody knows exactly how is work by DbManager.
So I am also stuck on the same kind of questions
0

#3 User is offline   samdark 

  • Having fun
  • Yii
  • Group: Yii Dev Team
  • Posts: 5,139
  • Joined: 17-January 09
  • Location:Russia

Posted 22 May 2017 - 06:24 PM

1. You shouldn't really care about DB structure since you'll never read/write it directly but just for reference, data fields may contain extra data that it passed to RBAC hierarchy item when it's being checked.
1.1. Type of the RBAC hierarchy item. Either role (1) or permission (2).
1.1.1. Because permissions are marked with 2.


2. A rule defines a condition that should be met in order for permission to be granted. It is defined via code.
2.1. http://www.yiiframew...tml#using-rules
2.1.1. The wiki article is a bit weird about using those URLs. I'd build hierarchy as described in the guide instead.
2.2. See official guide.


3. A role is RBAC hierarchy item which is assigned to user.
3.1. "admin", "editor".
3.1.1. You can assign role to users. You can assign permissions to role.


4. You can use access check filter. Additionally you can create a controller class, check it there and then inherit all your admin controller from that one.
4.1. See the guide.
Yii 2.0 Development Cookbook

Enjoying Yii? Star us at github

Support me so I work on Yii fulltime: https://www.patreon.com/samdark
1

#4 User is offline   samdark 

  • Having fun
  • Yii
  • Group: Yii Dev Team
  • Posts: 5,139
  • Joined: 17-January 09
  • Location:Russia

Posted 22 May 2017 - 06:25 PM

Quote

Nobody knows exactly how is work by DbManager.


Same as with PhpManager. Via Manager interface as described in the guide.
Yii 2.0 Development Cookbook

Enjoying Yii? Star us at github

Support me so I work on Yii fulltime: https://www.patreon.com/samdark
1

#5 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 23 May 2017 - 12:59 PM

Thanks SamDark, :)

I'm going to read your answers and I will try to applicate...
I think, I will have some other questions so I will be ask to you...

thanks
0

#6 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 23 May 2017 - 03:35 PM

Hi,

I'm lost... :blink:

I can create the role or permission like following example using following forms / links :

localhost/index.php/admin/role
Create Role

localhost/index.php/admin/role/create
Name : "admin"
Description : "the admin have all of authorization : he can delete/ create/ Update / view"
Rule Name :
Data :

:) in the table [auth_item] there is 1 into type field like as a 'role'

localhost/index.php/admin/permission/create
Create Permission
localhost/index.php/admin/permission/create
Name : superAdmin
Description : all of authorization : delete/ create/ Update / view
Rule Name :
Data :
:lol: in the same table [auth_item] there is 2 into type field like as a 'permission'

So I have a role and some permissions
Role Name : "admin"
Permissions (authorisation item) : superAdmin
and others permissions : actionCreate / actionDelete /etc.

create a rule
And now I would create a rule "authenticated user like 'SuperAdmin'"
name : "condition of admin"


But how can I create a rule ? :mellow:
I can use some yii form like like localhost/index.php/admin/rule/create
or I must use phpMyAdmin / MuSql WorkBench etc ?

On phpMyAdmin, I have this option : I can choose binary file by [data] field.
What is it ?

Thanks
0

#7 User is offline   samdark 

  • Having fun
  • Yii
  • Group: Yii Dev Team
  • Posts: 5,139
  • Joined: 17-January 09
  • Location:Russia

Posted 24 May 2017 - 06:19 AM

Again, forget about URLs and that extension. Try RBAC how it's described in the official guide.
Yii 2.0 Development Cookbook

Enjoying Yii? Star us at github

Support me so I work on Yii fulltime: https://www.patreon.com/samdark
1

#8 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

Posted 24 May 2017 - 03:44 PM

Thanks SamDark,

View Postsamdark, on 24 May 2017 - 06:19 AM, said:

Again, forget about URLs and that extension. Try RBAC how it's described in the official guide.


I don't understand very weel the document (the official guide) well and that's why I wanted to use the URLs and that extension ...

Ok I will not use...

Now, I know what is a 'role' and 'permission' but I am not yet able to grasp the history of rule

So I want to write rule for me : to clarify my ideas and to understand the official guide (http://www.yiiframew...tml#using-rules).
I have a rule like this :

Quote

The folloving action can make by guest user not yet authenticated : login and signup


How I can name this rule in the table [auth_rule] ? like this : The rule of consultation by unknown ? or rCconsultationUnknown
I need to know this : It is only for indicative purposes

But I am able to concretize this story by the following code

'rules' => [
			[
				'allow' => true,
				'actions' => ['login', 'signup'],
				'roles' => ['?'],
			],

0

#9 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 25 May 2017 - 11:29 AM

HI,

I'm learning and reading the RBAC official guide.

In this guide : http://www.yiiframew...horization.html

Quote

If this option is empty or not set, it means the rule applies to all controllers

So in SiteController.php, I have this 'access rule' / code to all controllers :
return [
	'access' => [
		'class' => AccessControl::className(),
		'rules' => [
			[
				'actions' => ['login', 'error'],
				'allow' => true,
			],
			[
				'actions' => ['logout', 'index'],
				'allow' => true,
				'roles' => ['@'],
			],
		],
	],



Now I would add another 'access rule' to next controllers : : EmployeeController.php (class EmployeeController extends Controller) and DepartmentController.php (lass DepartmentController extends Controller)

How can I find its controller IDs ? :mellow:

It is [EmployeeController] and [DepartmentController], is not it ? :rolleyes:

I don't want to add each 'access rule' into the each own controllers file. So can I add into the SiteController.php ?
'controllers' => ['EmployeeController', 'DepartmentController'],

like this :
return [
	'access' => [
		'class' => AccessControl::className(),
		'rules' => [
			[
				'actions' => ['login', 'error'],
				'allow' => true,
			],
			[
				'actions' => ['logout', 'index'],
				'allow' => true,
				'roles' => ['@'],
			],			
			[
				'actions' => ['newActionA', 'newActionA'],
				'controllers' => ['EmployeeController', 'DepartmentController'],
				'allow' => true,
				'roles' => ['@'],
			],
		],
	],


Thanks
0

#10 User is offline   tri 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,806
  • Joined: 20-November 08
  • Location:Stockholm, Sweden

Posted 25 May 2017 - 12:12 PM

Quote

If this option is empty or not set, it means the rule applies to all controllers

To me it makes sense if used in a base controller (not 100% sure about Yii2).

Edit: According to this section, application or module level can be used. I guess the array returned from a base controller needs to be merged with any local additions, so probably not the best idea???
This list seems to say you don't need to merge with definitions application/module level

Quote

Apply filters declared in the application in the order they are listed in behaviors().
Apply filters declared in the module in the order they are listed in behaviors().
Apply filters declared in the controller in the order they are listed in behaviors().



Quote

How can I find its controller IDs ?

For an example, follow the link present in the doc page you referred to (section about "controller" option).
Don't forget to read The Definitive Guide to Yii (1.1 en) (1.1 sv) (2.0 en) | The class reference (1.1) (2.0) has the details
1

#11 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 25 May 2017 - 02:10 PM

Hi,

Thanks for this link : http://www.yiiframew...l#using-filters

I wondered how can we know the actions. I know also how can I create the action thanks to that your link

I return to the stories of the Controller IDs : controller-ids

http://www.yiiframew...#controller-ids :

Quote

By default, controller IDs should contain these characters only: English letters in lower case, digits, underscores, hyphens, and forward slashes. For example, article and post-comment are both valid controlle


So in my case, with my examples:

My ids : [employee] and [department], is it right ? :rolleyes:

Like this :


EmployeeController.php
class : EmployeeController
and its controller IDS : employee


DepartmentController.php
Class : DepartmentController
and its controller IDS : department

So can I use some access control filters by putting on only into the SiteController.php, at help by the Controller IDs
like this :
return [
        'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                        [
                                'actions' => ['login', 'error'], //all of controllers / models
                                'allow' => true,
                        ],
                        [
                                'actions' => ['logout', 'index'], //all of controllers / models
                                'allow' => true,
                                'roles' => ['@'],
                        ],                      
                        [
                                'actions' => ['newActionA', 'newActionA'],
                                'controllers' => ['employee', 'department'], //those actions can allow only 2 controllers / models
                                'allow' => true,
                                'roles' => ['@'],
                        ],
                ],
        ],


Or I must put it on own each controller like this :

  • into the SiteController.php

return [
        'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                        [
                                'actions' => ['login', 'error'], //all of controllers / models
                                'allow' => true,
                        ],
                        [
                                'actions' => ['logout', 'index'], //all of controllers / models
                                'allow' => true,
                                'roles' => ['@'],
                        ],                      
                ],
        ],

  • into the EmployeeController.php
    return [
            'access' => [
                    'class' => AccessControl::className(),
                    'rules' => [
                            [
                                    'actions' => ['newActionA', 'newActionA'], // adding new filltre actions
                                    'allow' => true,
                                    'roles' => ['@'],
                            ],                      
                    ],
            ],


and (or)
  • into the DepartmentController.php

return [
        'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                        [
                                'actions' => ['login', 'error'], 
                                'allow' => true,
                        ],
                        [
                                'actions' => ['logout', 'index','newActionA', 'newActionA'],
                                'allow' => true,
                                'roles' => ['@'],
                        ],                      
                ],
        ],


Thanks
0

#12 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 26 May 2017 - 11:25 AM

Hi,

I think my question is not claire because nobody help me. :blink:

I will say otherwise to clarify the situation of my questions. :rolleyes:


I want to know if we can use only one file (SiteController.php) for all web pages by access control filters ? ???

Some actions (logout/ signup /etc) are all of controllers
'access' => [
	'class' => AccessControl::className(),
	'only' => ['logout', 'signup'],
	'rules' => [
		[
			'actions' => ['signup'],
			'allow' => true,
			'roles' => ['?'],
		],
		[
			'actions' => ['logout'],
			'allow' => true,
			'roles' => ['@'],
		],
	],

and to forbidden certain actions like 'index' at certain controllers (visitorController.php and callerController.php) if user is guest like this :
'access' => [
	'class' => AccessControl::className(),
	'only' => ['logout', 'signup','index'],
	'rules' => [
		[
			'actions' => ['signup'],
			'allow' => true,
			'roles' => ['?'],
		],
		[
			'actions' => ['logout'],
			'allow' => true,
			'roles' => ['@'],
		],
		[
			'actions' => ['index'],
			'controllers' => ['visitor', 'caller'], // index is forbidden only visitorController  and callerController if user is guest 
			'allow' => true,
			'roles' => ['@'],
		],
	],


Thanks
0

#13 User is offline   tri 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,806
  • Joined: 20-November 08
  • Location:Stockholm, Sweden

Posted 26 May 2017 - 11:46 AM

View Posttonton, on 26 May 2017 - 11:25 AM, said:

...
I want to know if we can use only one file (SiteController.php) for all web pages by access control filters ? ???
...


Look here again

Application level definition will probably go into the application config file, which returns an config array.

To expect it to work from SiteController doesn't make sense (unless it's the base controller for the rest). It's not mandatory to access the SiteController in a request.
Don't forget to read The Definitive Guide to Yii (1.1 en) (1.1 sv) (2.0 en) | The class reference (1.1) (2.0) has the details
1

#14 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 26 May 2017 - 12:58 PM

Thanks Tri,

View Posttri, on 26 May 2017 - 11:46 AM, said:

To expect it to work from SiteController doesn't make sense (unless it's the base controller for the rest). It's not mandatory to access the SiteController in a request.

So, I must put the access control filters, into THE each controller, must not I ? :(

ok like this (e.g. visitorController.php):


if(Yii::$app->user->identity->status == "admin")
	{
		return
		[
			'access' => 
				[
					'class' => AccessControl::className(),
					'rules' => 
					[
						[
							'actions' => ['index','view','create','update','delete'],
							'allow' => true, 
							'roles' => ['@'], 
						],
					],
				],
		];
	}
else
	{
		throw new ForbiddenHttpException;
	}

0

#15 User is offline   samdark 

  • Having fun
  • Yii
  • Group: Yii Dev Team
  • Posts: 5,139
  • Joined: 17-January 09
  • Location:Russia

Posted 28 May 2017 - 08:10 AM

Either you put it into each controller or you create BaseController class, put it there and inherit all your controllers from it.
Yii 2.0 Development Cookbook

Enjoying Yii? Star us at github

Support me so I work on Yii fulltime: https://www.patreon.com/samdark
1

#16 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 30 May 2017 - 10:16 AM

Many Thanks, SamDark for this solution which I need it.

I would create this base controller.
So where I must put it this file ? into which directory ? yii2-app-advanced\backend\controllers ?

I will be try to create by GII :
like this : localhost/index.php/gii/controller

Controller Class : backend\controllers\BaseController
Action IDs : index
View Path (be blank)
Base Class : yii\web\Controller
Code Template : default (E:\site\yii\yii2-app-advanced\vendor\yiisoft\yii2-gii\generators\crud/default)

  • generated controllers\BaseController.php
  • generated views\base\index.php


So I have a BaseController.php in : E:\site\yii\\yii2-app-advanced\backend\controllers

1- Is it right ? :rolleyes:

And I think, I must change some code in this file (BaseController.php) :
namespace backend\controllers;

class BaseController extends \yii\web\Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

}

2- I must add some namespaces : Is it right ? :mellow:
3- Add 'status admin' on behaviors function, Is it right ? :rolleyes:
aND then
4- add a new role/rule "createDepartment" for "DepartmentController.php" into the function "actionCreate()" Is it right ? :mellow:

Here is my new controller after I added all of this :
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;	


class BaseController extends \yii\web\Controller
{
    
	public function behaviors()
    {
        if(Yii::$app->user->identity->status == "admin")
        {
			return
			[
				'access' => 
                [
					'class' => AccessControl::className(),
                    'rules' =>
					[
						[
							'actions' => ['index','view','create','update','delete'],
                            'allow' => true, 
                            'roles' => ['@'], 
                         ],
                     ],
                  ],
            ];
        }
		else
        {
			throw new ForbiddenHttpException;
        }
		
		return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }
	
	public function actionCreate()
    {
		if (Yii::$app->user->can('createDepartment'))
		{
			$model = new Department();

			if ($model->load(Yii::$app->request->post()) && $model->save()) {
				return $this->redirect(['view', 'id' => $model->id]);
			} else {
				return $this->render('create', [
					'model' => $model,
				]);
			}
		}
		else
		{
			throw new ForbiddenHttpException;
		}
	
	}
	
	// I don't know if I need following code :
	public function actionIndex()
    {
        return $this->render('index');
    }

}

What do you think ? is it good or there are something wrong ?
And now, I must change my others controlleurs : SiteController and DepartmentController, must not I ?

I extends SiteController by BaseController like this :
//class SiteController extends Controller
class SiteController extends \backend\controllers\BaseController

5- Is it right ? :rolleyes:

and for this (extends by BaseController) I must add use namespace like this into those file :
use backend\controllers\BaseController;

6- Is it right ? :rolleyes:
And I must add same thing for DepartmentController

I am wrong in these steps, am I not ?

thanks
0

#17 User is offline   tri 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,806
  • Joined: 20-November 08
  • Location:Stockholm, Sweden

Posted 30 May 2017 - 11:12 AM

Read this for a start
https://stackoverflo...roller-in-yii-2

(BTW Is it a correct assumption you cannot access Google where you live? :huh: )
Don't forget to read The Definitive Guide to Yii (1.1 en) (1.1 sv) (2.0 en) | The class reference (1.1) (2.0) has the details
0

#18 User is offline   tonton 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 43
  • Joined: 25-April 17

  Posted 31 May 2017 - 07:42 AM

Hi,

I know this article and I made my BaseController by reading this article.

View Posttri, on 30 May 2017 - 11:12 AM, said:



But I need confirmation on my steps above, beacuse it is not the same context between mine and that of this article

I would like to be assured that what I have done is correct

So what do you think on my BaseController above ?
Is it correct or not ?

I would like to know also my changes above are correct on my others controlleurs : SiteController and DepartmentController,

Your thoughts and help helps me alot on the understanding of Yii and PHP


Thanks

Note : BTW ? what is it ? :rolleyes:

View Posttri, on 30 May 2017 - 11:12 AM, said:

(BTW Is it a correct assumption you cannot access Google where you live? :huh: )

I can access Google ant thanks to that I found this article (How can create BaseController extends Controller in Yii 2 on stackoverflow) before your post. :D
0

#19 User is offline   tri 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,806
  • Joined: 20-November 08
  • Location:Stockholm, Sweden

Posted 31 May 2017 - 09:39 AM

Controllers: Already answered here

That means you should extend all other controllers from your BaseController (if you need what BaseController adds, in every controller).

Your "if statement" will only define the filter if you are "admin". No restriction for other users. For start without RBAC, perhaps just declare the '@' or '?' using a trinary operator isadmin?'@':'?'
Edit: This logic will not work. You have to figure out a correct filter. IIRC, If the 'access' is defined, but left empty no action will be allowed. You can have combinations of "allow" and "deny" filters. The order they appear are significant. E.g allow authenticated users some actions before a specific users conditionally allowed actions before deny the rest (empty 'role' may work) (I think, check the doc page and search for info posted earlier somewhere).


Then try to add other access filters (you told us you need but I'm not sure I understand why) in other controller(s).

Thus you will actually return a new PHP array from the behavior() function of an inherited controller. Unless the framework automagically merge it with what was returned in BaseController (don't think so), you have to do the "parent" merge. Remember that the order of rules will be significant (so good luck).
Don't forget to read The Definitive Guide to Yii (1.1 en) (1.1 sv) (2.0 en) | The class reference (1.1) (2.0) has the details
1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users