How to get rails authentication and redirection to work under RJS
While adding some new features to the auth system I came across some issues regarding certain RJS links that weren’t working as planned in regards to the authentication. With the RJS links, when clicked, if the auth session was expired it wouldn’t redirect back to the login page.
I’m using Auth Generator 2.0 and this might not apply to your auth system. So for redirection you’ll have to look beyond the standard rails redirect_to() method. This is because the prototype library doesn’t respond to HTTP status codes like a browser does. It also doesn’t follow 3xx redirect status codes.
Good thing the JavascriptGenerator in RJS has a redirect_to() method to take care of this. So for RJS methods or RJS links in views that require authentication redirection, you’ll need to call a separate auth method for the RJS methods in your controller.
The original auth method would look something like this:
def check_authunless user_logged_in?
flash[:notice] = “You lack credentials to access this page”
redirect_to :controller => ‘auth’, :action => ‘login’
end
end
But this won’t work in an RJS call. So you’ll have create something like this:
def rjs_check_authunless user_logged_in?
flash[:notice] = “Sorry but your session has expired, please login again.”
render :update do |page|
page.redirect_to :controller => ‘auth’, :action => ‘login’
end
return false
end
end
Set this to run in your RJS methods in order to force a redirect if their login has expired.
def rjs_method
rjs_check_auth
… rest of RJS code …
end
or stick it in a before_filter in your controller. I’m sure there a million other ways to do this and probably a few thousand better but this works for me.
.
Posted on September 30, 2006
Filed Under Daily Thoughts, Design, Ruby on Rails, Tech, Web
Related Posts:
-
Here’s my Ruby on Rails Stack … Literally
Ruby on Rails 1.1 Released!
In-Depth Ruby on Rails and Django Comparison
The Ruby on Rails Triad
Rails is a ghetto? Zed Shaw goes to war with Rails and the Rails community
10 AWESOME work environments
Comments
Leave a Reply
