Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell whether a given Devise user is signed in right now?

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

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

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?

like image 763
Nathan Long Avatar asked Jan 12 '12 15:01

Nathan Long


1 Answers

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.

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)

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

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.

like image 169
yuяi Avatar answered Nov 15 '22 10:11

yuяi