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.
Only this array cannot provide the password, this characterizes security failure.
– novic
Nor in
controller
, nor inmodel
nor in theview
. Use ahelper
or ahook
to do this safely. Ahook
is safer as it will be called in all instances to make the validation.– ShutUpMagda
I’ll do a little research on Hooks, thank you.
– Felipe Miranda De Lima
Search in my answer, it’s faster :D
– ShutUpMagda
A suggestion: your question has much more to do with "authentication" than with "Sessions".
– ShutUpMagda