D
D
Dmitry2017-02-02 14:42:22
Yii
Dmitry, 2017-02-02 14:42:22

How to implement role switching or substitution in Yii2?

There was a need to have one user in the database, but with several roles and the ability to switch between available ones, for example, by clicking on a button with the name of the corresponding role.
The role must be changed for the duration of the session or before switching to another role.
Perhaps someone has come across something similar?
Yii2 . We use RBAC .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-02-02
@another_dream

Overridden the authManager component and extended the DbManager class:

<?php
namespace common\rbac;

use Yii;
use yii\rbac\DbManager as YiiDbManager;

class DbManager extends YiiDbManager
{
    /**
     * Выбранная роль
     * @var
     */
    protected $currentRole;

    /**
     * Немного переопределим инициализацию, чтобы узнать какую роль установил юзер
     */
    public function init()
    {
        parent::init();

        if (is_null($this->currentRole)) {
            // Здесь проставим выбранную роль для юзера
           // Пока что вручную, потом данный параметр будет подтягиваться из сессий, к примеру
            $this->currentRole = 'buyer';
        }
    }


    /**
     * Определим какую из ролей пользователя выдать под текущий запрос
     * @param $userId
     * @return array
     */
    public function getAssignments($userId)
    {
        // Доступные пользователю роли
        $allAssignments = parent::getAssignments($userId);
        // Какую роль он предпочёл в этот раз
        $currentRole = $this->currentRole;

        // Найдём в доступных ролях требуемую
        $assignments = array_filter(
            $allAssignments,
            function ($key) use ($currentRole) {
                return $key === $currentRole;
            },
            ARRAY_FILTER_USE_KEY
        );

        // Если роль не нашлась, то используем первую из доступных
        if (empty($assignments)) {
            $assignments = array_shift($allAssignments);
        }

        return $assignments;
    }
}

The above solution does its job well.
Any comments? I will be grateful for constructive criticism or alternative options.

M
Maxim Timofeev, 2017-02-02
@webinar

What's the problem?
Option 1 - Create rights to switch roles, who can, who can't, etc. Switched - changed role.
The second option is that Yii provides that 1 user can have 2 or more roles, and you can add some activeRole identifier, but you will have to rewrite a lot.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question