We want to protect our admin pages, ensuring that only admins can access them. We've been using filter methods in our controllers, but this has been forgotten a few times. Is there a higher level we can implement this authorization check at to protect all of our admin pages?
We can use a routing constraint which control visibility at the routing level
and can wrap all of our admin routes. [Clearance][] provides routing
constraints for SignedIn and SignedOut users, but these can be further
customized by passing them a block which will receive the current_user
instance.
admin_constraint =
  Clearance::Constraints::SignedIn.new(&:admin?)
constraints admin_constraint do
  namespace :admin do
    resources :users
    resources :projects do
      resources :milestones
    end
  end
end
You can see a real usage of this in [Upcase's admin routes][].
You can read more about advance routing constraints in the [Advanced Routing Constraints][] section of the Rails routing guide.
In addition, you can read about [Clearance's routing constraints][] to see more detail on how they work.
[Advanced Routing Constraints]: http://guides.rubyonrails.org/routing.html#advanced-constraints [Clearance's routing constraints]: https://github.com/thoughtbot/clearance#access-control [Upcase's admin routes]: https://github.com/thoughtbot/upcase/blob/6e3c292891422e2c163430f485863bafa772a68d/config/routes/admin.rb [Clearance]: https://github.com/thoughtbot/clearance
Return to Flashcard Results