I am working on a relatively big project with a lot of controllers and actions and unknown number of user roles. I've decided to use CodeIgniter framework.
The first problem that I faced was the implementation of user authorization and his role permissions logic.
I wrote a solution that works pretty good for me, but I need your criticism, so I can make it better and continue to use it in future projects cleanly.
So ... in /system/codeigniter/CodeIgniter.php I change this code:
Code: Select all
// Call the requested method.
// Any URI segments present (besides the class/function) will be passed to the method for convenience
call_user_func_array(array(&$CI, $method), array_slice($RTR->rsegments, (($RTR->fetch_directory() == '') ? 2 : 3)))Code: Select all
if (method_exists($CI, '_check_privileges'))
{
if ($CI->_check_privileges($class, $method))
{
// Call the requested method.
// Any URI segments present (besides the class/function) will be passed to the method for convenience
call_user_func_array(array(&$CI, $method), array_slice($RTR->rsegments, (($RTR->fetch_directory() == '') ? 2 : 3)));
}
}
else
{
// Call the requested method.
// Any URI segments present (besides the class/function) will be passed to the method for convenience
call_user_func_array(array(&$CI, $method), array_slice($RTR->rsegments, (($RTR->fetch_directory() == '') ? 2 : 3)));
}Code: Select all
class CC_Controller extends Controller
{
var $is_login = false;
function CC_Controller($is_login = false)
{
parent::Controller();
$this->is_login = $is_login;
$this->user_logged = empty($_SESSION) ? false : (!empty($_SESSION['user_id']) ? true : false);
}
function _check_privileges($object = null, $method = null)
{
// Populate object/method values
$this->object = $object;
$this->method = $method;
// Only login controller should set $is_login to true
if ($this->is_login)
return true;
// Obviously user could not be granted any permissions when not logged in
if (!$this->user_logged)
return false;
if (empty($object) || empty($method))
return false;
// Role model should return 2D Array of object/methods
$this->load->model('role_model', '_role');
$this->role_permissions = $this->_role->get_permissions($_SESSION['user_role']);
// Role not found
if (empty($this->role_permissions))
return false;
// Permission to access this controller not granted
if (empty($this->role_permissions[strtolower($object)]))
return false;
// Permission to access this action of the controller not granted
if (empty($this->role_permissions[strtolower($object)][strtolower($method)]))
return false;
// OK
return true;
}
}
Any comments are welcome
PS: Maybe implementing a group role permissions is a good idea, but I think it should be placed in the Model, transparently to the CC_Controller ($_SESSION['user_id'] should be passed to get_permissions()?).