Hi I’m creating a simple CMS, that some day will be more complex I hope, and I am struggling to understand RBAC on Yii2.
I read the documentation and the guide but I need some more examples of the implementation of RBAC(with database) so that I can understand how it works. do you guys know any good tutorial or code examples so that I can try to follow?
and one more thing using the code on the examples,
Once you have created the permissions and assigned them to Roles and assigned one or more Roles to Users, you can use the names of those Roles in the behaviors function that returns the [‘access’]['rules][‘roles’] array. (see yii\filters\AccessControl)
or you can call this boolean method to check if the user has a permission:
How far have you gotten in the process? Is the authmanager prepared? Do you have roles assigned? Are the rules assigned but not working? Please elaborate.
Ok, if everything is set up (including the config) you just have to create the roles and assign them. When you create roles and assign them the information is stored in the database tables you set up for role management so you only need to do it once.
Well, now that you are getting console apps, you see that you would have different actions in it like a controller, so according to our example two actions you might have are:
public function actionCreaterole($rolename)
{
$auth = Yii::$app->authManager;
$role = $auth->createRole($rolename);
if ($auth->add($role))
echo "Role \"{$role->name}\" created\n";
else
echo "ROLE CREATION FAILED\n";
}
and
public function actionAssignrole($username, $role)
{
$user = $this->getUser($username);
$auth = Yii::$app->authManager;
$role = $auth->getRole($role);
$auth->assign($role, $user->id);
}
Ok I made the script and it is creating every thing as it should… didn’t test the rules yet…
One quick thing:
the default roles are for what(in the config files) is it to assign automatically to the visitors of the page or I have to declare all roles there?
I will have some trouble with the rules, but I probably will try to figure it out my self… If I need any more help related with RBAC I’ll come here again…
About default roles, it sounds like perhaps you should not worry about default roles since you are just starting out. In it’s simplest form, default roles are just roles that are automatically assigned to all users. You would do this instead of having to go in and assign a role to each user after they create their account. You would only have to do this if users typically need a very basic role to do anything on your site. For more info: http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#using-default-roles
In this case I would assume that the user id would be stored with the article record, and you would compare the user’s id with the user id stored with the article record to determine ownership. You would not need any roles for that.