random_user_0891
random_user_0891

Reputation: 2051

indicate which users are currently logged in

I'm trying to find a way to display logged in active users on my web app. I'm not using any gem for authentication like Devise. I have a list of users and wanted to show an icon or some type of indicator next to a users name if they are currently on the site.

I'm not sure how to go about this. Possibly I could add a column called currently_logged_in to my User model and could set the value to true when the session is created and then to false when the user session is destroyed?

class SessionsController < ApplicationController

    def new
    end

    def create
      if user = User.authenticate(params[:email], params[:password])
        session[:user_id] = user.id #session id created off of the 
        redirect_to(session[:intended_url] || user)
        session[:intended_url] = nil #removes url from the sessions 
      else
        flash.now[:error] = "Invalid email/password combination"
        render :new
      end
    end

    def destroy
      session[:user_id] = nil
      redirect_to root_url
    end

end

User model

 # tries to find an existing user in the database so that they can be authenticated.
  def self.authenticate(email, password)
      user = User.find_by(email: email) # returns user or nil value
      user && user.authenticate(password) # if user exists validate that password is correct
  end

Upvotes: 2

Views: 1010

Answers (2)

Foram
Foram

Reputation: 623

Firstly You need to find current user on site. You may b call current_user method which is in application helper and you should display all current user in wherever you want. For Example,

module ApplicationHelper
 def current_user
  @current_user ||= session[:user_id] && User.find_by_id(session[:user_id])
 end
end

And you call this method in Session controller as @current_user.

Upvotes: 0

Mike G
Mike G

Reputation: 668

It depends what you mean by "currently on the site".

Adding a currently_logged_in column like you described works IF you want to mark users that are currently logged in. However most users don't log out when leaving a website these days so that probably won't do what you want.

A better solution would be to add a last_active_at column which you can update with the current time whenever a user performs some action. Then determine a threshold that makes sense for your website, let's say 15 minutes, and only mark users in your list that have a last_active_at value less than 15 minutes in the past.

Assuming the definition of "active user" for your website involves hitting authenticated endpoints it would be as simple as changing your authenticate method to:

def self.authenticate(email, password)
  user = User.find_by(email: email) # returns user or nil value
  if user && user.authenticate(password)
    user.update!(last_active_at: Time.now)     
    true
  else
    false
  end
end

Upvotes: 4

Related Questions