开发者

With Rails 3, What's the easiest way to protect an entire site from un-authenticated users?

I'm using Devise for authentication for my site. An unauthenticated visitor should be able to only see: the welcome page, the sign-up page, and the login page. To unauthenticated visitors, all other pages/routes would be wholly inaccessible.

I looked at Cancan, but that seems like much, much more than I need.

I saw something else that suggested doing it at the Apache level, but life is way to short to be mucking around with web server settings.

I saw an article or two on using a session or user based before_filter, but it looks like I would have to modify each method in each controller.

Is there some other approach? It would be great if I could identify my routes as those publicly accessible and those requiring authentication. Is that possible? Or can I easily disable a complete controller based on current_user?

Just look开发者_如何学Going for something that is very simple and straightforward. Extra credit for something that errors-out gracefully. :-)


Just add a method to Application Controller that forbids access to nonauthenticated users (using before_filter) and overwrite this method for controllers where you want to give them access.

So in application controller:

before_filter :only_authenticated_users_are_welcome

def only_authenticated_users_are_welcome
  !user.blank?
end

And to grant access to some pages and in their controller:

def only_authenticated_users_are_welcome
  true
end

Or add some more logic to grant access only to some actions within the controller.


Agree with klew's answer, but instead of overriding the definition of only_authenticated_users_are_welcome, you can:

skip_before_filter :only_authenticated_users_are_welcome, :except => [:foo, :bar]

in controllers which should not be protected, and note the use of :except to indicate methods for which the before_filter should not be skipped. You can also use :only => [:foo, :bar] to indicate the skip should only be for the selected methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜