0

What is the best way to do query with filters based on roles from RBAC.

Objective: each user role see different results.

It's good create a sequence of "ifs" or is there another good organization for this?

Table auth_item:

id     |  name           
-------+---------
1      |  boss    
2      |  chef 
3      |  employe

Table contacts

id     |    name     |  id_department |  contact            
-------+-------------+----------------+-------------
1      |    John     |       2        | 999 999 999   
2      |    Angela   |       4        | 999 452 998 
3      |    Bea      |       5        | 999 678 997 
4      |    Monique  |       4        | 999 125 923

My current code:

public function actionIndex()
{
    $searchModel = new Contacts();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    if (\Yii::$app->user->can('employe')) {

        $dataProvider->query->andFilterWhere(['id_department' => 4]);
    } elseif (\Yii::$app->user->can('chef')) {
        $dataProvider->query->andFilterWhere(['id_department' => 2]);
    } elseif (\Yii::$app->user->can('boss')) {
        $dataProvider->query->andFilterWhere(['IN', 'id_department', [1, 2, 3, 4, 5]]); //all results
    }

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Moutinho
  • 321
  • 3
  • 14
  • 1
    That's the way if your results depend on user role. I would move `if conditions` in `search` function and reduce query results with `andWhere`, also set `id_department` to be index field in db if it's not. – vvpanchev Apr 08 '21 at 08:12
  • 1
    Your if conditions have one problem. If you have some hierarchy in roles it might not work as expected. If `chef` can do all `employe` can and some extra tasks, and the `boss` can do all `employe` and `chef` can do plus some extra tasks. In case like that if the `boss` is logged in the first if would be true and `elseif` parts wouldn't be checked. You want to order the conditions from most specialised to most generic. – Michal Hynčica Apr 08 '21 at 08:42

0 Answers0