views:

75

answers:

1

I want to set up auto-login by giving the user a link/key they can use like http://domain.com/4yT67rw. The last 7 digits are random and assigned to the user model.

Is it possible to do this with custom routing? I imagine it would have to be something like a regex to detect that it is a key and not a model name or error.

Would be great if I could do something like:

map.connect 'reg_ex_here', :controller => 'users', :action => 'key_redirect'

and then in the users controller:

def key_redirect
  user = User.find_by_key(key)
  redirect_to user_path(user)
end

Or probably some other easy way that I don't know about. ;)

Thanks

+2  A: 

something like this should work for you:

map.key_redirect '/:key_id', :requirements => {:key_id => /regex_here/}, :controller => 'users', :actions => 'key_redirect'

As with all routes, you can then refer to key_redirect_path or key_redirect_url when constructing urls.

Jason Yanowitz
Awesome. Thanks a lot, I didn't know about :requirements
Shagymoe
If you're going to do this, I would suggest NOT doing it at the root url. Instead, maybe something like /sessions/new/234829.
jonnii
Hi Jonnii, could you elaborate on why? A 16 digit key, composed of upper and lower case alphanumeric characters has 1498858244768912625744091545600000 possible combinations, so I'm not worried about someone brute-force cracking anything.
Shagymoe
Oops, make that 5719086709283091520696320000 combinations. ;)
Shagymoe
I just realized that my example only has 7 digits. I had actually planned on using 16. Also, I think the calculation is 62!/(62-16)! which gives the 5719... number. The key is an authentication token. Anyone who knows it can log in to the site as that user. The user is supposed to keep it a secret. There is no signup and the user does not submit any personal information.
Shagymoe
my previous calculation (I deleted) was wrong. a 16 digit key from [A-Za-z0-9] is 62**16 since you don't care about anagrams. That produces 47672401706823533450263330816 .If this is a high security application, btw, I would use https for this login and make sure not to log these URLs in your access log. Of course, if security really matters, you wouldn't want to do this at all :)
Jason Yanowitz