R
R
Roman2017-01-04 01:51:30
Yii
Roman, 2017-01-04 01:51:30

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>;
            ...

And get the value of the role in the code like this:
if (Yii::$app->user->identity->role == User::SOME_ROLE) {
    // Do something
}

How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-01-04
@kublahanov

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 question

Ask a Question

731 491 924 answers to any question