Controlling User Privileges in Codeigniter

2019-06-03 06:03发布

问题:

Suppose I am building a web application using Codeigniter. I have two levels of user- 1. Admin and 2. Manager. I want my admin to be able to ADD,EDIT, DELETE, so in my view file I have the following:

<a href="somelink">ADD</a>
<a href="somelink">EDIT</a>
<a href="somelink">DELETE</a>

But in some specific pages, I don't want my Manager to be able to delete or edit any record, he will be allowed to add data only . Now my question is since I have multiple types of user and user- privileges do I have to create a new controller and a view file for my manager(and for each other user levels) or there are some better ways to handle this in the same controller and view file that I will be using for the admin ?

At present I am creating separate controller, model and view files for my ADMIN and MANAGER which is very painful. So I thought there got to be a better way to do this.

Would you please give me some of your expert advice on how to handle this?

To figure out what type of user is logged in I am using the following code in my controllers:

 parent::__construct();
    if ( !($this->session->userdata('user_type')== 'flex_admin'))
    { 
        redirect('login');
    }

Thanks in Advance :)

回答1:

You most definitely do not need to create separate controllers and views.

You can just store the users privilege type (1 or 2) in a session and then do a check in each of your controllers or views to check the privileges for the user.

an example of a nav in a view file

<div id="nav">
  <ul>
    <li>Home</li>
    <li>Logout</li>
    <?php if($this->session->userdata('privilege') == 1) : ?>
      <li>Delete</li>
    <?php endif; ?>
  </ul>
</div>

You can perform the same kind of check in your controller to make sure that the users access is appropriate to perform some function.