How To Restrict Controllers Functions Based On User Roles in Codeigniter?

To restrict logged in users from an entire controller is fairly simple in Codeigniter.

   function __construct(){
 parent::__construct();

  // to protect the controller to be accessed only by registered users
   if(!$this->session->userdata('logged_in')){
                redirect('login', 'refresh');
           }
    }

This works great. The user is not allowed access to functions or methods within the controller unless they are authenticated or registered users.

If you want to restrict controllers functions/methods based on user roles, you can do the following way:

     function __construct(){
 parent::__construct();
     
 // to protect the controller to be accessed only by registered users
  if(!$this->session->userdata('logged_in')){
                redirect('login', 'refresh');
         }

         //list of protected methods to access (for example only by admin )
  $protected_methods = array('METHOD1', 'METHOD2', 'METHOD3');

          /*$this->session->userdata('logged_in') is the array containing user information such as name, email, user role etc.*/

          if($this->session->userdata('logged_in')['user_role'] == 'role1'){
                        
              //grab the controller/method name and compare with protected methods array
              if(in_array($this->router->method, $protected_methods)){      
          redirect('login', 'refresh');    
       }
               else {
               redirect('home', 'refresh');
              }
           }

      }

How it works:
You should simply do the check in the constructor of the class that you're calling.
Firstly, check if the user is authenticated or not. If user is not an authenticated, system redirect the user to Login page.
And use $this->router->method (it gives you the real controller/method names, even if you reroute them) to see what method the user is trying to access.
Check that against an array of methods that required some specific roles to access the methods/functions.
In this example, role1 is the user that is not allowed to access protected methods 1,2 and 3.
If the user has role i.e. role1, it will redirect to login page otherwise redirect to home page.

Comments

Popular Posts