【问题标题】:Rails 3 + Devise: log out user after timeoutRails 3 + Devise:超时后注销用户
【发布时间】:2011-03-09 14:58:42
【问题描述】:

在我的应用程序中,我将 Devise 设置为在 30 分钟后使会话超时。哪个工作正常......用户必须在那之后再次登录。我唯一的问题是,在会话超时后,设计显然不使用会话控制器中的销毁操作。因此,用户的属性 :signed_in 未设置为“假”。 因此,即使在会话超时后,该用户仍显示为在线。 有没有办法在超时后销毁会话或在一定时间后和浏览器关闭时将 signed_in 属性设置为 false?

我在会话控制器中的销毁操作:

def destroy
  current_user.try("signed_in=", false); current_user.save
  signed_in = signed_in?(resource_name)
  sign_out_and_redirect(resource_name)
  set_flash_message :notice, :signed_out if signed_in
end

【问题讨论】:

    标签: ruby-on-rails session devise


    【解决方案1】:

    我并不是 Devise 方面的专家,但我怀疑这是因为 HTTP 的无状态特性。 Devise 仅在用户尝试在您的超时时间后再次访问页面时才知道会话超时,并且可能只会在用户实际注销并在会话控制器上调用 destroy 方法时调用 destroy 方法。

    为了实现您可能正在寻找的目标,您需要运行一个后台进程来扫描旧会话,然后手动调用 destroy 方法(或执行类似操作)。

    【讨论】:

      【解决方案2】:

      使用新的 Devise 版本,它的工作原理如下,以获得准确的在线/离线状态:

      把它放在你的 application_controller 中:

      before_filter :last_request
      
      def last_request
       if user_signed_in?
        if current_user.last_request_at < 1.minutes.ago
          current_user.update_attribute(:last_request_at, Time.now)
        end
        if current_user.currently_signed_in = false
            current_user.update_attribute(:currently_signed_in, true)
        end
       end
      end
      

      应用程序会检查最后一次请求是否超过 1 分钟,如果是,他会更新用户属性。

      把这个放到user.rb中:

      before_save :set_last_request
      
      Warden::Manager.after_authentication do |user,auth,opts|
        user.update_attribute(:currently_signed_in, true)
      end
      
      Warden::Manager.before_logout do |user,auth,opts|
        user.update_attribute(:currently_signed_in, false)
      end
      
      def set_last_request
        self.last_request_at = Time.now
      end
      
      def signed_in?
       if self.currently_signed_in
      
        if self.timedout?(self.last_request_at.localtime)
          return false
        else
          return true
        end
      
       else
        false
       end
      end
      

      然后你可以使用signed_in 吗?确定用户在线状态的方法。

      【讨论】:

        猜你喜欢
        • 2013-04-18
        • 2020-08-22
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多