Give user limited access of data

Hey all, I want to give only specific user to get the data. I have company table and user table. In my user table I have company_id field so that I can relate two tables. The thing I want, When a user logged in, I want the user to see that related company info not the other company’s information. How can I achieve that? I did some research. I found this Yii::$app->user->identity. But I dont know exactly how to do it. I am beginner in Yii. Thanks for your time.

Hi @yasoyase

You need to use RBAC (Role-Based Access Control) feature of Yii.
Check the following section of the Definitive Guide.

If you are talking about the gridview, or something that uses the Search Model for the model in question, you can create a new search method that filters data to the user’s company id. In your User Model, create a function to return the company id given the user id.

public static function getCompanyId($user_id)
{
$user = self::findOne($user_id);
return $user->company_id;
}

In the Search Model, copy & paste the search method (public function search($params) ) and name it something else. At the top of this new method, make your call to the method in the User model to get the company id.

$company_id = User::getCompanyId(Yii::$app->user->identity->id);

Look for the line that says
'company_id' => $this->company_id,
and change it to
‘company_id’ => $company_id,

In your controller for the action that displays the data, look for the line that defines $dataProvider,
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
and change ‘search’ to whatever you named your new search method.

You definitely want to set up access control to allow for regular users to use the limited search method, but not the original one that returns everything.

1 Like

Tables should be something like

users

  • id
  • name
  • company_id

companies

  • id
  • name

records

  • id
  • title
  • amount
  • company_id

then every time you query something remember to limit by its company ID

$userCompany = Yii::$app->user->identity->company_id;
$records = Record::find()->where(['company' => $userCompany])->all();

the identity in Yii::$app->user->identity is the user identity class that you configured in web config. Most f the time it extends your user model which abstracts the users table