How to restrict access per user in Codeigniter

Asked

Viewed 1,081 times

0

I have a system that I need to restrict access to in some areas like User Administration, for example. I’m not sure how to get the user who is 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  }; ?>
  • 1

    You can use session to do this. If the user tries to access a page in an admin controller, in __contruct of that control will have the admin session check, if the session is not valid, redirect it to login.

  • Could you explain it to me in more detail? Mine looks like this: public Function __Construct() { Parent::__Construct(); if(!$this->Session->userdata('logged in')) { redirect('account/log in'); } } I don’t have much experience. I’m starting to learn.

  • That’s exactly it, except this session belongs to the user. Just create an equal for the admin, but remember to change the name of the admin session, example: admin_logged in, this will be to your liking.

  • It would be something like: $this->Session->userdata('adm_logado'); I want to hide the menu and block the access of those who are not Adm. .

  • How is the issue of login admin and user on the web page organized? Both use the same login page ?

  • Be careful when blocking somnte admin pages using ifs in the menu, if I have knowledge of the URL and type it in the browser, I will surely be able to access the resource. To prevent this, you need to create an admin session and verify that the session is active in the __Construct() of the controller being accessed.

Show 1 more comment

1 answer

3

Fabricio, you will need to configure the session variables, try this, 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, is by your choice. My library has the _check function which 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(); this allows me to load another library/model into it directly using only the command $CI->load->model('nome_model');

The safe library takes care of encrypting the user’s password and validating whether the password sent by the user matches the cryptographic. I will not post my encryption routine because it has features that I do not wish to expose.

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

If the user exists and the password is valid, arrow the variable "logado" as TRUE and user id in session variable "userID"

Then to check if there is a user in the session ( userid ) just 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 what you want on the system, or even redirect.

I will leave a link to a nice and complete tutorial from where I learned to make the system:

Codeigniter Tips - Login Screen with Bootstrap and CI

Hug...

Browser other questions tagged

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