使用Javascript在Devise注销后自动重定向?

时间:2013-11-08 15:21:14

标签: javascript ruby-on-rails devise

我正在使用Devise,自动注销效果很好。

但是,在用户发出另一个请求之前,系统不会通知用户他们已被注销,此时他们会被重定向到登录页面。对于AJAX功能,这不是很好,它要么无声地失败,要么引发异常。

设计维基似乎没有一个例子,是否有一个标准的解决方案?一个带有倒数计时器的javascript弹出窗口,如果用户没有点击“让我登录”,它会进行重定向吗?

1 个答案:

答案 0 :(得分:1)

我最终实现了类似于下面的jscript超时。

一些悬而未决的问题:

  • 切换到另一个标签时会发生什么?
  • 适用于IE?

<强>的application.js

//= require timer

// redirect user after 15 minutes of inactivity - should match Devise.timeout_in + 1 second grace period
$(function() {
    var logout_timer = new Timer(901, 'users/sign_in', window);
    logout_timer.start();

    // restart timer if activity
    $(document).on('keyup keypress blur change mousemove',function(){
      logout_timer.start();
    });

});

<强> timer.js

Timer = function(time_in_secs, path, windowobj) {  // window object must be injected, else location replace will fail specs
  var self = this;    // 'this' not avail in setInterval, must set to local var avail to all functions
  this.state = 'init'
  this.time_remaining = time_in_secs;
  this.timer_id = undefined;

  this.start = function() {
    // if restarting, there will be a timer id.  Clear it to prevent creating a new timer, reset time remaining
    if (this.timer_id !== undefined) {
      this.time_remaining = time_in_secs;
      this.clear_timer(this.timer_id, self); 
    }
    this.state = 'running';

    this.timer_id = setInterval(function() {    // IE any version does not allow args to setInterval.  Therefore, local variables or refer to self obj
      self.time_remaining -= 1;

      // log status every 10 seconds
      if ((self.time_remaining % 10) === 0) {
        console.log("logging user out in " + self.time_remaining + " seconds");
      }

      // when timer runs out, clear timer and redirect
      if ( self.time_remaining <= 0 ) {
        self.clear_timer(self.timer_id, self);
        self.do_redirect(path, windowobj);
      };


    }, 1000);
    return this.timer_id;
  };

  this.clear_timer = function(timer_id, self) {
    self.state = 'stopped';
    clearInterval(self.timer_id);
  }

  this.remaining = function() {
    return this.time_remaining;
  };

  this.do_redirect = function(path, windowobj) {
    console.log("Redirecting to " + path);
    self.state = 'redirecting';
    windowobj.location = path;
  }
}