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



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

我的应用控制器如下:

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

每个用户都可以访问"注册","忘记pw","重置pw"的视图,如用户控制器的初始化函数中所述。目前没有用户可以访问"索引"、"添加"、"查看"或"编辑",管理员应该可以访问这些内容。

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

好的,

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

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

应该是

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

最新更新