linkyndy
linkyndy

Reputation: 17900

Deny certain controller action permission in CakePHP

The idea is quite simple. If you are not logged in, you have no access to any page beside the register and login page. If you are logged in, you have access to all pages except the register page.

Now, half of this is achieved by using CakePHP's Auth Component. This restricts access when not logged, and allows access when logged.

The problem I stumbled upon when doing this was restricting access to the register page when logged. I tried different methods, all with the same result: the register page was still accessible.

Need some help, as I got stuck with this problem.

Here's part of my code (the beforeFilter() in the UsersController class; register() would be the action from within this controller):

function beforeFilter(){
    parent::beforeFilter();

    $this->Auth->allow("register");

    if($this->Auth->user()){//if user is logged in...
        $this->Auth->deny("register");//...deny his access to register and login page
    }
}

Upvotes: 3

Views: 5760

Answers (2)

bancer
bancer

Reputation: 7525

Try to do it this way:

function beforeFilter() {
    $this->Auth->authorize = 'controller';
    $this->Auth->allow('register');
}

function isAuthorized() {
    if ($this->Auth->user()) {
        $this->Auth->deny('register');
    }
}

UPDATE: Probably, the cleaner solution would be

function beforeFilter() {
    $this->Auth->authorize = 'controller';
    if(is_null($this->Auth->user())) {
        $this->Auth->allow('register');
    }
}

Upvotes: 2

Leo
Leo

Reputation: 6571

function register()
{
    if ($this->Auth->user())
    {
        $this->redirect('someOtherPage');
        // or exit;
    }
    //other stuff
}

Upvotes: 3

Related Questions