views:

1118

answers:

3

Is there an easy way in Authlogic (haven't found nothing browsing the docs) to assure that a UserSession can't be created if the User already has an UserSession object?

In other words: I want to make sure that a user can't log in twice with the same credentials.

UPDATE: Check the comments on thief's answer to find the solution to this problem.

+3  A: 

in your user sessions controller:

    before_filter :require_no_user, :only => [:new, :create]

in your app controller:

def require_no_user
  if current_user
    store_location
    flash[:notice] = "You must be logged out to access this page"
    redirect_to account_url
    return false
  end
end
thief
In addition, it's probably best to hide the login links as well, when someone is logged in.
Steve Klabnik
@thief: Could you elaborate? I don't understand how this will keep X to log in as Alice on client B while Y is already logged in as Alice on client A.
Javier
I misunderstood your question. In this case a callback is the way to go. eg: in your UserSessionModel use the callback 'before_persisting' to check if the account is logged in on another machine with the AuthLogic method 'logged_in?' - http://authlogic.rubyforge.org/classes/Authlogic/ActsAsAuthentic/LoggedInStatus/Methods/InstanceMethods.html::
thief
A: 

To my mind a cleaner approach is to use callbacks in the UserSession class. Like, you can define a before_create callback there, and mark the model as invalid in appropriate case. Haven't tried this out myself, though. Here are the docs for the Callbacks module.

neutrino
Yes, but you can use your require_no_user method anywhere that it is required that a user is not logged in, also it pairs well with its opposite: require_user
thief
I agree. Nothing to add here.
neutrino
A: 

Sorry to rehash the question, but I'm having some trouble getting this to work in my app. I understand the logic - use a callback to check if the user's already logged in - but I can't seem to figure out how to write it.

Could someone elaborate a bit?

Cory Schires
If you have some specific questions/problems about the implementation better start a new question about it, more people will see it that way. The "Ask Question" button is in the top right of the page.
sth
Look for the "current_user" method in Authlogic. That will probably answer your question. If not, starting a new question and asking specifically what your problem is will probably solve your problem and help others having the same problem.
Javier