Yii2- How to restrict a user from viewing others data in index page


Keywords:yii2 


Question: 

I am working on yii2 in my project, I have users and their roles. Each role is given access to a Module and a Sub Menu. There is a sub-menu named SIM List in which all the SIM records can be viewed. There is a field named issued_to which tells us that which SIM has been issued to which user.

Unless a SIM is issued to any user, the issued_to field will remain empty. Once issued the name of the user will appear on the SIM List.

Now I want to manage it in such a way that only a specific user can see the list. For example 5 Sims have been issued to a user named U. Now the user U should only see that SIM records which are issued to him, otherwise the list should be empty.

In my Index controller I am getting issued_to field name which is empty by default.

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

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

By doing like below I can get issued_to user id

$model = $dataProvider->getModels()[0];
$user_id =  $model['issued_to'];
var_dump($user_id);
exit();

Now in this controller, I want to add a check of user_id which gives me only the records which are of that specific user.

Index View

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        //'id',
        'imsi',
        'sim_number',
        'operator_name',
        'data_details',
        'sms_details',
        'monthly_bill',
        //'created_by',
        [
            'label' => 'Created By',
            'value' => function ($data) {
                if (is_object($data))
                    return $data->created->name;
                return ' - ';
            },
            //'filter' => Html::activeDropDownList($searchModel, 'created_by', \app\models\User::toArrayList(), ['prompt' => "Created By", 'class' => 'form-control']),
        ],
        'created_at',
        // 'updated_at',
        'status',
        // 'updated_by',
        //'sim_stauts',
        [
            'label'=>'SIM Status',
            'value'=>function($a){
                return $a->getStatusvalue();
            }
        ],
        //'issued_to',
        [
            'label' => 'Issued To',
            'value' => function ($d) {
                if(is_object($d->user))
                    //return $d->user->name;
                    return $d->issued_to == '' ? '' : $d->user->username;
                return ' - ';
                // return $d->user->name;

            },
            'filter' => Html::activeDropDownList($searchModel, 'issued_to', \app\models\User::toArrayList(), ['prompt' => "Users", 'class' => 'form-control']),

        ],
       //'returned_by',
        [
            'label' => 'Returned By',
            'value' => function ($d) {
                if(is_object($d->user2))
                    //return $d->user->name;
                    return $d->returned_by == '' ? '' : $d->user->username;
                return ' - ';
                // return $d->user->name;

            },
            'filter' => Html::activeDropDownList($searchModel, 'returned_by', \app\models\User::toArrayList(), ['prompt' => "Users", 'class' => 'form-control']),

        ],
        'historic',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

Update 1

My search model is below

public function search($params)
{
    $query = Sims::find();

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

    // grid filtering conditions
    $query->andFilterWhere([
        'id' => $this->id,
        'created_by' => $this->created_by,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'updated_by' => $this->updated_by,
        'sim_stauts' => $this->sim_stauts,
        'issued_to' => $this->issued_to,
        'returned_by' => $this->returned_by,
        'historic' => $this->historic,
    ]);

    $query->andFilterWhere(['like', 'imsi', $this->imsi])
        ->andFilterWhere(['like', 'sim_number', $this->sim_number])
        ->andFilterWhere(['like', 'operator_name', $this->operator_name])
        ->andFilterWhere(['like', 'data_details', $this->data_details])
        ->andFilterWhere(['like', 'sms_details', $this->sms_details])
        ->andFilterWhere(['like', 'monthly_bill', $this->monthly_bill])
        ->andFilterWhere(['like', 'status', $this->status]);

    return $dataProvider;
}

How can I achieve it? Any help would be highly appreciated.


1 Answer: 

As per your description, you have the user_id saved inside the issued_to field and you need to only fetch the results that have the current logged in user_id saved in the field issued_to.

I assume that your search in the grid view is visible to only logged-in users.

You should set the issued_to param manually by first getting the queryParams array from the request object Yii::$app->request->queryParams; which has the array in the same format as the POST has i.e ['ModelName']['field_name'] so you need to infact set the issued_to as

$arrayParams['SimSearch']['issued_to']=Yii:$app->user->id;

Your actionIndex should look like below

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

    //check if user or one of the managers
    $isAdmin=in_array(Yii::$app->user->identity->user_role,[1,6]);

    //set params if normal user
    if(!$isAdmin){
       $queryParams['SimsSearch']['issued_to']=Yii::$app->user->id;
    }

    $dataProvider = $searchModel->search($queryParams);

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

Hope this helps you out.