Using Devise on Rails, is there some way to list all the users who currently have active sessions i.e. the users that are currently logged in?
Ps. I'm looking for a robust solution, not something simplistic like the ones in this question
Using Devise on Rails, is there some way to list all the users who currently have active sessions i.e. the users that are currently logged in?
Ps. I'm looking for a robust solution, not something simplistic like the ones in this question
https://github.com/ctide/devise_lastseenable
You can use this gem that I wrote to store the 'last_seen' timestamp of a user. From there, it's pretty trivial to display the users who were last_seen in the last 5 or 10 minutes.
Simply add after_filter in ApplicationController
after_filter :user_activity
private
def user_activity
current_user.try :touch
end
Then in user model add online? method
def online?
updated_at > 10.minutes.ago
end
Also u can create scope
scope :online, lambda{ where("updated_at > ?", 10.minutes.ago) }
https://github.com/ctide/devise_lastseenable
You can use this gem that I wrote to store the 'last_seen' timestamp of a user. From there, it's pretty trivial to display the users who were last_seen in the last 5 or 10 minutes.
If you're bothered by making a trip to database on every. single. http. request. only to have some small window where you can sort of assume that a user is online; I have an alternate solution.
Using websockets and redis it's possible to reliably get a user's online status up to the millisecond without making a billion costly writes to disk. Unfortunately, it requires a good bit more work and has two additional dependencies, but if anybody's interested I did a pretty detailed write here:
I've just implemented another version of this and thought I'd share in case it helps anyone else.
I just add a last_sign_out_at
column to my Users table and then subclassed the Devise sessions controller so I could override the destroy method to set it when the session is destroyed (user signs out):
# app/controllers
class SessionsController < Devise::SessionsController
def destroy
current_user.update_attribute(:last_sign_out_at, Time.now)
super
end
end
And then in my User model I have a method to check if the user is online:
class User < ActiveRecord::Base
def online?
if current_sign_in_at.present?
last_sign_out_at.present? ? current_sign_in_at > last_sign_out_at : true
else
false
end
end
end
Also you need to tell Devise to use the new Sessions controller in your routes.
We can list the current active sessions using the active record session store. Please look at the github app page https://github.com/mohanraj-ramanujam/online-users.
© 2022 - 2024 — McMap. All rights reserved.