Class: OpenC3::AuthModel

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

Constant Summary collapse

PRIMARY_KEY =
'OPENC3__TOKEN'
SERVICE_KEY =
'OPENC3__SERVICE__TOKEN'
TOKEN_CACHE_TIMEOUT =
5
@@token_cache =
nil
@@token_cache_time =
nil
@@service_token_cache =
nil
@@service_token_cache_time =
nil

Class Method Summary collapse

Class Method Details

.is_set?(key = PRIMARY_KEY) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/openc3/models/auth_model.rb', line 37

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

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



63
64
65
66
67
68
69
70
71
# File 'lib/openc3/models/auth_model.rb', line 63

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



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/openc3/models/auth_model.rb', line 41

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

  token_hash = hash(token)
  return true if @@token_cache and (Time.now - @@token_cache_time) < TOKEN_CACHE_TIMEOUT and @@token_cache == token_hash
  return true if @@service_token_cache and (Time.now - @@service_token_cache_time) < TOKEN_CACHE_TIMEOUT and @@service_token_cache == token_hash and permission != 'admin'

  @@token_cache = Store.get(PRIMARY_KEY)
  @@token_cache_time = Time.now
  return true if @@token_cache == token_hash

  @@service_token_cache = Store.get(SERVICE_KEY)
  @@service_token_cache_time = @@token_cache_time
  if ENV['OPENC3_SERVICE_PASSWORD'] and hash(ENV['OPENC3_SERVICE_PASSWORD']) != @@service_token_cache
    set_hash = hash(ENV['OPENC3_SERVICE_PASSWORD'])
    OpenC3::Store.set(SERVICE_KEY, set_hash)
    @@service_token_cache = set_hash
  end
  return true if @@service_token_cache == token_hash and permission != 'admin'
  return false
end