简体   繁体   中英

How to implement an access privilege and user checking in every Controller using Codeigniter?

I am using Ion_Auth library. And I found out that it's easy to implement authentication here. But my question is how can I use this to perform a checking in every controller?

In my admin part I have multiple users but every users is assigned to a specific group. Means there are no user will be assign to a multiple group. When I checked the ion_auth the user can be belong to multiple groups. In that part I just get the value from the index 0 and make it as the primary group type.

public function __construct() {

    parent::__construct();

    $this->load->library('my_auth');

    $user_groups = $this->ion_auth->get_users_groups()->result_array();
    $get_user_group = $user_groups[0]['id']; //hard coded!!! still finding a good way to prevent this

    if (!$this->ion_auth->logged_in()) {
        redirect('auth/login');
    }

    if (!$this->ion_auth->is_admin()) {
        redirect('error/error_privilege');
    }

    $this->data['options'] = array(
        'active_menu'   =>  'dashboard'
    );

}

And the other thing I want is how can I do this without including all of these codes in every controller I want to have an authentication?

What I want is perform an authentication

  • first to validate if user is login or not
  • next is to validate what are they group type

After getting the group type how can I restrict the view of the page? My idea is after login and if the user is valid I will call their group type and store it in a session. And I will include a flag variable with an id of the user group(hard coded)in a specific view and from that I can validate thew viewing of the page.

Just like this: Here I have a navigation menu

Inbound List Outbound List Inbound List Outbound List

And for the specific controller

 //inbound controller public function __construct() { parent::__construct(); $group_type = 1; if(!$this->session->userdata('group_type') == 1) { //warn user or redirect } } 

Can you suggest me a better way to implement this type of checking?

Your controllers should all be extending a default controller that contains all logic applied before any rendering or data manipulation occurs.

class PageController extends DefaultController {
    /*
     * logic for pages!
     */
}

Where DefaultController actually extends the base Controller

class DefaultController extends Controller {
    /**
     * And also checks the authorization as well
     */
     public function __construct(){
         //logic to check roles etc.

         //redirect and flash session if failed, otherwise just return.
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM