Sha256: 76cbcacd78a9916e751987b8a07798021c2c73d6b7fd176c0a152ff2701cdddc

Contents?: true

Size: 1.23 KB

Versions: 8

Compression:

Stored size: 1.23 KB

Contents

require 'pundit'

module JSONAPI
  module Authorization
    module PunditScopedResource
      extend ActiveSupport::Concern

      module ClassMethods
        def records(options = {})
          user_context = JSONAPI::Authorization.configuration.user_context(options[:context])
          ::Pundit.policy_scope!(user_context, _model_class)
        end
      end

      def records_for(association_name)
        record_or_records = @model.public_send(association_name)
        relationship = fetch_relationship(association_name)

        case relationship
        when JSONAPI::Relationship::ToOne
          record_or_records
        when JSONAPI::Relationship::ToMany
          user_context = JSONAPI::Authorization.configuration.user_context(context)
          ::Pundit.policy_scope!(user_context, record_or_records)
        else
          raise "Unknown relationship type #{relationship.inspect}"
        end
      end

      private

      def fetch_relationship(association_name)
        relationships = self.class._relationships.select do |_k, v|
          v.relation_name(context: context) == association_name
        end
        if relationships.empty?
          nil
        else
          relationships.values.first
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
jsonapi-authorization-3.0.2 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-3.0.1 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-3.0.0 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-2.0.0 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-1.0.0 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-1.0.0.beta2 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-1.0.0.beta1 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-1.0.0.alpha6 lib/jsonapi/authorization/pundit_scoped_resource.rb