Using except with filter access to all for Declarative Authorization
March 26, 2014One of the problems with using Declarative Authorization for controlling access to controller methods in your Ruby on Rails application is that the function filter_access_to
does not have an except or skip option. This means that if you have five methods in your controller and only want to protect four of them you have to list them specifically, which can become a bit tedious.
However, the workaround is quite easy and quite logical. In your authorization_rules.rb
file you simply add the method you want to skip authorization on to the guest role. There are of course other way and patterns to do this as well, but it seems like a quite common question to want to use the following pattern.
# This is not supported by Declarative Authorization since it simply does not have an except option.
filter_access_to :all, except => [:show]
Read the full details on filter_access_to
Here is a full example of an easy and maintainable workaround
# Example controller
class ExampleController < ApplicationController
filter_access_to :all
def index
end
def show
end
def new
end
def create
end
def edit
end
def update
end
end
# authorization_rules.rb
authorization do
role :guest do
has_permission_on :exampel, to => [:show]
end
role :user do
has_permission_on :example, to => [:index, :new, :create, :edit, :update]
# or as an alternative and maybe more speaking for this example
has_permission_on :example, to => :all
end
end
This will allow everyone to access your show method and only users to access all the other methods without specifically listing all the methods in your controller you want to protect after filter_access_to.