Reputation: 33348
We are using the Auth component. We are currently able to prevent non-logged in users from visiting our "admin" page (adminhome.ctp). But we can't figure out how to make isAuthorized()
prevent non-admins from visiting the page also.
Inside the AppController:
public function beforeFilter() {
$this->Auth->allow('index', 'view', 'login', 'logout', 'display');
$this->Auth->authorize = array('Controller');
//$this->Auth->autoRedirect = false;
}
public function isAuthorized($user_id) {
$this->loadModel('User');
$user = $this->User->findById($this->Auth->user());
if ( $user['User']['role'] === 'admin') {
$this->Session->setFlash('isAuthorized');
return true;
}
$this->Session->setFlash('!isAuthorized');
return false;
}
Here the beforeFilter() in PagesController:
function beforeFilter() {
$this->Auth->deny('adminhome');
}
What are we doing wrong?
Upvotes: 0
Views: 2124
Reputation: 123
I have just used Aryan answer however I have made some minor changes which could be helpful for others:
if($this->Session->read('Auth.User.role') != 'admin')
{
$this->Session->setFlash('You are not authorized to visit this page');
$this->redirect('/');
}
Upvotes: 2
Reputation: 1061
You'll have role field in user table. In particular action add this line
if($this->Session->read('Auht.User.role') != 'admin') {
...............................
}
If you want only admin can see every actions in some controller like admincontroller
you can add this code in that controller in beforeRender action
if($this->Session->read('Auth.User.role') != 'admin')
{
$this->Session->setFlash(You are not authorized to visit this page,'flash',array('alert'=>'info'));
$this->redirect('/');
}
Upvotes: 0
Reputation: 1818
I believe that your way it doesn't work because you should use Auth->deny() to restrict access to methods, and adminhome is not a method in the PagesController. Try this:
# in app/controller/PagesController.php
public function display() {
$page = empty($this->request->params['pass'][0]) ? null : $this->request->params['pass'][0];
if($page == 'adminhome' || $this->User->isAuthorized()) {
$this->render($page);
} else {
# redirect the user somewhere else
}
}
I hope this helps
Upvotes: 1