Graceful session expiry?

According to the Rails book, the session object has an attribute called
:session_expires, but they don’t encourage its use. Currently I handle
session expiry by using a cron job to delete session files that have not
been modified in the last X minutes (it is a design/security requirement
for this project that sessions expire after a finite period of
inactivity).

However, this is a jarring experience for the user–to click on a link
and be taken, seemingly inexplicably, to the login page (which is where
I redirect if there is no valid session). It would be nice to detect the
condition that the session has expired (as opposed to the user clicking
on the “log out” link) and present a flash notice saying “Your session
has expired, please log in again.”

Any ideas how I would do that?

Dan T. wrote:

condition that the session has expired (as opposed to the user clicking
on the “log out” link) and present a flash notice saying “Your session
has expired, please log in again.”

Any ideas how I would do that?

Rather than simply deleting the session file, you could set it to a
specific “invalid” or “expired” value, which would cause a different
redirect, and you could then detect it on the login page, which would do
the deleting itself.

Alternatively, you can set the last-access time as a value in the
session, and check it’s not too old on the next load (before setting it
again, obviously), redirect as necessary, and keep your cron job
deleting things that are within a certain delta of the timeout. That
way, people who just miss the session timeout get an informative error,
and very old sessions just get clobbered.