avo icon indicating copy to clipboard operation
avo copied to clipboard

Add `:action_policy` authorization driver

Open adrianthedev opened this issue 2 years ago • 1 comments

Feature

Using this From here

Current workarounds

Screenshots or screen recordings

Additional context

adrianthedev avatar Aug 23 '23 14:08 adrianthedev

This is basically the same as what I've been using.

module Avo
  module Services
    module AuthorizationClients
      class ActionPolicyClient
        include ::ActionPolicy::Behaviour

        authorize :user
        attr_accessor :user

        def authorize(user, record, action, policy_class: nil)
          return if policy(user, record).nil?

          self.user = user
          authorize!(record, to: action, with: policy_class)
        rescue ActionPolicy::Unauthorized => error
          raise NotAuthorizedError, error.message
        end

        def policy(user, record)
          policy!(user, record)
        rescue NoPolicyError
          nil
        end

        def policy!(user, record)
          self.user = user
          policy_for(record:)
        rescue ActionPolicy::NotFound => error
          raise NoPolicyError, error.message
        end

        def apply_policy(user, model, policy_class: nil)
          policy = if policy_class.present?
            policy_class.new(model, user:)
          else
            policy!(user, model)
          end

          policy.apply_scope(model, type: :relation)
        end
      end
    end
  end
end

I wonder if, rather than overriding the initializer of the base Policy class, we ought have a method within the individual clients that initializes the policy in the manner expected by the auth method.

dhnaranjo avatar Sep 18 '23 22:09 dhnaranjo