How can I find out if this Devise user is signed up right now?

In a Rails app using Devise, there is a way to find out if a particular user is signed in

Do I know about a helper like 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 the current_sign_in_at column to users . But this will not be set to NULL when the user logs out, so I cannot verify this.

How can I check if a user is currently signed up?

+4
source share
4 answers

You can add before_filter to your ApplicationController to set the current date / time in the last_request_at field in your users table, which you must first add through migration. In the method called from the before_filter file, you must make sure that the user is authenticated first, of course. And you may want, in addition to the filter, for actions that do not require authentication.

Then, assuming that you have included the Timeoutable module in the user model, you can find out if the user session is current or not by making this call:

 user.timedout?(user.last_request_at) 

Timedout method ? (last_access) defined in the Timeoutable module compares the development session timeout with the last request time / date.

As an additional note, you may need to update last_request_at if the last value of last_request_at is more than a minute ago (or any time interval you choose). Otherwise, if there are many controller calls on your page, for example mine, through AJAX, in one request there are many unnecessary db updates.

+6
source

Are you trying to track if the user has been signed up and the session is active, or if the user is currently on the site?

To keep track of if the user is logged in, you need to add a callback to Warden and update the timestamp every time the page loads, and then, if they haven’t done anything longer than the X period, you assume that they are logged out. You can do this with:

 Warden::Manager.after_authentication do |user, auth, opts| if user.last_action <= 5.minutes.ago.utc user.last_action = Time.now user.save end end 

If you want to find out if there is an active season and have not been explicitly logged out, this would be something like:

 Warden::Manager.before_logout do |user, auth, opts| user.current_sign_in_at = nil user.save end 
+4
source

Add an active flag to the user model (invent). In the application controller, under the after_sign_in_path_for(resource) hook, set the active flag to true (happens when the user successfully creates a new session).

for a logged out user, override the destroy method in devise session_controller and set the active flag to false, and then call super.

Now can you call user.active? for any user.

+1
source

Devise ships with the current_user method, which will return the current user in controllers, models, and views.

0
source

Source: https://habr.com/ru/post/1390669/


All Articles