Reputation: 1
what is best way to manage multi user permissions and privileges in codeIgniter framework?
I tried to manage it and its working well. But I have to call one function in every controller. that is I am not want to. the function bellow that get controller name and data through session variable.
function allow_user_permission(){
$ci = & get_instance();
$arr = $ci->session->userdata("userdata")['persissions'];
$array = json_decode($arr);
$controller = $ci->router->fetch_class();
$per = (object) array("label"=>$controller,"val"=>true);
$permission = array($per);
if(isset($array)){
$res = in_array($permission, $array, true);
if ($res ==FALSE)
{
redirect(site_url("dashboard"));
}
}
}
Upvotes: 0
Views: 1214
Reputation: 634
All you need is creating a parent controller and then make your controllers inherit from it. The parent controller is instanciated each time you access any controller. And its constructor runs the security check.
1- Create file application/core/MY_Controller.php (PS: I shorthanded your code)
<?php
class Parent_controller extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->allow_user_permission();
}
public function allow_user_permission()
{
$arr = json_decode($this->session->userdata['persissions']);
$permission = array("label" = >$this->router->fetch_class(), "val" => true);
if (!empty($array) && !in_array($permission, $array, true))
redirect(site_url("dashboard"));
}
}
2- In your controllers, you just need to update the class from which your controller is inheriting and use Parent_controller
. example:
class Users extends Parent_controller {
}
Upvotes: 1