Enable the HOOKS in your application. This mechanism will automatically check and validate the login without marking or doing includes .
Use SESSIONS . I know the CodeIgniter native session library is not a marvel, but it will help you in a few moments, so it's best to leave it turned on (I like autoload ). And even if you do not want to use the native library, use $ _SESSION to store the logon credentials.
Never, under any circumstances, you should save the user's password in session or in cookies or elsewhere in memory. Not even the HASH of the password.
After enabling HOOKS and SESSION , go to application / config / hooks.php and insert it here:
$hook['post_controller_constructor'][] = [
'function' => 'logged',
'filename' => 'logged.php',
'filepath' => 'hooks'
];
It's simple: to validate the login, HOOK needs to know which driver and method is called, ie CodeIgniter has to pass this information on to him , and this is only possible after the drivers 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 it 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 is a lot more that can be done to make this HOOK more secure (confirm a hash in the database, confirm session lifetime, etc.) , but the basics of your doubt are that.