Yii2 - Скрыть настройки администратора в зависимости от роли пользователя - PullRequest
0 голосов
/ 05 августа 2020

У меня есть дерево, в котором я показываю узлы и их дочерние узлы. Я хочу скрыть параметры, отличные от admin, для пользователя, не являющегося администратором. По умолчанию isAdmin равно true. Для проверки ролей пользователей я сделал следующее.

<?=
TreeView::widget([
    'query' => \common\models\MdcNode::find()->addOrderBy('root, lft'),
    'headingOptions' => ['label' => 'Root'],
    'rootOptions' => ['label'=>'<span class="text-primary">Root</span>'],
    'topRootAsHeading' => true, // this will override the headingOptions
    'fontAwesome' => true,
    'isAdmin' => function(){
          if (Yii::$app->user->identity->user_role == 1)
          {
              return true;
          }
          else
          {
              return false;
          }
    },
    'iconEditSettings'=> [
        'show' => 'list',
        'listData' => [
            'building' => 'Building',
            'folder' => 'Floor',
            'user' => 'Customer'
        ]
    ],
    'softDelete' => true,
    'cacheSettings' => ['enableCache' => true]
]);
?>

Теперь, когда я запускаю свой код. Я получаю сообщение об ошибке ниже, когда нажимаю на узел

Operation Disallowed
Invalid request signature detected during tree data manage action! Please refresh the page and retry.
OLD HASH:
785a3cf9cbb1a90e862b718ed8ae3289944280448ae801de49d686aa5f70e951common\models\MdcNodehidebtn-default/mdc/backend/web/treemanager/node/save/mdc/backend/web/mdcnode/index@kvtree/views/_formw0-nodeselnodenodes<div class="kv-node-message">No valid nodes are available for display. Use toolbar buttons to add nodes.</div>111111{"id":"w0-nodeform"}{"1":"","2":"","3":"","4":"","5":""}{"submit":"<i class=\"glyphicon glyphicon-floppy-disk\"></i>","reset":"<i class=\"glyphicon glyphicon-repeat\"></i>"}a:0:{}[]list{"":"<em>Default</em> ( <span class=\"text-warning kv-node-icon kv-icon-parent\"><i class=\"fa fa-folder-close kv-node-closed\"></i></span> / <span class=\"text-warning kv-node-icon kv-icon-parent\"><i class=\"fa fa-folder-open kv-node-opened\"></i></span> / <span class=\"text-info kv-node-icon kv-icon-child\"><i class=\"fa fa-file\"></i></span>)","building":"<span class=\"fa fa-building\"></span> Building","folder":"<span class=\"fa fa-folder\"></span> Floor","user":"<span class=\"fa fa-user\"></span> Customer"}{"depth":"","glue":" &raquo; ","activeCss":"kv-crumb-active","untitled":"Untitled"}
NEW HASH:
e3037c327c2ddec080a38ce50002f825a214352f833f2acfe972c3d7d0a2b9abcommon\models\MdcNodehidebtn-default/mdc/backend/web/treemanager/node/save/mdc/backend/web/mdcnode/index@kvtree/views/_formw0-nodeselnodenodes<div class="kv-node-message">No valid nodes are available for display. Use toolbar buttons to add nodes.</div>11111{"id":"w0-nodeform"}{"1":"","2":"","3":"","4":"","5":""}{"submit":"<i class=\"glyphicon glyphicon-floppy-disk\"></i>","reset":"<i class=\"glyphicon glyphicon-repeat\"></i>"}a:0:{}[]list{"":"<em>Default</em> ( <span class=\"text-warning kv-node-icon kv-icon-parent\"><i class=\"fa fa-folder-close kv-node-closed\"></i></span> / <span class=\"text-warning kv-node-icon kv-icon-parent\"><i class=\"fa fa-folder-open kv-node-opened\"></i></span> / <span class=\"text-info kv-node-icon kv-icon-child\"><i class=\"fa fa-file\"></i></span>)","building":"<span class=\"fa fa-building\"></span> Building","folder":"<span class=\"fa fa-folder\"></span> Floor","user":"<span class=\"fa fa-user\"></span> Customer"}{"depth":"","glue":" &raquo; ","activeCss":"kv-crumb-active","untitled":"Untitled"}

Обновление 1

Ниже моя модель пользователя

class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;


/**
 * @inheritdoc
 */
public static function tableName()
{
    return '{{%user}}';
}

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        TimestampBehavior::className(),
    ];
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        ['status', 'default', 'value' => self::STATUS_ACTIVE],
        ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
    ];
}

/**
 * @inheritdoc
 */
public static function findIdentity($id)
{
    return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}

/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $type = null)
{
    return static::findOne(['auth_key' => $token]);
}

/**
 * Finds user by username
 *
 * @param string $username
 * @return static|null
 */
public static function findByUsername($username)
{
    return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}

/**
 * Finds user by password reset token
 *
 * @param string $token password reset token
 * @return static|null
 */
public static function findByPasswordResetToken($token)
{
    if (!static::isPasswordResetTokenValid($token)) {
        return null;
    }

    return static::findOne([
        'password_reset_token' => $token,
        'status' => self::STATUS_ACTIVE,
    ]);
}

/**
 * Finds out if password reset token is valid
 *
 * @param string $token password reset token
 * @return bool
 */
public static function isPasswordResetTokenValid($token)
{
    if (empty($token)) {
        return false;
    }

    $timestamp = (int) substr($token, strrpos($token, '_') + 1);
    $expire = Yii::$app->params['user.passwordResetTokenExpire'];
    return $timestamp + $expire >= time();
}

/**
 * @inheritdoc
 */
public function getId()
{
    return $this->getPrimaryKey();
}

/**
 * @inheritdoc
 */
public function getAuthKey()
{
    return $this->auth_key;
}

/**
 * @inheritdoc
 */
public function validateAuthKey($authKey)
{
    return $this->getAuthKey() === $authKey;
}

/**
 * Validates password
 *
 * @param string $password password to validate
 * @return bool if password provided is valid for current user
 */
public function validatePassword($password)
{
    return Yii::$app->security->validatePassword($password, $this->password_hash);
}

/**
 * Generates password hash from password and sets it to the model
 *
 * @param string $password
 */
public function setPassword($password)
{
    $this->password_hash = Yii::$app->security->generatePasswordHash($password);
}

/**
 * Generates "remember me" authentication key
 */
public function generateAuthKey()
{
    $this->auth_key = Yii::$app->security->generateRandomString();
}

/**
 * Generates new password reset token
 */
public function generatePasswordResetToken()
{
    $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}

/**
 * Removes password reset token
 */
public function removePasswordResetToken()
{
    $this->password_reset_token = null;
}   

public static function toArrayList()
{
    return ArrayHelper::map(self::find()->where(['user_role'=>2,'status'=>10])->all(),'id','username');
}
}

Структура таблицы пользователей

введите описание изображения здесь

RBA C Модель

class Rbac extends \yii\db\ActiveRecord
{
/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'rbac';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['controller', 'action'], 'string', 'max' => 50],
        [['roles'], 'string', 'max' => 255],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'controller' => 'Controller',
        'action' => 'Action',
        'roles' => 'Roles',
    ];
}

public static function allowAccess($c,$a){
    $sql= /** @lang text */
        "select count(*) as total from rbac where (controller='$c' and action='$a') and (roles = '' OR roles IS NULL OR FIND_IN_SET(". Yii::$app->user->identity->user_role . ",roles)<>0)";

    $rbac = Yii::$app->db->createCommand($sql);

    $r = $rbac->queryOne();
    return $r['total'] > 0;
}
}
...