Make RESTful Authentication XHR-aware
I’ve been working on a project that uses a little XHR mixed into the app to update DIVs on a page. The problem with the RESTful Authentication plugin is that it will always send a redirect back to the browser if the user is no longer logged in, but the XHR callback will simply try to insert the response into the DIV. Since the user may leave the page running for long periods of time, I need a graceful way of redirecting them to the login should they make an XHR request after their server session has timed out.
To make RESTful Authentication XHR-aware, I simply edited the access_denied function in lib/authenticated_system.rb so that it now looks like this:
def access_denied
respond_to do |format|
format.html do
if request.xhr?
# send a javascript-based redirect
render :inline => "<script>document.location.href = '<%=url_for(:controller => '/sessions', :action => 'new')%>';</script>"
return
end
store_location
redirect_to :controller => '/sessions', :action => 'new'
end
format.xml do
request_http_basic_authentication 'Web Password'
end
end
end
By sending a script tag back with the redirect, I force the browser to go to the login page rather than silently fail. Now I have a happy customer that simply needs to login again. I’ll be the first to admit this is a simple approach, but I still like it.