Sha256: 387eb3a44b216c9e877a0345a4317201afa7ed69e359cec8f3c3198c8e8e7c35

Contents?: true

Size: 1.47 KB

Versions: 10

Compression:

Stored size: 1.47 KB

Contents

require 'jwt'

module PandaPal
  class ApiCall < ActiveRecord::Base
    # TODO Add Rate Limiting?

    def self.decode_jwt(jwt)
      jwt_payload, jwt_header = ::JWT.decode(jwt, Rails.application.secret_key_base, true, { algorithm: 'HS256' })
      jwt_payload
    end

    def self.from_jwt(jwt)
      jwt = decode_jwt(jwt) if jwt.is_a?(String)
      ApiCall.find(jwt['api_call_id'])
    end

    before_validation on: [:update] do
      errors.add(:expiration, 'is not changeable') if expiration_changed?
    end

    def call(params, internal: false)
      if !internal && uses_remaining != nil
        self.uses_remaining -= 1
        if uses_remaining <= 0
          destroy!
        else
          save!
        end
      end

      prc = eval("->(p) {
        #{logic}
      }")

      prc.call(params)
    end

    def call_url(host: nil, params: {}, **kwargs)
      func_params = logic.scan(/\bp\[:(\w+)\]/).flatten
      phash = {}
      func_params.each.with_index do |p, i|
        phash[p.to_sym] = params[p.to_sym] || "TODO"
      end

      PandaPal::Engine.routes.url_helpers.call_logic_url(self, token: jwt_token(**kwargs), only_path: !host, host: host, **phash, format: nil)
    end

    def jwt_token(expiration: self.expiration)
      payload = {
        api_call_id: id,
        organization_id: Organization.current&.id,
      }
      payload[:exp] = expiration.iso8601 if expiration.present?
      ::JWT.encode(payload, Rails.application.secret_key_base, 'HS256')
    end

  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
panda_pal-5.6.7 app/models/panda_pal/api_call.rb
panda_pal-5.6.7.beta2 app/models/panda_pal/api_call.rb
panda_pal-5.6.7.beta1 app/models/panda_pal/api_call.rb
panda_pal-5.6.6 app/models/panda_pal/api_call.rb
panda_pal-5.6.5 app/models/panda_pal/api_call.rb
panda_pal-5.6.4 app/models/panda_pal/api_call.rb
panda_pal-5.6.3 app/models/panda_pal/api_call.rb
panda_pal-5.6.2 app/models/panda_pal/api_call.rb
panda_pal-5.6.1 app/models/panda_pal/api_call.rb
panda_pal-5.6.0 app/models/panda_pal/api_call.rb