Sha256: 8032c1e49397cac6b3c3f02087f0824f5834ed11feefa600decd5bf0218b20ae

Contents?: true

Size: 1.27 KB

Versions: 2

Compression:

Stored size: 1.27 KB

Contents

module Permits
  module Policy
    class Base
      include ActiveModel::Model
      include ActiveModel::Attributes
      include ActiveModel::Validations

      attribute :owner
      attribute :resource

      validates :owner, presence: true
      validates :resource, presence: true

      def self.authorize!(owner, resource, action)
        policy = new(owner: owner, resource: resource)
        if policy.authorized?(action)
          true
        else
          raise ::Permits::Policy::UnauthorizedError
        end
      end

      def self.authorized?(owner, resource, action)
        policy = new(owner: owner, resource: resource)
        policy.authorized?(action)
      end

      def authorized?(action)
        return false unless valid?

        if respond_to?("#{action}?")
          return send("#{action}?")
        else
          has_action_permissions?(action)
        end
      end

      private

      def has_action_permissions?(action)
        return false unless owner_permissions.respond_to?("permits_#{action}")

        return owner_permissions.send("permits_#{action}").where(resource: resource).exists?
      end

      def owner_permissions
        @owner_permissions ||= ::Permits::Permission.active.where(owner: owner).includes(:resource)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
permits-0.1.1 lib/permits/policy/base.rb
permits-0.1.0 lib/permits/policy/base.rb