在 Rails 中使用 Devise 注销特定用户 [英] Sign out specific user with Devise in Rails

查看:24
本文介绍了在 Rails 中使用 Devise 注销特定用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于用户身份验证的设计.我想注销具有特定 ID 的用户.

I have Devise for user authentication. I want to sign out a user with a specific id.

在我的控制器中

  def exit
    @user = User.find(5)
    sign_out(@user) # this line here signs out the current_user   
  end

devise 的注销命令,即使我通过了@user,它也会注销current_user.如何从数据库中选择用户并使用设计命令将其注销?

The sign out command of devise, even though I pass the @user, it signs out the current_user. How can I select a user from the database and sign him out with the devise commands?

推荐答案

我假设这是某个管理模块的一部分,您希望在其中注销特定用户.

I am assuming this is part of some admin module, where you want to sign out a particular user.

然而,这不容易解决.用户是否登录都存储在会话中.因此,要注销另一个用户,您必须有权访问其会话.

However, this is not easy to solve. Whether or not a user is signed in or not is stored in the session. So to sign out another user, you would have to have access to its session.

注意:afaik sign_out 方法仅适用于当前会话,或者可能通过warden(不太了解warden)它可以扩展到当前服务器曾经接触过的所有会话.但是:如果您使用乘客或某种形式的 rails 服务器集群(这很常见),afaik 这将不起作用.我有兴趣听到其他消息,并提供一些解释:) sign_out 使用给定的参数来确定从(afaik)当前会话中注销的范围.

Note: afaik the sign_out method only works in the current session, or maybe through warden (do not know warden well enough) it could extend to all sessions this current server has ever touched. However: if you use passenger, or some form of rails server cluster (which is pretty common), afaik this will not work. I would be interested to hear otherwise, with some explanation :) The sign_out uses the given parameter to determine the scope to sign out from in (afaik) the current session.

所以我们通常做的是添加一种紧急按钮来注销所有用户:它会破坏所有会话.请注意,这当然只有在您使用某些数据库或文档存储支持的会话存储时才有可能.

So what we generally did was add a kind of emergency button to sign out all users: which destroys all sessions. Note this is of course only possible if you use some database or document-store backed session-store.

或者,您可以打开所有会话,查找正确的会话(对于您的用户),然后销毁这些会话.

Alternatively you could open all sessions, and look for the correct session (for your user), and then destroy those sessions.

要从存储在 activerecord 中的特定会话中读取数据,您可以编写以下内容:

To read data from a specific session in stored in activerecord, you can write the following:

@session = ActiveRecord::Base.connection.select_all( "SELECT * FROM sessions WHERE session_id = '#{sess_id}'" )
Marshal.load(ActiveSupport::Base64.decode64(@session.data))

有替代方法:

  • 使用 Timeoutable 模块,并强制用户超时?
  • 如果您使用 Rememberable,您可以使用 @user.forget_me,但我不确定这是否会影响当前会话?
  • use Timeoutable module, and force a timeout for a user?
  • if you use Rememberable you could do @user.forget_me, but I am not sure that this actually affects the current session?

这篇关于在 Rails 中使用 Devise 注销特定用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆