Chris Keele
Chris Keele

Reputation: 3453

Cancan with database roles and abilities: AuthorizationNotPerformed

I'm building a site-wide cancan auth system. Just to get very simple validation of my attempts, I'm initializing my test cases every time I try to hit a page:

# application_controller.rb
class ApplicationController < ActionController::Base
  admin = Role.new(name: :admin, is_default: true)
  admin.permissions << Permission.create(action: :manage, subject_class: :all)
  admin.save
  current_user=User.create!
  # users automatically get associations to all roles with `is_default: true`

  check_authorization
end

Only controllers with skip_authorization_check are letting me through, all others throw the AuthorizationNotPerformed error:

CanCan::AuthorizationNotPerformed in ExampleAuthEngin::PermissionsController#index

This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check.

What am I doing wrong?

Upvotes: 2

Views: 3308

Answers (1)

Adam
Adam

Reputation: 3158

Within the controller, you need to either call load_and_authorize_resource (at the class level), or within individual actions call authorize! :action, resource where :action and resource are the things to be tested. load_and_authorize_resource adds before_filters to the controller that instantiates an instance variable for the resource (where the method of instantiation is based on the action, and the resource to load is based on the controller name) and also adds a filter to authorize the loaded resource, authorizing on either :read, :create, :update, or :destroy, based on the action that's being hit.

You can read more about it here.

Upvotes: 3

Related Questions