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.