CakePHP 3 - 具有编号角色的授权

CakePHP 3 - Authorization with numbered roles

所以我有 4 个不同的角色,它们在用户 table 中是属性 "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;
    }
}

然后在用户控制器中:

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);
    }
}

每个用户都可以访问 'register'、'forgetpw'、'resetpw' 的视图,如 UsersController 的初始化函数中所述。目前没有用户可以访问 'index'、'add'、'view' 或 'edit',管理员应该可以访问它们。

我在想,如果可以修复 UserController 页面的授权,我可以将其应用于所有其他 Controller。

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

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

应该是

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