Authentication and authorization: Remembering were you came from
Most webapps need authorization and authentication of some sort, right?
If you happen to have a copy of Agile Web Development with Rails, then you are fortunate, as it covers adding support for that very thing.
It is a bit simplistic though. Books have to have a finite length, and so some not everything can be covered in super depth.
I followed their recipe for authentication on my blog, and my annoyance was that if you request an authorized action, you get prompted to login, but after logging in, you get sent to a single page you set in code, NOT the resource you were initially requesting.
Fortunately, this is pretty simple to address.
So if you were following things in the book, in ApplicationController, you have something like:
So the trick here is to record what was being requested in the session. The URI being requested is available from request’s request_uri
method. The updated authorize looks like:
We remember what the URI requested was, and get sent to the login page in UserController. The trick is to do something useful with it in the login action. Initially, login will look like:
If the request URI is stashed on the session, we want to redirect it and reset the value, otherwise, just redirect to the default page we had before. Here’s the resulting code:
Pretty straightforward, right?