Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails and Authlogic: Allow only one session per user?

Is there a way to limit the number of sessions in Ruby on Rails application (I'm using Authlogic for authentication)?

I would like to allow only 1 session per user account. When the same user is logging on another computer the previous session should be expired/invalidated.

I was thinking about storing the session data in database and then deleting it when a new session instance is created but probably there is an easier way? (configuration option)

like image 589
Jakub Troszok Avatar asked Sep 18 '25 15:09

Jakub Troszok


1 Answers

I just ran into a possible solution, if you reset presistence token you can achieve the intended behaviour:

class UserSession < Authlogic::Session::Base
  before_create :reset_persistence_token

  def reset_persistence_token
    record.reset_persistence_token
  end
end

By doing this, old sessions for a user logging in are invalidated.

Earlier I implemented it as you mentioned: add a session_key field to the users table and make sure that the current session_id is stored for the user on login:

class UserSession < Authlogic::Session::Base
  after_save :set_session_key
  def set_session_key
    record.session_key = controller.session.session_id
  end
end

Then in the generic controller do something like this to kick out a user when someone else logged in with that same account:

before_filter :check_for_simultaneous_login

def check_for_simultaneous_login
  # Prevent simultaneous logins
  if @current_user && @current_user.session_key != session[:session_id]
    flash[:notice] = t('simultaneous_logins_detected')
    current_user_session.destroy
    redirect_to login_url
  end
end
like image 164
vdB Avatar answered Sep 21 '25 07:09

vdB