Sha256: 775c35aff53c4ff07701810be85c453855a4c2a56625ddfc6c46ac45ae7e3d00

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

module Ingress
  class PermissionRule
    attr_reader :action, :subject, :conditions

    def initialize(allows:, action:, subject:, conditions: nil)
      @allows = allows
      @action = action
      @subject = subject
      @conditions = [conditions].compact.flatten
    end

    def allows?
      @allows
    end

    def match?(given_action, given_subject, user, options = {})
      return false unless action_matches?(given_action)
      return false unless subject_matches?(given_subject)

      conditions_match?(user, given_subject, options)
    end

    private

    def action_matches?(given_action)
      given_action == action ||
        given_action == "*" ||
        "*" == action
    end

    def subject_matches?(given_subject)
      given_subject == subject ||
        given_subject.class == subject ||
        given_subject == "*" ||
        "*" == subject
    end

    def conditions_match?(user, given_subject, options)
      conditions.all? do |condition|
        if condition.arity == 2
          condition.call(user, given_subject)
        else
          condition.call(user, given_subject, options)
        end
      end
    rescue => e
      log_error(e)
      false
    end

    def log_error(error)
      if defined?(Rails)
        Rails.logger.error error.message
        Rails.logger.error error.backtrace.join("\n")
      else
        $stderr.puts error.message
        $stderr.puts error.backtrace.join("\n")
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ingress-0.3.0 lib/ingress/permission_rule.rb