How to end session automatically

1

What friends are I working on a project and I have this to close the session, but I would like to implement JQuery Confirm the problem is that I do not know how to do it, I have this code, which does the following with a sweet alert:

var timeout; 
document.onmousemove = function(){ 
    clearTimeout(timeout); 
    timeout = setTimeout(function(){
        swal({
          title: "Cierre de Sesion Automatica",
          text: "Si deseas salir haz clic en Cerrar Sesion o en Cancel para continuar trabajando",
          type: "warning",
          showCancelButton: true,
          confirmButtonClass: "btn-danger",
          confirmButtonText: "Cerrar Sesion",
          closeOnConfirm: false,
          showLoaderOnConfirm: true,
        },
        function(isConfirm){
            if (isConfirm) {
                $.ajax({
                    url: base_url + "auth/logout",
                    type: "POST",
                    success:function(resp){
                        window.location.href= base_url;
                    }

                });
            }else{
                window.location.href = base_url + "movimientos/ordenes";
            }

        });
    }, 30000); 
} 

Now there is a code that I provided @Walter Cordova but I would need you to help me implement it in my code, since I need the countdown anyway, and after that destroy the session.

This is the code of @Walter Cordova which works very well, I leave it in a box of JS.

$( document ).ready(function() {
    $.confirm({
       title: 'Alerta!',
        content: 'La sesión esta por expirar.',
        autoClose: 'logoutUser|10000',
        buttons: {
            logoutUser: {
                text: 'cerrar sesión',
                action: function () {
                    $.alert('La sesión ha expirado');
                    //tu codigo AJAX                    
                }
            },
            cancelar: function () {
                $.alert('cancelado');
            }
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.js"></script>

This is my Session controller, and below is the logout function that destroys the session:

    <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->model("Usuarios_model");
    }
    public function index()
    {
        if ($this->session->userdata("login")) {
            redirect(base_url()."dashboard");
        }
        else{
            $this->load->view("admin/login");
        }


    }

    public function login(){
        $username = $this->input->post("username");
        $password = $this->input->post("password");
        $res = $this->Usuarios_model->login($username, sha1($password));

        if (!$res) {
            /*$this->session->set_flashdata("error","El usuario y/o contraseña son incorrectos");*/
            //redirect(base_url());
            echo "0";
        }
        else{
            $data  = array(
                'id' => $res->id, 
                'nombre' => $res->nombres,
                'rol' => $res->rol_id,
                'login' => TRUE
            );
            $this->session->set_userdata($data);
            //redirect(base_url()."dashboard");
            echo "1";
        }
    }

    public function logout(){
        $this->session->sess_destroy();
        redirect(base_url());
    }
}
    
asked by WilsonicX 05.09.2018 в 23:15
source

3 answers

1

I bring the answer to this debate, I think it complicates me a bit, but here I leave the code with the solution, what it does is that every time the mouse is moved the counter is reset all this including clearTimeout, for the demonstration Place yourself in the snippet, and move the mouse, then leave it static, and in 3 seconds the message will appear.

var base_url = 'fake_url';
var timeout;
document.onmousemove = function(){ 
    clearTimeout(timeout); 
    contadorSesion(); //aqui cargamos la funcion de inactividad
} 

function contadorSesion() {
   timeout = setTimeout(function () {
        $.confirm({
            title: 'Alerta de Inactividad!',
            content: 'La sesión esta a punto de expirar.',
            autoClose: 'expirar|10000',//cuanto tiempo necesitamos para cerrar la sess automaticamente
            type: 'red',
            icon: 'fa fa-spinner fa-spin',
            buttons: {
                expirar: {
                    text: 'Cerrar Sesión',
                    btnClass: 'btn-red',
                    action: function () {
                        salir();
                    }
                },
                permanecer: function () {
                    contadorSesion(); //reinicia el conteo
                    $.alert('La Sesión ha sido reiniciada!'); //mensaje
                    window.location.href = base_url + "dashboard";
                }
            }
        });
    }, 3000);//3 segundos para no demorar tanto 
}

function salir() {
    window.location.href = base_url + "auth/logout"; //esta función te saca
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.js"></script>
    
answered by 06.09.2018 / 18:00
source
2

Well, given your question I would decide to use only confirm-js or SweetAlert , the problem that you are combining two libraries that do exactly the same, so you would not see the advantage of combining them.

In the example I give you, the methods in php will not work, but depending on the code of your question, when you get to that method logout() the session dies effectively, just put the path of that controller and that method well.

In your role:

var timeout;
var base_url = 'fake_url';

document.onmouseout = function(){ 
  contadorSesion(); //aqui cargamos la funcion de inactividad
} 

function contadorSesion() {
    setTimeout(function () {
        $.confirm({
            title: 'Alerta de Inactividad!',
            content: 'La Sesión esta a punto de expirar.',
            autoClose: 'expirar|3000',
            type: 'red',
            buttons: {
                expirar: {
                    text: 'Expirar',
                    btnClass: 'btn-red',
                    action: function () {
                        salir();
                    }
                },
                permanecer: function () {
                    contadorSesion(); //reinicia el conteo
                    $.alert('Sesión ha sido reiniciada!'); //mensaje
                }
            }
        });
    }, 10000);
}

function salir() {
    window.location.href = base_url + "/logout"; //esta función te saca
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.js"></script>
    
answered by 06.09.2018 в 00:06
0

It's not that difficult, it's just copying the old scheme to the new one. Here it will not pull because there is no back and reduced the time to 3s. We hope and you will see how the message appears.

Greetings

var timeout;
var base_url = 'fake_url';
document.onmousemove = function() {
  clearTimeout(timeout);
  timeout = setTimeout(function() {
    $.confirm({
      title: 'Cierre de Sesion Automatica',
      content: 'Si deseas salir haz clic en Cerrar Sesion o en Cancel para continuar trabajando',
      buttons: {
        confirm: function() {
          $.ajax({
            url: base_url + "auth/logout",
            type: "POST",
            success: function(resp) {
              window.location.href = base_url;
            }
          });
        },
        cancel: function() {
          window.location.href = base_url + "movimientos/ordenes";
        },
      }
    });
  }, 3000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.js"></script>
    
answered by 05.09.2018 в 23:34