cjm2671
cjm2671

Reputation: 19496

Simple Rails Session question

Having followed a tutorial online, I have a sessions controller that looks like:

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.authenticate(params[:email], params[:password])
    if user
      session[:user_id] = user.id
      redirect_to root_url, :notice => "Logged in!"
    else
      flash.now.alert = "Invalid email or password"
      render "new"
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => "Logged out!"
  end

end

There is no model & database table to back this up, although login does work. Is there any way for me to list the logged in users, or would that not be possible? How does the server persist sessions if they are not stored someplace?

Upvotes: 3

Views: 340

Answers (3)

apneadiving
apneadiving

Reputation: 115541

By default, sessions are cookie based. So because it's client-side you won't be able to know who is connected or not.

The principle is:

  • session is encrypted in the browser

  • cookies cannot carry more than 4ko, so only ids are stored inside

You can of course change this default behavior and store the information in database, cache or whatever.

Knowing who is online could be deduced by a lastseen parameter as already mentionned in the thread.

Beware though: Putting this kind of feature could consume much db queries. Prefer using cache.

Upvotes: 1

Swift
Swift

Reputation: 13198

How about this:

Update a field called last seen

class ApplicationController
  before_filter :update_last_seen
private
  def update_last_seen
    current_user.last_seen = DateTime.now
    current_user.save
  end
end

and then do a find for all users last seen within the last X minutes

@online_users = User.find :all, 
                      :conditions => ["last_seen > ?",5.minutes.ago.to_s(:db)]

Upvotes: 2

Sam 山
Sam 山

Reputation: 42863

This is basic http authentication. You don't need any server side stuff for this. See my blogpost about it here:

http://codeglot.com/posts/1-default_authentication_for_simple_rails_apps

Or checkout basically the same thing at railsguides:

http://guides.rubyonrails.org/getting_started.html#security

Upvotes: 0

Related Questions