Sha256: 1f0fb36c7def418c055fe6cafe6f5fb9fa1c36aa318d42917ef93030d7d44d1c

Contents?: true

Size: 1.22 KB

Versions: 6

Compression:

Stored size: 1.22 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({}) == association_name
        end
        if relationships.empty?
          nil
        else
          relationships.values.first
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
jsonapi-authorization-1.0.0.alpha5 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-1.0.0.alpha4 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-1.0.0.alpha3 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-1.0.0.alpha2 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-1.0.0.alpha1 lib/jsonapi/authorization/pundit_scoped_resource.rb
jsonapi-authorization-0.8.2 lib/jsonapi/authorization/pundit_scoped_resource.rb