Sha256: 0002f2175e784a6793cdfef73575a89f38d91d4c7757b5bf0a904f86fc3b51a3

Contents?: true

Size: 1.18 KB

Versions: 37

Compression:

Stored size: 1.18 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[:base] =
        "API Key length must be #{KEY_SIZE*2}" if
        api.api_key && api.api_key.length != KEY_SIZE*2

      api.errors[:base] =
        "Script Name must reference a valid script" if
        Marty::Script.find_script(api.script_name, nil).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').exists?
  end
end

Version data entries

37 entries across 37 versions & 1 rubygems

Version Path
marty-1.0.27 app/models/marty/api_auth.rb
marty-1.0.26 app/models/marty/api_auth.rb
marty-1.0.25 app/models/marty/api_auth.rb
marty-1.0.24 app/models/marty/api_auth.rb
marty-1.0.23 app/models/marty/api_auth.rb
marty-1.0.22 app/models/marty/api_auth.rb
marty-1.0.20 app/models/marty/api_auth.rb
marty-1.0.19 app/models/marty/api_auth.rb
marty-1.0.18 app/models/marty/api_auth.rb
marty-1.0.17 app/models/marty/api_auth.rb
marty-1.0.15 app/models/marty/api_auth.rb
marty-1.0.14 app/models/marty/api_auth.rb
marty-1.0.13 app/models/marty/api_auth.rb
marty-1.0.12 app/models/marty/api_auth.rb
marty-1.0.11 app/models/marty/api_auth.rb
marty-1.0.10 app/models/marty/api_auth.rb
marty-1.0.9 app/models/marty/api_auth.rb
marty-1.0.8 app/models/marty/api_auth.rb
marty-1.0.7 app/models/marty/api_auth.rb
marty-1.0.6 app/models/marty/api_auth.rb