Search

Auto-Login for Any URL in Rails

James Edward Gray

2 min read

Feb 5, 2008

Auto-Login for Any URL in Rails

One of our current projects at Highgroove sends a lot of email to its users. It essentially walks them through a process and emails them at each step. All of those messages include URL’s to visit the relevant page in the application for that step. Since we’ve emailed them the URL’s we don’t want them to have to login every time they click one.

To get around that I modified the application to accept URL’s like the following:

    http://domain.com/login/TOKEN/ANY/SITE/URL 

These URL’s log the user in using their security TOKEN and then redirect them to /ANY/SITE/URL. This setup allows me to easily forward a user to any URL on the site which is great when writing all of these emails.

The code is easy enough too. I imagine many of us have a sessions controller that looks something like:

    class SessionController < ApplicationController   def create     if user = User.authenticate(params[:email], params[:pass])       # log user in...     else       # login error message...     end   end    # ... end 

First, I just added some support for the token based login with redirect to that:

    class SessionController < ApplicationController   def create     if params[:token] and (user = User.find_by_token(params[:token]))       # log user in...       if params[:path].is_a? Array         redirect_to "/#{params[:path].join('/')}"       else         redirect_to home_path  # or whatever default page you want       end     elsif user = User.authenticate(params[:email], params[:pass])       # log user in...     else       # login error message...     end   end    # ... end 

The magic redirect_to() call in that new code uses a not-often-seen feature of Rails’s routing. You can specify that Rails collect any number of trailing URL bits into an Array much like Ruby can do for method parameters. Here’s the route definition I am using to get users to the code above:

    # a custom login route with forwarding map.connect "login/:token/*path", :controller => "session",                                   :action     => "create" 

The *path is the magic slurping parameter syntax, again just like arguments to a Ruby method. Rails will collect each piece of the remaining URL into an Array called path, so just remember that you need to rejoin the elements to make them a real URL again.

Josh Justice

Reviewer Big Nerd Ranch

Josh Justice has worked as a developer since 2004 across backend, frontend, and native mobile platforms. Josh values creating maintainable systems via testing, refactoring, and evolutionary design, and mentoring others to do the same. He currently serves as the Web Platform Lead at Big Nerd Ranch.

Speak with a Nerd

Schedule a call today! Our team of Nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Not applicable? Click here to schedule a call.

Stay in Touch WITH Big Nerd Ranch News