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 Compo开发者_开发技巧nent. 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
}
}
function register()
{
if ($this->Auth->user())
{
$this->redirect('someOtherPage');
// or exit;
}
//other stuff
}
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');
}
}
精彩评论