Today I am going to talk about limiting access in rails. this is reference from Agile Web Development with Rails. This book telling you the basic how to prevent user to type the url directly access to the page.

let’s say you have a controller called “Login

class LoginController < ApplicationController

# first page

def index

end

# login page

def login

end

end

So we don’t want user to access the index page. we are going to create an “authorize” method in ApplicationController, the parent class of all our controllers.

class ApplicationController < ActionController::Base

helper :all # include all helpers, all the time
session :session_key => “_aom_session_id”
private

# check if user has been loging in.
def authorize

unless User.find_by_id(session[:user_id])
redirect_to(:controller => ‘login’ ,:action => ‘login’)
end

end

end

alright so we have 1 last thing left, that is we need to add before_filter into our controller

class LoginController < ApplicationController

before_filter :authorize

#…………..

end

That’s it. now our Login controller can not prevent user to access the url without login.

**But if you start server and try to view your page. it going to end up like this \

The page isn’t redirecting properly

that because after you put => before_filter :authorize in your controller, it means that you can not access any action in your controller without login but in “authorize” method is redirect you to the “login” page, which you cannot access it either.

So if you need to finish this you need to put one more thing, which is an “exception”

class LoginController < ApplicationController

before_filter :authorize, :except => ‘login’

#…………..

end

created by WhenURnotAround