开发者

Rails, Devise gem, authenticate with routes or in controller? Which is best?

So Devise has what seems to be two methods of accomplishing the same thing, firstly it seems the classic way of protecting a unauthorized user from accessing a controllers action would be something like this in my controller:

before_filter :authentic开发者_运维问答ate_user!

But I've been seeing this done in the routes.rb more often now also like so:

authenticate :user do
  resources :reports
end

Which one should I be using?


Normally I'd agree, routes should be a simple mapping and not contain complex logic. But the Devise method (second example in OP), while perhaps not the best way to protect against unauthorized access, is useful for at least one very common use case - namely, routing to one "home page" for a signed in user (e.g., a dashboard), and to another home page for a non-signed in user (e.g., a signup page). This is IMO standard enough to merit a direct routing mechanism, which allows you to easily handle errors with a redirect_to root_path and have it go to the right spot with a single redirect (one HTTP(s) transaction), preserving flash messages (which would likely be lost in a second redirect inside a before_filter), without sprinkling lots of additional code in your controllers.

The "authenticate[d]" method is described very succinctly here


That logic belongs to the controller, not routes. Routes are just what they are, routes. It's not good to put some logic into them.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜