Class: Cosmos::AuthModel

Inherits:
Object show all
Defined in:
lib/cosmos/models/auth_model.rb

Constant Summary collapse

PRIMARY_KEY =
'COSMOS__TOKEN'
SERVICE_KEY =
'COSMOS__SERVICE__TOKEN'

Class Method Summary collapse

Class Method Details

.is_set?(key = PRIMARY_KEY) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/cosmos/models/auth_model.rb', line 28

def self.is_set?(key = PRIMARY_KEY)
  Store.exists(key) == 1
end

.set(token, old_token, key = PRIMARY_KEY) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/cosmos/models/auth_model.rb', line 49

def self.set(token, old_token, key = PRIMARY_KEY)
  raise "token must not be nil or empty" if token.nil? or token.empty?

  if is_set?(key)
    raise "old_token must not be nil or empty" if old_token.nil? or old_token.empty?
    raise "old_token incorrect" unless verify(old_token)
  end
  Store.set(key, hash(token))
end

.verify(token, permission: nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/cosmos/models/auth_model.rb', line 32

def self.verify(token, permission: nil)
  return false if token.nil? or token.empty?

  token_hash = hash(token)
  return true if Store.get(PRIMARY_KEY) == token_hash

  service_hash = Store.get(SERVICE_KEY)
  if ENV['COSMOS_SERVICE_PASSWORD'] and hash(ENV['COSMOS_SERVICE_PASSWORD']) != service_hash
    set_hash = hash(ENV['COSMOS_SERVICE_PASSWORD'])
    Cosmos::Store.set(SERVICE_KEY, set_hash)
    service_hash = set_hash
  end
  return true if service_hash == token_hash and permission != 'admin'

  return false
end