How to create user validation with access levels in codeigniter?

Asked

Viewed 4,081 times

1

I have this model and control that checks and validates users registered in the table tb_users database. I need a script that checks whether the user is 0 or 1 in the column nv_nivel. If the user is equal to 0 it directs to redirect('usuario/home', 'refresh'); if it equals 1 directs to redirect('admin/home', 'refresh');

Follow the code below Model and Controller.

-> Model

   class Login_model extends CI_Model {

    function ValidaLogin() {
        $this->db->where('hl_email', $this->input->post('email'));
        $this->db->where('pw_password', md5($this->input->post('senha')));
        $query = $this->db->get('tb_user');
        if ($query->num_rows == 1) {
            return true;
        }
    }
}

-> controller

public function valida() {

        $this->load->model('login_model'); //Carrega o model
        $query = $this->login_model->ValidaLogin(); //Chama a função da Model que checa o usuário no BD

        if ($query) { //Se o Usuário e senha existir no mesmo registro...
            $data = array(
                'login' => $this->input->post('email'),
                'is_logged_in' => true
            );
            $this->session->set_userdata($data);
            redirect('usuario/home', 'refresh');
        } else { // incorreto username ou password
            $info['msg'] = "Informações incorretas";
            $this->load->view('header_html');
            $this->load->view('header_view');
            $this->load->view('login/login_view', $info);
            $this->load->view('footer_view');
            $this->load->view('footer_html');
        }
    }

2 answers

1


The first option you have is to create this "privilege system" on your arm. Like?

In your user table or in a related third, create a column called role or function and determine such a value.

Then breaking with if, we can distinguish the role of the user and determine something for him. For example:

if ($user->role == 1) {
    // é administrador
} else {
   // não é administrador
}

Or, if you want, you can use a ready-made library, such as the Ion Auth.

Unfortunately the IC does not have a role Provider native.

  • In case I need to put this information in the model and controller?

  • So at first you think that role It’s just another column in the database. You need to redeem it through your template and then you can work with it freely in the views or controllers. In other words, the model will rescue the user function and the view or controller will take advantage of such a feature.

0

What you need is a ACL - ACESS CONTROL LIST, there is a ready that is very good called Ion Auth.

Visit the website Ion Auth Docs, and see its documentation, download and configure in your project.

  • I hadn’t seen it, but @Guilhermeoderdenge also mentioned Ion Auth.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.