Answer the question
In order to leave comments, you need to log in
How to make dynamic role detection in Yii2?
Given:
There are a number of diverse entities (companies, inspections, services, etc.). There are users. Entities are linked to some of the users through junction tables. Links may change from time to time. The user table does not contain fields to define the user's role, and no additional tables are expected to be created.
Required:
Add to Yii::$app->user->identity the role field, which would be filled during user authorization, and, later, used to simply check access to entities (if there is an entry with given UserId - we assign a certain role to the user and check it when necessary).
I would like to make it as simple as possible, without using additional tables, without RBAC and extensions.
Checking the user's connection (defining his role) is done, for example, like this:
class User extends ActiveRecord implements IdentityInterface
{
...
public function init()
{
parent::init();
Yii::$app->user->on(WebUser::EVENT_AFTER_LOGIN, [$this, 'assignRole']);
}
public function assignRole()
{
if ($this) {
$this->role = <Role ID>;
...
if (Yii::$app->user->identity->role == User::SOME_ROLE) {
// Do something
}
Answer the question
In order to leave comments, you need to log in
If you want to solve the problem correctly - use RBAC. What you are trying to do is crutches. In an attempt to avoid "extra" entities, you are moving in the wrong direction. Your solution:
1. Reduces the obviousness of the code.
2. Reduces the overall flexibility and scalability of the system.
3. Deprives the possibility of built-in caching of access data, do you plan to implement it yourself?
4. Deprives the ability to check access to actions using AccessControl, or do you plan to write a bunch of ifs in each action to check access?
and you can write a lot of other things. In fact, you are now asking "how to hammer a nail with a planer?" the answer is no way, for this you need to use a hammer.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question