inicio mail me! sindicaci;ón


working with Rails 2.0, Ruby on Rails, Flex, Flash and …

A simple Referer

April 22, 2008 at 11:55
Explaination: I assume you have a restricted area where a user has to log in before he can use this area of your website.
So when the user sets a direct Link to a page in that user area and wants to use that link again when he is not logged in, he will be redirected to the login page and after the correct login he will get to a page specified in that login method, but not to the page he wanted to go.

A simple Referer could solve that problem by grabbing the initial url and storing it until the is logged in. That’s where the user could be send to the page he originally wanted to visit.
To make a referer like this one you need at least a small authorization filter. In my application.rb there is the following method:

Code (ruby)
  1. def authorize
  2.  unless User.find_by_id(session[:user_id])
  3.   session[:referer] = request.path_parameters
  4.   flash[:notice] = "Please Log-In"
  5.   redirect_to :controller => "/user", :action => "login"
  6.  end
  7. end

This method is added to every controller where a user has to be authenticated. You do that using a before filter:

Code (ruby)
  1. before_filter :authorize

For example the user wants to go to http://localhost/user/profile but is not logged in. The method authorize checks ( Line 2) whether the user is logged in, if it’s not the case he will be redirected (Line 5) to the Login in page. The interesting part is in line 3. Here the path the user entered is grabbed (http://localhost/user/profile) and stored in the current session as session[:referer].
Next thing is to get the referer path from the session after a successful login and redirect the user to the page he wanted to go. To make that happen just enter the following snippet into your login method:

Code (ruby)
  1. def login
  2.  . . . . .
  3. if session[:referer]
  4.  referer = session[:referer]
  5.  redirect_to(:controller => referer[:controller], :action => referer[:action] )
  6. else
  7.  redirect_to(:controller => "/user", :action => "index")
  8. end
  9.  . . . . .
  10. end

It’s rather self explainatory, if there is a referer variable in the session (line 3) the user will be redirected to the original page (line 5).

If you have any question or there are mistakes in my code don’t hesitate to leave a comment.

No comments yet »

Your comment

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>