Pragma::Policy

Build Status Dependency Status Code Climate Coveralls

Policies provide fine-grained access control for your API resources.

They are built on top of the Pundit gem.

Installation

Add this line to your application's Gemfile:

gem 'pragma-policy'

And then execute:

$ bundle

Or install it yourself as:

$ gem install pragma-policy

Usage

To create a policy, simply inherit from Pragma::Policy::Base:

module API
  module V1
    module Article
      class Policy < Pragma::Policy::Base
      end
    end
  end
end

By default, the policy does not return any objects when scoping and forbids all operations.

You can start customizing your policy by defining a scope and operation predicates:

module API
  module V1
    module Article
      class Policy < Pragma::Policy::Base
        class Scope < Pragma::Policy::Base::Scope
          def resolve
            scope.where('published = ? OR author_id = ?', true, user.id)
          end
        end

        def show?
          record.published? || record.author_id == user.id
        end

        def update?
          record.author_id == user.id
        end

        def destroy?
          record.author_id == user.id
        end
      end
    end
  end
end

You are ready to use your policy!

Retrieving Records

To retrieve all the records accessible by a user, use the .accessible_by class method:

posts = API::V1::Article::Policy::Scope.new(user, Article.all).resolve

Authorizing Operations

To authorize an operation, first instantiate the policy, then use the predicate methods:

policy = API::V1::Article::Policy.new(user, post)
fail 'You cannot update this post!' unless policy.update?

Since raising when the operation is forbidden is so common, we provide bang methods a shorthand syntax. Pragma::Policy::NotAuthorizedError is raised if the predicate method returns false:

policy = API::V1::Article::Policy.new(user, post)
policy.update! # raises if the user cannot update the post

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/pragmarb/pragma-policy.

License

The gem is available as open source under the terms of the MIT License.