I’m having trouble getting a simple RBAC rule working. I want the user to be able to able to access actionView($id) if the $id is their own.
My view action is the simple gii generated one:
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
The behaviors are:
...
'actions' => [
'class' => AccessControl::className(),
'only' => ['index','view', 'create', 'update', 'delete' ],
'rules' => [
[
'allow' => true,
'actions' => ['index'],
'roles' => ['manageUsers'],
],
[
'allow' => true,
'actions' => ['view'],
'roles' => ['viewUser'],
],
...
The relevant parts of my RbacController look like this:
//separation of user and admin
$userGroupRule = new UserGroupRule();
$auth->add($userGroupRule);
//check if the owns the id on the page
$userOwnerRule = new UserOwnerRule();
$auth->add($userOwnerRule);
// roles
$user = $auth->createRole('user');
$user->ruleName = $userGroupRule->name;
$auth->add($user);
$admin = $auth->createRole('admin');
$admin->ruleName = $userGroupRule->name;
$auth->add($admin);
// permissions
$viewUser = $auth->createPermission('viewUser');
$viewUser->description = "View A User";
$auth->add($viewUser);
$viewUserRestricted = $auth->createPermission('viewUserRestricted');
$viewUserRestricted->ruleName = $userOwnerRule->name;
$viewUserRestricted->description = "View Only Yourself";
$auth->add($viewUserRestricted);
//add sub permissions to permissions
$auth->addChild($viewUserRestricted, $viewUser);
//assignments of permissions to role
$auth->addChild($user, $viewUserRestricted);
$auth->addChild($admin, $viewUser);
//give admin user's stuff
$auth->addChild($admin, $user);
My rule looks like this:
class UserOwnerRule extends Rule
{
public $name = 'isOwner';
public function execute($user, $item, $params)
{
if (isset($params['user'])) {
error_log("The user parameter is set.");
error_log("View ID: " . $params['user']->id);
error_log("The User: " . $user);
return ($params['user']->id == $user);
}
else {
error_log("The user parameter is not set.");
error_log("The User: " . $user);
return false;
}
}
}
Edit:
I guess a simpler way to put this is that the rule applies automatically without me using
(\Yii::$app->user->can(‘viewUser’)). This causes users to be denied from actionView with their own $id because the $params[] aren’t set. How do I get the user model being loaded in actionView to the $params[] variable in UserOwnerRule if the user is being denied before the action’s code even runs?