Created
October 20, 2012 20:13
-
-
Save tiagoa/3924633 to your computer and use it in GitHub Desktop.
A CakePHP access control implementation with a User hasMany Role schema
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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