How to restrict user access in Codeigniter

0

I have a system that I need to restrict access in some areas such as User Administration, for example. I'm not sure how to get the user logged in. I know I need to restrict access to the file and hide the menu.

<?php 
        $this->load->model('Usuarios_model');   
            if($usuario) { ?>           

        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Usuários
                <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
                <li><a href="<?php echo base_url('usuario/visualizar_todos'); ?>">Visualizar</a></li>
                <li><a href="<?php echo base_url('usuario/cadastrar'); ?>">Cadastrar</a></li>            
            </ul>
        </li>

        <?php  }; ?>
    
asked by anonymous 26.04.2016 / 20:10

1 answer

3

Fabrício, you will need to configure the session variables, so try to create a LOGIN controller.

public function entrar(){
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        $this->form_validation->set_rules('senha', 'Senha', 'required|trim');
            if ($this->form_validation->run() == TRUE){

                $formData = $this->input->post();

                $this->load->library('usuario');
                $user = new Usuario;


                if( $user->_check($formData['email'], $formData['senha']) == FALSE ) {
                    $this->session->set_flashdata("msg",'<p>Usuário / Senha não conferem</p>');
                } else {
                    $this->session->set_userdata("logado", TRUE);
                    $this->session->set_userdata("userID", $user->getId());
                    redirect("dashboard");
                }
            }

        $this->load->view("login/v_header", array('pageTitle'=>'Entrar no Sistema | miPague', 'title'=>'Entrar no sistema'));
        $this->load->view("login/v_loginForm");
        $this->load->view("login/v_footer");
    }

In my case I created a library to take care of the user, but it can be a model too, it is your choice. My library has the _check function that has the following structure:

 public function _check($email, $senha){
        $CI =& get_instance();
        $CI->load->model(array('m_login','m_clientes'));
        $CI->load->library(array('safe'));
        $user_mail = $CI->m_clientes->buscar_email($email);
        if($user_mail){
            $user_pass = $CI->m_login->check_user($user_mail->id);
            if($user_pass){
                $q = $CI->safe->valid_crypt($senha, $user_pass->senha);

                if($q == FALSE){
                    return FALSE;
                } else {
                    $this->setId($user_mail->id);
                    return TRUE;
                }
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

Note that this function loads a command called $CI =& get_instance(); so it allows me to load another library / model into it directly using only the command $CI->load->model('nome_model');

The library safe, is responsible for encrypting the user's password and validate if the password sent by the user configures with the cryptografada. I will not post my encryption routine because it has particularities that I do not want to expose.

Anyway, returning to the Login Controller, there is a if shortly after the command: $user = new Usuário; This if if, if the password and the user do not exist, it generates an error in the session using $this->session->set_flashdata("var","mensagem aqui dentro")

If the user and password are valid, set the "logado" variable to TRUE and the user id in the session variable "userID"

Then to check if a userID exists in the session, simply use one of the following commands:

$this->session->userdata("userID");
// Ou usar
$_SESSION['userID'];

Now just use basic PHP commands like empty or exists to show / hide whatever you want on the system, or even redirect.

I'll link to a cool and complete tutorial from where I learned how to make the system:

Codeigniter Tips - Login Screen with Bootstrap and CI

Embrace ...

    
27.04.2016 / 07:17