I am using Yii 2 basic application template.
I have the scenario where one teacher can be assigned to multiple ASC centers. One ASC center can have many teachers.
Following are the mysql tables.
- ascassignment - (ASCAssignmentId, ASCId, UserId)
- student - (StudentId, ASCId, StudentName, DateofBirth)
I have implemented RBAC and is functioning well. Now I have create a RBAC rule which allows the teachers to view, update and delete only those student details who belong to their ASC centers i.e, teachers whose ASCId matches with the ASCId from student will only be allowed to update, view and delete.
But now index page does not shows the details correctly. For eg: A teacher Ashok has been assigned to two ASC centers called A and B. Now this teacher creates students records for both ASC centers. Now on index page of students he can see only students records of B ASC center.
Following is the Rule
<?php
namespace app\rbac;
use Yii;
use yii\rbac\Rule;
use app\models\Ascuser;
use app\models\Ascassignment;
/**
* Checks if authorID matches user passed via params
*/
class ASCCenterstudentsRule extends Rule
{
public $name = 'ASCCenterStud';
/**
* @param string|int $user the user ID.
* @param Item $item the role or permission that this rule is associated with
* @param array $params parameters passed to ManagerInterface::checkAccess().
* @return bool a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{
$userid=\Yii::$app->user->identity->getonlyid();
$ascid1;
$ascid= Yii::$app->db->createCommand('SELECT asccenter.ASCId
FROM asccenter,ascassignment
where asccenter.ASCId=ascassignment.ASCId
and ascassignment.UserId=:id
'
)->bindValues([':id' => $userid])
->queryAll();
foreach($ascid as $ascid2)
{
$ascid1=$ascid2['ASCId'];
if($ascid1==$params['model']->ASCId)
{
return $params['model'];
}
}
}
}
index action of Student
public function actionIndex()
{
$searchModel = new StudentSearch();
if (!Yii::$app->user->can('indexStudent')) {
$userid=\Yii::$app->user->identity->getonlyid();
$ascid= Yii::$app->db->createCommand('SELECT asccenter.ASCId
FROM asccenter,ascassignment
where asccenter.ASCId=ascassignment.ASCId
and ascassignment.UserId=:id
'
)->bindValues([':id' => $userid])
->queryAll();
foreach($ascid as $ascid2)
{
$ascid1=$ascid2['ASCId'];
}
$searchModel->ASCId = $ascid1;
}
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$query= Student::find();
$count=$query->count();
$pagination= new Pagination(['defaultPageSize' => 5,
'totalCount' => $count]);
$training = $query->offset($pagination->offset)->limit($pagination->limit)->all();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'pagination' => $pagination,
]);
}