views:

695

answers:

1

Warning: some of this may be very wrong-headed, so please let me know if my assumptions are incorrect.

Here's what I'm trying to accomplish:

I'm using restful-authentication for login. However, as I am using flex/ruby_amf for my UI, I have to separately authenticate each connection from flex.

The way I decided to do that was by having the log-in screen redirect to the embedded flash page, inserting the session-id as a flashvar. The flash app sends the session-id with every request, and a before filter on all of the relevant controllers checks to see if the user associated with the session identified by the session-id is logged on.

The way I associate a user with session is by adding a 'user_id' column to the sessions table, and doing an sql "update sessions set user_id...'" type query called from the login function.

However, the user_id only gets updated the 2nd time the user logs in. A little investigating showed that the record in the sessions table does not yet exist during execution of the login function.

So, if everything up to this point makes sense, and conforms to best-practices, etc., then my question is:

At what point in time is the record in the sessions table created? Is there a way to update the session object in the login function and have rails write the user_id to the database for me?

The behavior of sessions in rails is a real mystery to me. I'd appreciate any help.

Thank you.

A: 

In Rails 2.3, the session is saved after the Rack application has finished its processing. In traditional Rails applications, this will be after the request is fully processed: before filters, controller action, view rendering, and after filters. Look in actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/session/abstract/id.rb.

If you think about it, this makes perfect sense. Writing the session to its store every time you place something in the session would incur a lot of extra overhead.

It's Rails, so if you want to mess with it enough, sure, you can monkeypatch yourself a way to write the session to store anytime you wish. I don't recommend it. You'll end up having to rework the code constantly as Rails evolves.

You are right that for ActiveRecord::SessionStore, one row does map to one session. The data column is an encoded form of every object you put in the session. Each time a request comes in, Rails has to reconstitute the session as it existed by creating new instances of all the objects you previously stored in it.

Steve Madsen