如何判断给定的Devise用户是否已经登录? [英] How can I tell whether a given Devise user is signed in right now?

查看:133
本文介绍了如何判断给定的Devise用户是否已经登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Devise的Rails应用程序中,是否有一种方法来判断具体用户是否已登录

In a Rails app that uses Devise, is there a way to tell if a specific user is signed in right now?

我知道视图助手, user_signed_in?。我正在寻找的更像是:

I know about the view helper, user_signed_in?. What I'm looking for is more like:

User.all.each do |user|
  puts user.signed_in?
end

我看到,Devise添加了一个 current_sign_in_at 列到用户。但是,当用户注销时,不会设置为 NULL ,所以我无法测试。

I see that Devise has added a current_sign_in_at column to users. But that doesn't get set to NULL when the user signs out, so I can't test with that.

如何检查用户当前是否已登录?

How can I check whether a user is currently signed in?

推荐答案

您可以添加 before_filter 到您的ApplicationController以在用户表中的 last_request_at 字段中设置当前日期/时间,您必须首先通过迁移添加。在从before_filter调用的方法中,您要确保用户首先被认证,当然。而您可能希望除了过滤器以外的操作不需要身份验证。

You can add a before_filter to your ApplicationController to set the current date/time in the last_request_at field in your users table, which you'd have to add first via a migration. In the method called from the before_filter, you wanna make sure that the user is authenticated first, of course. And you may want to except the filter for actions not requiring authentication.

然后,假设您已经在您的用户模型中包含了 Timeoutable 模块您可以通过以下方式查看用户的会话是否正在进行:

Then, assuming you've included the Timeoutable module in your User model, you can see if the user's session is current or not by making a call like this:

user.timedout?(user.last_request_at)

在Timeoutable中定义的 timedout(last_access)模块将会将Devise会话超时与最后一个请求时间/日期进行比较。

The timedout?(last_access) method, defined in the Timeoutable module, will compare the Devise session timeout with the last request time/date.

作为附注,如果最后一个last_request_at值更大,您可能只想更新last_request_at (或任何时间间隔您选择)。否则,如果您的页面进行了很多控制器调用,就像我通过AJAX一样,在一个请求中有很多不必要的数据库更新。

As a side note, you might want to only update last_request_at if the last last_request_at value is greater than a minute ago (or any time interval you choose). Otherwise, if your page makes lots of controller calls, like mine does via AJAX, there are a lot of unnecessary db updates in one request.

这篇关于如何判断给定的Devise用户是否已经登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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