authentication and conditional page caching

This is another followup on conditional page caching in Rails. In the original article I glossed over the integration of the page caching with the authentication mechanism. After all, there are lots of web sites discussing how to do authentication in Rails, so it was not really the focus of the article. However a few readers have been confused because I didn’t make it very clear where my solution was incomplete.

The most confusing part of the article was that I used the method c.loggedin? without pointing out that this method doesn’t exist in Rails – you have to define it for your application. It is just a method on your controller that returns ‘true’ if there is a logged in user, and ‘false’ if not. This will be defined on the ApplicationController application.rb. In many applications, the user (or user ID) will be stored in the session, so it would be sufficient to define the method like this (change session attribute name as necessary):

def loggedin?
session[:user]
end

The other point is that whatever authentication mechanism you use, it has to call the code for setting and clearing the ‘logged_in’ cookie. (My own application is using OpenID for authentication, so it is not a good example for a ‘typical’ application.)

When your user is logged in, you need to call

cookies[:logged_in] = 'yes'

When your user logs out, you need to call

cookies.delete :logged_in

I hope that makes this a bit clearer.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*