Dynamic Menu and Role Permission in Codeigniter

Dynamic menu and role permission in codeigniter

database tables example :

CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL,
`username` varchar(100) NOT NULL,
`password` text NOT NULL,
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

INSERT INTO `users` (`user_id`, `first_name`, `last_name`, `username`, `password`, `create_at`) VALUES
(1, 'ali', 'qorbani', 'aliqorbani', '63bed66f3d9dcd13440490d90738f816', '2018-07-28 08:34:01'),
(2, 'mohammad', 'ahmadi', 'mohammad', '316946a88ad51d75465c4c0b1e4a066a', '2018-07-28 08:34:01');


CREATE TABLE IF NOT EXISTS `user_groups` (
`group_id` int(11) NOT NULL AUTO_INCREMENT,
`group_name` varchar(100) NOT NULL,
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`group_id`),
KEY `group_id` (`group_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

INSERT INTO `user_groups` (`group_id`, `group_name`, `create_at`) VALUES
(1, 'superadmin', '2018-07-28 08:35:56'),
(2, 'admin', '2018-07-28 08:35:56'),
(3, 'moderator', '2018-07-28 08:36:12'),
(4, 'customer', '2018-07-28 08:36:12');

CREATE TABLE IF NOT EXISTS `user_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`),
KEY `user_id` (`user_id`),
KEY `group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `user_roles`
ADD CONSTRAINT `user_roles_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `user_roles_ibfk_2` FOREIGN KEY (`group_id`) REFERENCES `user_groups` (`group_id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;

codes for your model will be like this.

//User_model

public function add($data){
$this->db->insert('users',$data);
return true;
}
public function update($data,$id){
$this->db->where('user_id',$id);
$this->db->update('users',$data);
return true;
}

public function add_user_roles($user_id,$roles = array()){
$this->db->where('user_id',$user_id);
$this->db->delete('user_roles');
foreach ($roles as $role){
$this->db->insert('user_roles',['user_id'=>$user_id,'group_id'=>$role]);
}
return true;
}

and the example for your controller Edit method will be like this snippet:

//Users controller
public function edit($user_id){
if($this->form_validation->run() == FALSE) {
$data_view['user'] = $this->User_model->get_user($user_id);
$this->load->view('user_edit',$data_view);
}else{
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$user_roles = $this->input->post('roles');
$data_user_update = array(
'first_name' => $first_name,
'last_name' => $last_name,
'username' => $username,
'password' => $password
);
$this->User_model->add_user_roles$user_id,$user_roles);
$this->User_model->update($data_user_update,$user_id);
$this->session->set_flashdata('success','user updated correctly');
redirect('users/edit/'.$user_id);
}
}

Displays a menu based on permissions in CodeIgniter

A simple way is provide a profile id to differentiate the users. For example for Admin 1 and for Operator user 2. When you are displaying menu in the view file put some conditions on your menu display using profile id.

Note save profile id in session data with user data.

Codeigniter Menu Based on Access Level

Each of your user accounts should have a set of roles, i.e. Dashboard, Sales, Payments, Products, Product Add/Edit, Product Delete, Reports, etc. (you can use Ion Auth's groups as roles). Then you create a view which will display the menu and you will pass the logged user roles to that view. Then you go through all roles and compare them to the user roles. If the user has a role to see a specific page then you add a link to that page in the menu.

That's it :-)
Hope I helped.

Laravel menu based on role?

As mentioned in the comments,it sounds like what you want is the ability to conditionally display content based on whether a user has certain permissions.

There's a number of implementations of this. Essentially what they all do is store permissions that can be granted to users, and optionally store roles that allow permissions to be assigned to a role and then users can be given that role, automatically granting them the permissions associated with that role.

I've found spatie/laravel-permission which appears to be quite good. Then, if you pass your user model into the view, you can do something like this:

@if ($user->can('edit-posts'))
<a>Edit post</a>
@endif

That should be flexible enough that it can be reused for different permissions too. If that doesn't do the trick, then it's not hard to roll your own permission system using Laravel's authorization system and you should be able to use the can() method in the same way.

Codeigniter managing user roles

Use the Permission Class.

Watch this video to see this in action.

what is the best practice for role based login system in Codeigniter

I am using a single Controller Login system for all user roles. I have a table of user roles and I have role id in users table. Then I have controller names matching those roles. When user login, I check for role and redirect the user to that controller after verification. Following is the index function of my Login Controller.

public function index()
{
if(!$this->isLoggedIn())
{
$data['title']='Title You want to set on Page';
if($_POST)
{
$config=array(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email',
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required',
),
);
$this->form_validation->set_rules($config);
if($this->form_validation->run()==false)
{
$data['errors']=validation_errors();
$this->load->view('static/head', $data);
$this->load->view('admin/login');
}
else
{
$user=$this->admin_model->checkUser($_POST);
if(!empty($user))
{
if($user['role']==1)
{
$user['type']='admin';
}
elseif($user['role']==2)
{
$user['type']='team';
}
elseif($user['role']==3)
{
$user['type']='client';
}
elseif($user['role']==4)
{
$user['type']='manager';
}
$this->session->set_userdata($user);
redirect(base_url().$user['type']);
}
else
{
$data['errors']='The credentials you have provided are incorrect or your account has not been approved yet.';
$this->load->view('static/head', $data);
$this->load->view('admin/login');
}
}
}
else
{
$this->load->view('static/head', $data);
$this->load->view('admin/login');
}
}
else
{
redirect(base_url().$this->session->userdata['type']);
}

}

Its working perfectly for me. Furthermore in each Controller I have functions to check if the user is logged in for this role like this

public function isLoggedIn()
{
if(!empty($this->session->userdata['id'])&& $this->session->userdata['type']=='team')
{
return true;
}
else
{
return false;
}
}

And I render my index function of that controller. E.g Following is the team controller index function

public function index()
{
if($this->isLoggedIn())
{
$data['menu']=$this->team_model->getMenuItems();
$data['task_logs']=$this->admin_model->getAllLogs();

$data['title']='Title';
$this->load->view('static/head',$data);
$this->load->view('static/header');
$this->load->view('static/sidebar');
$this->load->view('team/dashboard');
$this->load->view('static/footer');
}
else
{
redirect(base_url());
}

}


Related Topics



Leave a reply



Submit