Rails -Protecting Pages From Unauthorized Access
7 months ago
When you want to protect a page in a Rails app from uauthorized access you use a before_filter. Before_filters are placed at the top of a controller for a given view. Two parameters are passed to the before_filter: the method to call before allowing access to a page, and the page to restrict access to.
That’s all. The only slightly more complicated part involves writing the method that allows access, but it’s rather quite trivial.
Let’s review.
Step 1 – At the top of your controller add the following line of code:
before_filter :login_required, :only => [:index]
This line specifies that the method “login_required” must be executed before calling the “index” action and page.
Step 2 – Create a method in application.rb named “login_required”. All methods in application.rb are available to all Controllers. You can use this snippet:
def login_required unless logged_in?</code> session[:protected_page] = request.request_uri redirect_to :controller => "admin", :action => "login" return false end end