Skip to content

Instantly share code, notes, and snippets.

@tiagoa
Created October 20, 2012 20:13
Show Gist options
  • Save tiagoa/3924633 to your computer and use it in GitHub Desktop.
Save tiagoa/3924633 to your computer and use it in GitHub Desktop.
A CakePHP access control implementation with a User hasMany Role schema
<?php
class AppController extends Controller {
public $permissions = array(
'Admin' => '*',
'Student'=>array(
array('controller'=>'pages', 'action'=>'display'),
array('controller'=>'books', 'action'=>'*')
)
);
function beforeFilter() {
$this->Auth->allow('users', 'login');
$this->Auth->allow('books', 'index');
$this->isAuthorized();
}
public function verifyRole($roles){
$request = $this->request->params;
foreach($roles as $role):
if($this->permissions[$role] == '*'):
return true;
else:
foreach($this->permissions[$role] as $permission):
if($permission['controller'] == $request['controller']):
if($permission['action'] == '*'):
return true;
else:
if($permission['action'] == $request['action']):
return true;
else:
return false;
endif;
endif;
endif;
endforeach;
endif;
endforeach;
}
function isAuthorized(){
if($this->Auth->loggedIn()){
$personId = $this->Auth->user('Person_id');
if($personId):
Controller::loadModel('Person');
/*
Get the active roles from the Person Model in an simple array:
Student roles: array('Student', 'Default')
Teacher roles: array('Teacher', 'Default')
Coordinator roles: array('Coordinator', 'Teacher', 'Default')
*/
$roles = $this->Person->listActiveRoles($personId);
if(!empty($roles)):
if(!$this->verifyRole($roles)):
$this->Session->setFlash("You do not have permission.");
$this->redirect($this->Auth->loginRedirect);
endif;
else:
$this->Session->setFlash("You do not have an active role.");
$this->redirect($this->Auth->logout());
endif;
else:
$this->Session->setFlash("Your user is not vinculated to a person.");
$this->redirect($this->Auth->logout());
endif;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment