Search code examples
ruby-on-railsruby-on-rails-3cancan

Admin Authorization with CanCan


A have a bunch of controllers with the Admin namespace. I want to restrict access to these unless the user is an admin. Is there a way to do this using CanCan without having to call unauthorized! in every method of every controller?


Solution

  • Add an application controller to your namespace and a before filter to it.

    class ApplicationController < ActionController::Base
    end
    
    class Admin::ApplicationController < ApplicationController 
      # these goes in your namespace admin folder
      before_filter :check_authorized
    
      def check_authorized
        redirect_to root_path unless can? :admin, :all
      end
    end
    
    class SomeadminController < Admin::ApplicationController
       def some_action
         # do_stuff
       end
    end