@EVOSandru6

Ошибка в проверке на роль в контроллере yii1?

Добрый день,

Организовал доступ к контроллерам на основе ролей как указано в документации:
yiiframework.ru/doc/cookbook/ru/access.rbac.file

<?php
class UserIdentity extends CUserIdentity
{
    protected $_id;
    public function authenticate()
    {
        $user = Users::model()->find('LOWER(email)=?',
            [
                strtolower($this->username)
            ]);
        if(
            $user->confirm &&
            (
                ($user  === null) || (md5($this->password) !== $user->password)
            )
        )
            $this->errorCode = self::ERROR_USERNAME_INVALID;
		else 
		{
            $this->_id                  =    $user->id;
            $this->username             =    $user->name;
            $this->setState('id',           $user->id);
            $this->setState('email',        $user->email);
            $this->setState('role',         $user->role_id);
            $this->setState('sex',          $user->sex_id);
            $this->setState('adress',       $user->adress);
            $this->setState('postcode',     $user->postcode);
            $this->setState('role_name',    $user->role->name);
            $this->setState('telephone',    $user->telephone);
            $this->setState('country',      $user->country);
            $this->setState('city',         $user->city);

            $this->errorCode = self::ERROR_NONE;
        }
        return !$this->errorCode;
    }
    public function getId(){
        return $this->_id;
    }
}

<?php
class WebUser extends CWebUser
{
    private $_model = null;
    public $loginUrl = ['users/login'];
    private function getModel()
    {
        if (!$this->isGuest && $this->_model === null)
        {
            $this->_model       =   Users::model()->findByPk($this->id); // , $criteria
        }
        return $this->_model;
    }

    function getRole()
    {
        if($user = $this->getModel())
        {
            // в таблице User есть поле role
            return $user->role_id;
        }
    }
    public function getEmail()
    {
        if ($user = $this->getModel())
            return $user->email;
    }
    function getRoleName()
    {
        if($user = $this->getModel())
            return $user->role->name;
    }
    public function getSex()
    {
        if ($user = $this->getModel())
            return $user->sex_id;
    }
    public function getTelephone()
    {
        if ($user = $this->getModel())
            return $user->telephone;
    }
    function getId()
    {
        if($user = $this->getModel())
            return $user->id;
    }
    public function getCountry()
    {
        if ($user = $this->getModel())
            return $user->country;
    }
    public function getCity()
    {
        if ($user = $this->getModel())
            return $user->city;
    }
    public function getAdress()
    {
        if ($user = $this->getModel())
            return $user->adress;
    }
    public function getPostcode()
    {
        if ($user = $this->getModel())
            return $user->postcode;
    }
}

class PhpAuthManager extends CPhpAuthManager
{
    public function init()
    {
        if($this->authFile  === null)
            $this->authFile =   Yii::getPathOfAlias('application.config.auth').'.php';
        parent::init();
        if(!Yii::app()->user->isGuest)
        {
            $this->assign
            (
                Yii::app()->user->role
                , Yii::app()->user->id
            );
        }
    }
}


protected/config/auth.php


return
   [
       'guest' =>
       [
           'type'           =>      CAuthItem::TYPE_ROLE,
           'description'    =>      'Guest',
           'bizRule'        =>      null,
           'data'           =>      null
       ],
       '2' =>
       [
           'type'           =>       CAuthItem::TYPE_ROLE,
           'description'    =>      'customer',
           'children'       =>
           [
               'guest', // унаследуемся от гостя
           ],
           'bizRule'        =>      null,
           'data'           =>      null
       ],
       '3' =>
       [
           'type'           =>      CAuthItem::TYPE_ROLE,
           'description'    =>      'moderator',
           'children'       =>
           [
               'customer',          // позволим модератору всё, что позволено пользователю
           ],
           'bizRule'        =>      null,
           'data'           =>      null
       ],
       '4' =>
       [
           'type'           =>      CAuthItem::TYPE_ROLE,
           'description'    =>      'admin',
           'children'       =>
           [
               'moderator',          // позволим модератору всё, что позволено пользователю
           ],
           'bizRule'        =>      null,
           'data'           =>      null
       ],
   ];


В классе Users есть константы ролей:
const ID_CUSTOMER       =   2;
    const ID_MODERATOR    =   3;
    const ID_ADMIN              =   4;


По какой то причине пользователь с ролью 4 получает exception, что недостаточно прав (403), хотя в контроллере такая конструкция:

public function accessRules()
    {
        return
		[
            ['allow',
                'actions'=>
				[
					'show',
					'index',
					'view',
					'admin',
					'toggle',
					'update'
				],
                'roles'	=> [ Users::ID_ADMIN ],
            ],
            ['deny',
                'users'=>['*'],
            ],
        ];
    }


Если комментирую 'accessControl' расписываю:
echo Users::ID_ADMIN .':'.Yii::app()->user->role;
		die();


То получаю 4:4 , в чем может быть проблема?

Также при закоменченом accessControl

Если в actionIndex пишу:

if(Yii::app()->user->checkAccess('4'))
echo "hello, I'm administrator";
else
echo Users::ID_ADMIN .':'.Yii::app()->user->role;
die();


То ловлю :

hello, I'm administrator


Какой то глюк именно в accessRules
  • Вопрос задан
  • 159 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
28 мая 2024, в 08:33
500000 руб./за проект
28 мая 2024, в 07:56
1500 руб./в час
28 мая 2024, в 06:55
400 руб./в час