如何注销所有登录用户

时间:2019-04-01 10:08:51

标签: ruby-on-rails ruby session session-cookies sorcery

我在我们的网站中使用巫术进行身份验证。我想从我们的网站注销所有登录用户,但找不到任何方法注销所有用户。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

  1. 使用超时

    # config/initializers/sorcery.rb
    Rails.application.config.sorcery.submodules = [:session_timeout]
    
    # config/initializers/sorcery.rb
    Rails.application.config.sorcery.configure do |config|
      config.session_timeout = 1 # This is in seconds.
      config.session_timeout_from_last_action = true # session timeout is calculated from the last valid activity. By default this is false.
    end
    
  2. 使用回调

    # app/controllers/application_controller.rb
    before_action :auto_logout, if: :logged_in?
    def auto_logout
      force_forget_me!
      logout
    end
    
  3. 使用current_users,在用户模型中添加类方法

    # app/models/user.rb
    def self.get_current_users
      config = sorcery_config
    
      where("#{config.last_activity_at_attribute_name} IS NOT NULL") \
      .where("#{config.last_logout_at_attribute_name} IS NULL 
        OR #{config.last_activity_at_attribute_name} > #{config.last_logout_at_attribute_name}") \
      .where("#{config.last_activity_at_attribute_name} > ? ", config.activity_timeout.seconds.ago.utc.to_s(:db))
    end
    
    # call upper method anywhere (or console)
    User.get_current_users.each do |user|
      current_user = user
      before_logout!
      @current_user = nil
      reset_sorcery_session
      after_logout!(user)
    end
    
  4. (推荐)从磁盘中删除会话存储,例如session_store,redis等。

答案 1 :(得分:0)

您可以使用invalidate_active_sessions!

使所有会话无效

请参见https://github.com/Sorcery/sorcery#session-timeout