Feb 04 authlogic avoiding ending up with multiple sessions
tags:
Authlogic is cool to handle your authentication. But in my new app the admin user was the one who created new users and updated them also. There I stumbled with a funny gotcha. Admin logged out and there was the user session of the users just created/updated. The thing is authlogic when you save a model that acts a authenticated you got a user session created. The trick is to tell authlogic to save but not creating a session.
Have a look at what I did:
class ClientsController < ApplicationController
# no admin name spacing, see?
def create
@client = Client.new(params[:client])
respond_to do |format|
# the best practice would be to admin-namespace the clients creation
# but since later *surely* other users will create clients this here is more general (and fast to implement :-))
success = if current_user_is_not_the_one_saving? # you get the idea right?
@client.save_without_session_maintenance # here it is authlogic easy way
else
@client.save
end
if success
flash[:notice] = t('creation.success', :resource => t('client'))
format.html { redirect_to(@client) }
# ...
end
def update
@client = Client.find(params[:id])
respond_to do |format|
# and the update part
success = if current_user_is_not_the_one_saving?
@client.attributes= params[:client] # hah, cool! Rails at its best providing you with tools
@client.save_without_session_maintenance
else
@client.update_attributes(params[:client])
end
if success
flash[:notice] = t('update.success', :resource => t('client'))
# ....
end
end
and then do not forget to spec your code, here’s an idea on cucumber
# you did the creation and edition processes and then after you logout admin Then /^there should not be sessions active$/ do AdminSession.find.should be_nil ClientSession.find.should be_nil end