CakePHP 3 - 带编号角色的授权

时间:2017-01-11 06:49:17

标签: cakephp authorization cakephp-3.0 cakephp-3.x

所以我有4个不同的角色,在Users表中是属性" role_id"下的外键。管理员的role_id等于1.我一直试图阻止所有用户,但管理员无法访问管理页面,例如用户'索引页。

我的AppController如下:

class AppController extends Controller
{

public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Auth',[
            'authorize' => 'Controller',
        ]);

        $this->Auth->allow(['display', 'index', 'view', 'add']);
    }

public function isAuthorized($user)
    {
        // Default deny
        return false;
    }
}

然后在UsersController中:

class UsersController extends AppController
{

public function initialize()
    {
        parent::initialize();
        // Add logout to the allowed actions list.
        $this->Auth->deny(['index', 'add', 'view']); 
        $this->Auth->allow(['register', 'forgetpw', 'resetpw', 'logout']);
    }

public function isAuthorized($user)
    {       
        if (in_array($this->request->action,['view', 'edit', 'index', 'add'])) {
            return (bool)($user['role_id'] === '1');
        }

        return parent::isAuthorized($user);
    }
}

每个用户都可以访问“注册'”,“忘记密码”,“重新启动'如在UsersController的初始化函数中允许的那样。目前没有用户可以访问'索引'添加','查看'或者'编辑',管理员应该可以访问。

我认为如果可以修复UserController页面的授权,我可以将其应用于所有其他控制器。

1 个答案:

答案 0 :(得分:0)

好的,我想我已经解决了这个问题。

return (bool)($user['role_id'] === '1');

应该是

return (bool)($user['role_id'] === 1);
相关问题