Control of séssions and authentication in PHP with Codeigniter

Asked

Viewed 2,169 times

3

Good morning guys, I’m new to programming with PHP and I have a question: I have already developed the login system and it is working correctly, now I would like to control the access to the other pages of the application, ie the user only access internal pages if you have logged in.

I also know that for that I need to use a if (isset(....)) but my question is: where do I put this if (isset(....))?

How I’m using the Framework Codeigniter I must put that clause in Controller, in Model or in the View?

Also, this is my structure after logging in:

inserir a descrição da imagem aqui

So, man isset would look that way:

if(isset(usuario_logado[username]))
{
//usuário não logado direciona para a pagina de login
}

$usuario_logado is the array which receives user data after authentication with the database.

  • Only this array cannot provide the password, this characterizes security failure.

  • Nor in controller, nor in model nor in the view. Use a helper or a hook to do this safely. A hook is safer as it will be called in all instances to make the validation.

  • I’ll do a little research on Hooks, thank you.

  • Search in my answer, it’s faster :D

  • A suggestion: your question has much more to do with "authentication" than with "Sessions".

3 answers

3


Enable the HOOKS in your application. This mechanism will automatically check and validate the logon without having to mark or do includes.

Use SESSIONS. I know the native session library of Codeigniter it is not a wonder, but it will help you in a few moments, so it is better to leave activated (I like to autoload). And even if you don’t want to use the native library, use $_SESSION to store login credentials.

Never, not at all, vc must save the user password in the session or in cookies or in any other memory location. Not even the HASH of password.

After enabling the HOOKS and the SESSION, go to application/config/Hooks.php and insert this here:

$hook['post_controller_constructor'][] = [
    'function' => 'logged',
    'filename' => 'logged.php',
    'filepath' => 'hooks'
];

It’s simple: to validate the logon, the HOOK needs to know which is the controller and the method called, ie the Codeigniter have to pass this information to him, and this is only possible after the controllers are already loaded, so post_controller_constructor:

post_controller_constructor Called immediately after your controller is instantiated, but prior to any method calls happening.

Create application/Hooks/logged.php and put this here:

function logged() {
    $ci = & get_instance();//Instância do CodeIgniter
    $method = $ci->router->fetch_class().'/'.$ci->router->fetch_method();//Método atual
    $protegidos = ['sistema/clientes'];//Métodos protegidos
    $usuario_logado = $ci->session->userdata('usuario_logado');//Array gerado pelo seu algotitmo de "login" e gravado na SESSION
    if (in_array($method, $protegidos)) {//Verificando se o método é protegido
        if (!$usuario_logado[username]) {//Verificando se o usuário está logado
            $ci->session->set_flashdata('alert', 'Autentique-se, por favor!');//Aqui vc tb pode criar um aviso pro usuário saber o motivo do comportamento da aplicação
            $url = base_url('controller/metodo_de_logon');
            redirect($url);//usuário não logado direciona para a pagina de login
        }
    }
}

There’s so much more that can be done to make this HOOK safer (confirm a hash in the database, confirm the life time of the session, etc), but the basic question is this.

  • In fact, the life of the session is controlled by Session Library. That’s why it’s nice to have it activated ;)

  • I did well as you said @Shutupmagda, if I am already logged in and enable the Hooks, it works perfect, but if I log out it already returns the error: Message: Undefined index: usuario_logged Filename: Hooks/logged.php Line Number: 7

  • When you are not logged in, it does not find the $_SESSION['logged in user'] for obvious reasons. The solution is to check the session before assigning: if($_SESSION['usuario_logado']){$usuario_logado = $_SESSION['usuario_logado'];} else{$usuario_logado = NULL;}. I edited the answer ;)

  • Yes I imagined that it would be something like this, but this is a little strange because it is entering the if and Else correctly (tested using die and simulating the two situations logged in/not logged in) but still it returns the same error as before, I am new here in the OS also not allowed to disclose the project via git

  • Variable name. It depends on how you are naming this SESSION. Do you have github? What is it? It is even easier if you disclose.

  • https://github.com/fmlima4/sistema

  • Well, I looked at the github, I didn’t see anything. You can try using $ci->session->userdata('usuario_logado') instead of $_SESSION['usuario_logado'], or if(isset($_SESSION['usuario_logado'])){... but I think it’s the same...

  • Ah, in buscaPorEmailSenha() of Usuarios_model you are returning row_array(), but I think it should be result_array().

Show 3 more comments

0

To perform the check if the session exists the best way would be:

if($this->session->has_userdata('usuario_logado') == true){
     echo "Logado.";
}

-1

You can do:

if(isset($this->session->userdata('usuario_logado'))){
     echo "Logado.";
}
  • Thanks for the help, but when using your method I get the following error Cannot use isset() on the result of an Expression (you can use "null !== Expression" Instead)

Browser other questions tagged

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