Log out after 5 minutes of inactivity

Asked

Viewed 628 times

0

Hello, I am lost in this logic, I am using codeigniter, and I am trying to expire the session after 5 minutes of inactive (in case the user does not access the page for up to 5 minutes), I tidied up the code, and created a logic with ajax, as soon as the user logs in I save the team to the database as follows:

$dataSessao['ultima_activity'] = time()+(5 * 60);

in my database table session save the time in the ultima_activity field, and check with ajax of 1 in 1 minute by consulting the controller Area_user the time of the last activity of Session:

$lastVisitTime = $_SESSION['last_visited'];

and compare with the team recorded in the bank ultima_activity, and if it is less than or equal to the last team recorded in the bank I give an update on the bank increasing the team, until then beauty, I made the code it is updating the team in the bank of 1 in 1 minute, and it doesn’t work at all, even if I leave the window inactive for more than 5 minutes it doesn’t run the expiration, I don’t know what’s going on if you can help me thank you.

My code is like this, this is my controller Area_usuario:

 //verificar inatividade de sessão
      public function verificarInatividade()
      {
          $vetor = $_SESSION['usuarioLogado'];
          $email = $vetor->email; 
           
           //pego a ultima atividade que eu gravei na session;     
           $lastVisitTime  = $_SESSION['last_visited'];        
             
            //verifico o time gravado no tempo  
            $verificar =  $this->login_cliente_model->checarTempoSession($email);
            $cincominutos = $verificar->ultima_atividade;
          
          //veririco se o tempo inativo é menor ou igual ao gravado no banco
          if ($lastVisitTime <= $cincominutos) {  
                  
                  //se for ele faz o update pra mudar a ultima atividade do banco
                  $ultima_atividade = time()+(5 * 60);
                  $this->login_cliente_model->updateSession($ultima_atividade, $email);
                  
                  $retorno['erro'] = 0;
                  $retorno['msg']  = 'Ativo';
                  $retorno['verificarSessao']  =  $lastVisitTime;

                  header('Content-Type: application/json');
                  echo json_encode($retorno);
                  exit;

              } else {

                  //se não ele exclui a sessão aberta no banco e vai pra função logout 
                 $checharSessi = $this->login_cliente_model->checarSession($email);
              
                if($checharSessi  != FALSE){
                 
                   $this->login_cliente_model->deletarSession($email); 
                }
                
                  $retorno['erro'] = 60;
                  $retorno['msg']  = 'Inativo';
                  $retorno['verificarSessao']  = $lastVisitTime;

                  header('Content-Type: application/json');
                  echo json_encode($retorno);
                  exit;
          }

      }
      //verificar tempo de sessao
      public function expiraSessao()
      {
           if ($this->session->userdata('usuarioLogado')) {
           
                  $retorno['erro'] = 0;
                  $retorno['msg']  = 'Sessão expirou, acesse novamente.';
                  $retorno['verificarSessao']  =  '0';

                  header('Content-Type: application/json');
                  echo json_encode($retorno);
                  exit;
             
           }
             

      }

Here my ajax doing the check:

//Verificar inatividade na session
        var verificarInatividade= function (tempoParaChecarNovamenteEmSegundos) {
        $.ajax({
            type:"GET",
            url:"localhost/area_usuario/verificarInatividade", 
            dataType: "json",
            success: function (resposta){
            
            if (resposta.erro === 0) {  
                
                   var url = resposta.verificarUsuario;
                   console.log(url);
                    setTimeout(function() { verificarInatividade(tempoParaChecarNovamenteEmSegundos); }, tempoParaChecarNovamenteEmSegundos * 60000);
            } else {
                   
                      expiraSessao();
                     console.log(url);
                    setTimeout(function() { verificarInatividade(tempoParaChecarNovamenteEmSegundos); }, tempoParaChecarNovamenteEmSegundos * 60000);
            }  

            },
            error:function(){
                console.log(resposta);
            }
        });
        }

   //expira sessão    
        var expiraSessao= function() {
            $.ajax({
                type:"GET",
                url:"localhost/area_usuario/expiraSessao", 
                dataType: "json",
                success: function (resposta){
                   
                    window.location.replace("localhost/login_usuario/sessao_expirada");
                   
                },
                error:function(){
                    console.log(resposta);
                }
            });
        }

Now I log in and even if I leave the window inactive for more than 5 minutes, it keeps updating the team in the bank and it doesn’t expire the session, and it should expire if the session is inactive for 5 minutes, I don’t know why he’s acting like this, I’ve reviewed this code over a thousand times, if you can help me by giving me a light, I’m grateful.

1 answer

1


The best solution is to implement your own session timeout. Use a simple date and time record that indicates the time of the last activity (i.e., request) and update it with each request:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minutes ago
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

Updating session data with each request also changes the modification date of the session file, so that the session is not removed by the trash collector prematurely.

You can also use an additional date/time stamp to re-generate the session ID periodically to avoid attacks on sessions like session fixing :

if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
    // session started more than 30 minutes ago
    session_regenerate_id(true);    // change session ID for the current session and invalidate old session ID
    $_SESSION['CREATED'] = time();  // update creation time
  • thank you, I will give a studied in your code and try to implement here

  • but these two checks I do separately? , because doing this first check and this second so that the session is not removed by the garbage collector, is doing to dislodge anyway

Browser other questions tagged

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