开发者

Roles in CakePHP Auth Component

I'm trying to use roles in the CakePHP Auth component. The roles would be user, admin, super-admin, etc. I'm having difficulty with placing a conditional in each controller based off the user role. I tried the following and it didn't work:

function  beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('add');

        if($this->Auth->user('roles') == 'admin') {
            $this->Auth->allow('index', 'add', 'edit', 'delete');
        } 
        elseif($this->Auth->user('roles') == 'super-admin') {
            $this->Auth->allow('index', 'add', 'edit', 'delete', 'make_super_admin', 'privileges'); //Note difference in superadmin privile开发者_高级运维dges

        }

The problem is with the conditional. I want the function to go in each controller (UsersController, PatientsController, AdmissionsController, etc.) and based off the user role, give different permissions.


Placing this logic in the beforeFilter() of the AppController class should do the trick.

Another thought that I had was that maybe you should consider using the Acl component in conjunction with the Auth component. The Acl component will give you out-of-the-box granular control over every action in every controller. If used correctly, you'd only have to set permissions on the actions for each role and the type of access-control checking that you are currently trying to do will be automated.

The book has an excellent tutorial on how to make this work. I'm using it in my application and it's well worth the time invested to setup and understand how it all works. Reference below.

CakePHP Book :: Simple Acl controlled Application


I don't know if this is your problem, but if you want to allow every action you have to use * instead of nothing:

function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('add');

    if($this->Auth->user('roles') == 'admin') {
        $this->Auth->allow('*');
    } elseif($this->Auth->user('roles') == 'super-admin') { 
        $this->Auth->allow('*');
    }
}

If you want to set those permissions for every controller it would be the best to put it in your AppController so it will affect everything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜