Sha256: 8afca8114125b65df8ac5732ee147fc60a72c6d08454be34c2ba9b02cd61be57

Contents?: true

Size: 1.19 KB

Versions: 27

Compression:

Stored size: 1.19 KB

Contents

class Marty::ApiAuth < Marty::Base
  has_mcfly

  KEY_SIZE = 19

  def self.generate_key
    SecureRandom.hex(KEY_SIZE)
  end

  class ApiAuthValidator < ActiveModel::Validator
    def validate(api)
      api.errors.add(:base, "API Key length must be #{KEY_SIZE*2}") if
        api.api_key && api.api_key.length != KEY_SIZE*2

      api.errors.add(:base, "Script Name must reference a valid script") unless
        Marty::Script.find_script(api.script_name, nil)
    end
  end

  before_validation do
    self.api_key = Marty::ApiAuth.generate_key if
      self.api_key.nil? || self.api_key.length == 0
  end

  validates_presence_of :app_name, :api_key, :script_name

  validates_with ApiAuthValidator

  mcfly_validates_uniqueness_of :api_key, scope: [:script_name]
  validates_uniqueness_of :app_name, scope: [:script_name,
                                             :obsoleted_dt]

  def self.authorized?(script_name, api_key)
    is_secured = where(script_name: script_name,
                       obsoleted_dt: 'infinity').exists?
    !is_secured || where(api_key: api_key,
                         script_name: script_name,
                         obsoleted_dt: 'infinity').pluck(:app_name).first
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
marty-2.3.15 app/models/marty/api_auth.rb
marty-2.3.14 app/models/marty/api_auth.rb
marty-2.3.13 app/models/marty/api_auth.rb
marty-2.3.12 app/models/marty/api_auth.rb
marty-2.3.11 app/models/marty/api_auth.rb
marty-2.3.10 app/models/marty/api_auth.rb
marty-2.3.9 app/models/marty/api_auth.rb
marty-2.3.8 app/models/marty/api_auth.rb
marty-2.3.7 app/models/marty/api_auth.rb
marty-2.3.5 app/models/marty/api_auth.rb
marty-2.3.4 app/models/marty/api_auth.rb
marty-2.1.5 app/models/marty/api_auth.rb
marty-2.3.2 app/models/marty/api_auth.rb
marty-2.3.1 app/models/marty/api_auth.rb
marty-2.3.0 app/models/marty/api_auth.rb
marty-2.1.4 app/models/marty/api_auth.rb
marty-2.1.3 app/models/marty/api_auth.rb
marty-2.1.2 app/models/marty/api_auth.rb
marty-2.1.1 app/models/marty/api_auth.rb
marty-2.1.0 app/models/marty/api_auth.rb