0

I am using yii2 basic and implemented RBAC.

I have two roles admin and fieldofficer and created permissions and rules and assigned users. Now when admin logs in, on index page he should be able to see all records as well as his created records in grid.

Whereas when fieldofficer logs in, he should be able to see only his created records in index page.

How to accomplish this?

Questions
  • 69
  • 1
  • 12

1 Answers1

1

You need to pre-load the user's id into the Search Model. If security is an issue (ie: you don't want other user's to be able to bypass this no matter what), then you will need to detect if the user's id has been passed to the query, and force it back to the user you want (ie: the one logged in). In most situations, your going to need the extra security, and should.

Replace UserPlan with whatever your model is. Since you didn't post code, I have no clue what it is :)

Before: Original Index Example (as generated by Gii):

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

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

After: Locked to the currently logged in user:

public function actionIndex()
{
    $searchModel = new UserPlanSearch();
    $searchModel->user_id = Yii::$app->user->id;

    // override (so users can't bypass)
    $queryParams = Yii::$app->request->queryParams;
    if ( isset($queryParams['UserPlan']['user_id']) ) {
        $queryParams['UserPlan']['user_id'] = Yii::$app->user->id;
    }

    $dataProvider = $searchModel->search($queryParams);
    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

Also, you should post code when posting to StackOverflow unless you want a bunch of down votes. Just asking questions, is against the rules. They want to see what you have tried so far, and some code to go by.

Wade
  • 3,757
  • 2
  • 32
  • 51