Sha256: a30c68c4de4564dbdc9d1912a8bbd49a9513f6f39b77d07c73ad6392ded6a7d8

Contents?: true

Size: 1.11 KB

Versions: 2

Compression:

Stored size: 1.11 KB

Contents

# frozen_string_literal: true

module Pragma
  module Macro
    def self.Policy(name: :default, action: nil)
      step = ->(input, options) { Policy.for(input, name, options, action) }
      [step, name: "policy.#{name}"]
    end

    module Policy
      class << self
        def for(input, name, options, action = nil)
          policy = options["policy.#{name}.class"].new(options['current_user'], options['model'])

          action_name = action.is_a?(Proc) ? action.call(options) : action
          action_name ||= input.class.operation_name

          options["result.policy.#{name}"] = Trailblazer::Operation::Result.new(
            policy.send("#{action_name}?"),
            'policy' => policy
          )

          unless options["result.policy.#{name}"].success?
            handle_unauthorized!(options)
            return false
          end

          true
        end

        private

        def handle_unauthorized!(options)
          options['result.response'] = Pragma::Operation::Response::Forbidden.new.decorate_with(
            Pragma::Decorator::Error
          )
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pragma-2.3.0 lib/pragma/macro/policy.rb
pragma-2.2.0 lib/pragma/macro/policy.rb