Reputation: 11
I would like to know how to proceed for the application to log out when the user is idle for a few minutes. I researched a few things, but found nothing that could help.
I am using codeigniter 3.
Thank you.
Upvotes: 0
Views: 1947
Reputation: 687
If you want to make sure that, after an interval of inactivity, the user will be sent to login page, you could use an ajax to call a logged
function in your controller that will assess whether the user's session is still valid.
setInterval(function(){
$.getJSON('url/to/controller/logged', function(response) {
if (typeof response.redirect != 'undefined') {
window.location.href = response.redirect;
}
});
}, <INTERVAL-IN-MILLISECONDS>);
To make that uniform, you could extend the original CI_Controller
class to a class named MY_Controller
, under application/core/MY_Controller.php
, that will be used to extend every credential protected controller of yours.
Every time any function in your controller is called, the not_logged_in()
function will be called first. If the session has expired, it will handle redirection according to the type of call. Otherwise it will work normally.
class MY_Controller extends CI_Controller{
public function __construct(){
parent::__construct();
$this->not_logged_in();
}
private function not_logged_in(){
$is_logged_in = $this->session->userdata('is_logged_in');
// The cookie was not found or has expired
if(!isset($is_logged_in) || $is_logged_in != true)
{
/* AJAX request check
* If it is not a AJAX request then redirects to login page
*/
if( ! $this->input->is_ajax_request()) {
redirect('login');
} else{ // send and JSON message to redirect
echo json_encode(array(
'status' => FALSE,
'message' => 'Your session expired. Please, login.',
'redirect' => base_url('login')
));
exit();
}
}
}
public function logged()
{
// Request coming from AJAX call
if($this->input->is_ajax_request()) {
echo json_encode(array('status' => TRUE, 'message' => 'You are still logged in.'));
}
else {
show_404();
}
}
}
The only thing you would need to change in your login class would be adding the is_logged_in
field in your cookie.
class Login extends CI_Controller{
// function called to validate credentials
public function validate()
{
// ... code to validate login
// If the user is validated
$data = array(
'is_logged_in' => true,
... // more user data, if you will
);
$this->session->set_userdata($data);
}
}
Upvotes: 1