2016-05-06 4 views
0

Я установил gem 'auto-session-timeout', чтобы автоматически отключать пользователей от неактивных сеансов. Я хочу, чтобы дать пользователю 2 минутное предупреждение перед временем сессии изПроблема кэширования Javascript с рельсами

Я добавил следующее к моему application.html.erb

<%= javascript_tag do %> 
     var d = new Date('<%= session[:auto_session_expires_at] %>'); 
     setInterval(function(){ 
        var d = new Date('<%= session[:auto_session_expires_at] %>'); 
        var e = new Date(); 
        var f = e.getTime(); 
        var diff = d - f ; 
        alert(d + " | " + diff); 

     if (diff < 120000) { 
     // alert("Your session is about to timeout in less than 2 minutes " + diff); 
         } 
      }, 10000); 

    <% end %> 

Моя цель состоит в том, чтобы использовать if (diff < 120000) заявление, чтобы показать предупреждение 2 минут от выхода из системы.

Приведенный выше код получает переменную сеанса, заданную с помощью автоматического сеанса, и затем вычитает ее с текущей даты (из getTime() js и создает diff.

Это ПОЛНОСТЬЮ работает нормально. При взаимодействии с приложением счетчик сбрасывается. Однако похоже, что старый счетчик продолжает работать.

Другими словами, если я посмотрю на результаты оператора предупреждения, которые не были отмечены, я могу увидеть время, которое находится в переменной сеанса и рассчитанном diff. Ниже я показываю только минуты и сеансы, которые показаны для простоты.

25:22 168134 - первое окно предупреждения - показывает содержимое сеанса var, а также показывает вычисленные интервалы разности или миллисекунды.

25:22 143249 - второе поле оповещения - все как ожидается.

25:22 120816 - Значит, он правильно отсчитывать с правильной информацией от сессии переменной

Теперь, если я взаимодействовать с приложением, тайм-аут автоматического сеанса сбрасывает переменную auto_session_expires_at сеанса.

26:13 158345 - ОК - именно то, чего я ожидал бы. Javascript подбирает новую переменную сеанса и пересказывает diff.

25:22 86327 - Но теперь я вижу предыдущий переменный сеанс и дифф калькулятор все еще работают

Цикл выше будет повторять между «хорошим» и «старой» переменным сеансом и разн. Я думаю, что происходит какое-то кеширование, но я не могу его точно определить.

это поведение повторяемые для меня

==================================== =================== HTML с момента, когда я первый открыть приложение

/<![CDATA[ 


     var d = new Date('2016-05-06 15:58:19 -0400'); 

     setInterval(function(){ 

        var d = new Date('2016-05-06 15:58:19 -0400'); 
        var e = new Date(); 
        var f = e.getTime(); 
        var diff = d - f ; 
        alert(d + " | " + diff); 


     if (diff < 120000) { 
     // alert("Your session is about to timeout in less than 2 minutes " + diff); 
         } 
      }, 10000); 




//]]> 

HTML с после того, как я нажимаю на пункт нав. Вы можете видеть, что дата, снятая с изменения переменной сеанса, изменяется

/<![CDATA[ 


     var d = new Date('2016-05-06 15:58:48 -0400'); 

     setInterval(function(){ 

        var d = new Date('2016-05-06 15:58:48 -0400'); 
        var e = new Date(); 
        var f = e.getTime(); 
        var diff = d - f ; 
        alert(d + " | " + diff); 


     if (diff < 120000) { 
     // alert("Your session is about to timeout in less than 2 minutes " + diff); 
         } 
      }, 10000); 




//]]> 
</script> 
+1

Когда вы говорите, что сеанс сбрасывается после взаимодействия с сайтом, вы перенаправляетесь? Я спрашиваю об этом, потому что было бы полезно увидеть сгенерированный HTML-код. – SanF

+0

Извините, я, возможно, был немного нечетким. То, что я делал, это выбрать что-то из навигационного меню, так как это загружает новую страницу. –

+1

Хорошо, можете ли вы опубликовать сгенерированный HTML-код для проверки функции javascript? – SanF

ответ

0

@SanF был прав про clearInterval. Вот пересмотренный код. Это сильно отличается от того, с чего я начал.

<% if current_user %> 

    <%= javascript_tag do %> 


     // -------------------------------------------------------------------------------------------------------- 
     // This script enhances the functionality of the auto_session_timeout gem 
     // 
     // this script will give the user a warning at a specified time before they will be automatically logged out 
     // from their session. 
     // 
     // The polling interval is set in var myVar = setInterval(myTimer, 10000); where 10000 = 10 seconds 
     // That should be set to about 1000 so that the login screen appears as soon as possible when 
     // the user comes to a screen from a timed out session. 
     // 
     // The time before logout for the warning is set in if (diff < 120000) 120000 = 120 seconds 
     // 
     // The timeout itself is contrlled by the auto_session_timeout gem and the setting in the application 
     // controller ' auto_session_timeout 4.minutes' . Make sure that the time set there is LONGER than the 
     // time set below for the warning 
     // --------------------------------------------------------------------------------------------------------- 

       clearTimer();              // clear the warning timer if it has been set previously 
       var diff = 0;              // Initialize the difference calculation 
       var b = new Date(); 
       var f = new Date(); 
       var e = new Date(); 
       var current_time = e.getTime();          // get the current time from the system 
       expires = new Date('<%= session[:auto_session_expires_at] %>');  // get the expiration time set by auto session expires. 
       var myVar = setInterval(myTimer, 5000);        // this calls myTimer and runs it at intervals specified. 1000 = 1 second 


     // ------------------------------------ myTimer -------------------------------------------------- 
     // This function is called with a setInterval so that it runs at a set interval depending on the number 
     // passed to var myVar = setInterval(myTimer, 1000); above. It gets the session variable 
     // containing the expires at date/time and also the current time. If the difference is less than the value set 
     // a warning is shown via an alert box and then the function is cleared. 
     // ------------------------------------------------------------------------------------------------ 

      function myTimer() { 
        var diff = 0;                // Initialize the difference between expires date/time and current date/time 
        var expires_raw = '<%= session[:auto_session_expires_at] %>'    // Get the raw session variable from rails 
                           // we need to parse the date above to be like var d = new Date('2016-05-10T13:50:12-04:00'); 
        var exp_date = expires_raw.slice(0,10);         // grab the date 
        var exp_time = expires_raw.slice(11,19);         // grab the time H M S 
        var exp_tzh = expires_raw.slice(20,23);         // grab the hour part of the timezone with the - 
        var exp_tzm = expires_raw.slice(23,25);         // grab the minute part of the timezone which should be 00 
        var expires_parsed = exp_date + "T" + exp_time + exp_tzh + ":" + exp_tzm; // Parse it all together. Date plus a constant 'T' , time, time zone hour, colon, timezone min 
        var expires_parsed_time = new Date(expires_parsed);      // take expires_parsed and create a date/time from it 
        var expires_parsed_time_iso = expires_parsed_time.toISOString();   // Convert expires_parsed_time to an ISO string - This step is KEY to making this 
                           // work with IE 11 and firefox. They need the date from a strict ISO format 
        var expires_final = new Date(expires_parsed_time)       // create a date from the expires_parsed_time 
        var expires_parsed_final = new Date(expires_parsed_time)     // This is the final date that is fed to the diff variable 


        var e = new Date();               // set up a new date for the current time 
        current_time = e.getTime();             // get the current time from the system 
        diff = expires_parsed_final - current_time ;        // calculate the difference between the expires and current times. 

      // The following commented alert can be uncommented as a debugging tool 

//         alert("\n raw date  " + '<%= session[:auto_session_expires_at] %>' + 
//         "\n exp parsed  " + expires_parsed + 
//         "\n diff   " + diff + 
//         "\n current_time " + current_time + 
//         "\n exp raw   " + expires_raw + 
//         "\n exp date  " + exp_date + 
//         "\n exp time  " + exp_time + 
//         "\n exp tzh   " + exp_tzh + 
//         "\n exp tzm   " + exp_tzm + 
//         "\n exp par time " + expires_parsed_time + 
//         "\n exp par tm iso " + expires_parsed_time_iso + 
//         "\n exp par final " + expires_parsed_final); 

     if (diff < 180000) { 
      alert("\n Your Internal complaints session is about to timeout \n in less than 3 minutes \n \n " + 
        "Please save your work \n" + 
        "Navigating to any page will reset the timeout timer"); 
        clearInterval(myVar);              // this clears the current warning timer since the message has already been shown to the user. 
      } 
     } 


     // ------------------------------------ clearTimer ------------------------------------------ 
     // When called, this function will stop the setInterval for myTimer so that we don't have 
     // multiple timers running 
     // ------------------------------------------------------------------------------------------ 

      function clearTimer() { 
      clearInterval(myVar); 
      } 


      function myTest() { 
      alert("test inside the test"); 
      } 

    <% end %> 

Еще одна проблема, которую я столкнулся в том, что Firefox и IE использовать строгое толкование стандартов ISO для даты. Это потребовало нескольких дополнительных шагов, чтобы использовать формат ISO 8601 для даты, прежде чем пытаться установить арифметику в IE/FF.

Это все еще требует небольшой работы, но, возможно, это может помочь кому-то, кто пытается сделать подобное предупреждение «до таймаута».

Смежные вопросы