Restrict certain routes to logged in users
I'd like /something to only be accessible for logged in users, I have a current_user helper which returns a user id or nil if the current visitor is not logged in.
Where wo开发者_如何学JAVAuld be the best place to limit access to /something in the controller or can it be added as part of the routes?
You must add in controller :before_filter and create action for that.
:before_filter :authenticate
def authenticate
redirect_to(registration_path) unless current_user.nil?
end
Also you can use :only or :except filter options. Or i did not understant question?
You should handle that in your controller. Routes decide where things go and then it is up to the controller to decide if you're allowed to go there.
You should have a general purpose authenticate
method in your ApplicationController that checks if someone is logged in and redirects them to a login page if they're not. Then in your specific controller:
class SomethingController < ApplicationController
before_filter :authenticate
def handler
#...
end
end
You can skip authentication for a specific handling with the :except
option:
before_filter :authenticate, :except => [ :this_one, :and_this_one ]
There are other options as well, see the filters section of the Action Controller Overview for details.
精彩评论