db.networx
working with Rails 2.0, Ruby on Rails, Flex, Flash and …A simple Referer
April 22, 2008 at 11:55So 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:
-
def authorize
-
unless User.find_by_id(session[:user_id])
-
session[:referer] = request.path_parameters
-
flash[:notice] = "Please Log-In"
-
redirect_to :controller => "/user", :action => "login"
-
end
-
end
This method is added to every controller where a user has to be authenticated. You do that using a before filter:
-
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:
-
def login
-
. . . . .
-
if session[:referer]
-
referer = session[:referer]
-
redirect_to(:controller => referer[:controller], :action => referer[:action] )
-
else
-
redirect_to(:controller => "/user", :action => "index")
-
end
-
. . . . .
-
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
HTML-Tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>