Class: Leash::Provider::AuthCode

Inherits:
Ohm::Model
  • Object
show all
Defined in:
app/models/leash/provider/auth_code.rb

Constant Summary collapse

MAX_ASSIGN_TRIES =
20

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.assign!(app_name, owner) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'app/models/leash/provider/auth_code.rb', line 14

def self.assign!(app_name, owner)
  tries = 0
  auth_code = nil

  loop do
    begin
      auth_code = SecureRandom.urlsafe_base64(32)
      timestamp = Time.now.to_i
      self.create app_name: app_name, owner: owner_key(owner), auth_code: auth_code, created_at: timestamp
      break

    rescue Ohm::UniqueIndexViolation => e
      tries += 1

      fail if tries > MAX_ASSIGN_TRIES
    end
  end

  auth_code
end

.find_by_auth_code(auth_code) ⇒ Object



41
42
43
# File 'app/models/leash/provider/auth_code.rb', line 41

def self.find_by_auth_code(auth_code)
  self.find(auth_code: auth_code).first
end

.owner_key(owner) ⇒ Object



46
47
48
49
50
51
52
# File 'app/models/leash/provider/auth_code.rb', line 46

def self.owner_key(owner)
  if owner.is_a? ActiveRecord::Base
    "#{owner.class.name}##{owner.id}"
  else
    owner
  end
end

.valid?(auth_code) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'app/models/leash/provider/auth_code.rb', line 36

def self.valid?(auth_code)
  self.find(auth_code: auth_code).size != 0
end

Instance Method Details

#owner_instanceObject



55
56
57
58
59
# File 'app/models/leash/provider/auth_code.rb', line 55

def owner_instance
  owner_klass, owner_id = owner.split("#", 2)

  owner_klass.classify.constantize.find(owner_id)
end