Class: OpenC3::AuthModel

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

Constant Summary collapse

PRIMARY_KEY =
'OPENC3__TOKEN'
SESSIONS_KEY =
'OPENC3__SESSIONS'
TOKEN_CACHE_TIMEOUT =
5
SESSION_CACHE_TIMEOUT =
5
MIN_TOKEN_LENGTH =
8
@@token_cache =
nil
@@token_cache_time =
nil
@@session_cache =
nil
@@session_cache_time =
nil

Class Method Summary collapse

Class Method Details

.generate_sessionObject



82
83
84
85
86
# File 'lib/openc3/models/auth_model.rb', line 82

def self.generate_session
  token = SecureRandom.urlsafe_base64(nil, false)
  Store.hset(SESSIONS_KEY, token, Time.now.iso8601)
  return token
end

.hash(token) ⇒ Object



94
95
96
# File 'lib/openc3/models/auth_model.rb', line 94

def self.hash(token)
  Digest::SHA2.hexdigest token
end

.logoutObject



88
89
90
91
92
# File 'lib/openc3/models/auth_model.rb', line 88

def self.logout
  Store.del(SESSIONS_KEY)
  @@sessions_cache = nil
  @@sessions_cache_time = nil
end

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



71
72
73
74
75
76
77
78
79
80
# File 'lib/openc3/models/auth_model.rb', line 71

def self.set(token, old_token, key = PRIMARY_KEY)
  raise "token must not be nil or empty" if token.nil? or token.empty?
  raise "token must be at least 8 characters" if token.length < MIN_TOKEN_LENGTH

  if 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

.set?(key = PRIMARY_KEY) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/openc3/models/auth_model.rb', line 41

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

.verify(token) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/openc3/models/auth_model.rb', line 45

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

  time = Time.now
  return true if @@session_cache and (time - @@session_cache_time) < SESSION_CACHE_TIMEOUT and @@session_cache[token]
  token_hash = hash(token)
  return true if @@token_cache and (time - @@token_cache_time) < TOKEN_CACHE_TIMEOUT and @@token_cache == token_hash

  # Check sessions
  @@session_cache = Store.hgetall(SESSIONS_KEY)
  @@session_cache_time = time
  return true if @@session_cache[token]

  # Check Direct password
  @@token_cache = Store.get(PRIMARY_KEY)
  @@token_cache_time = time
  return true if @@token_cache == token_hash

  # Handle a service password - Generally only used by ScriptRunner
  # TODO: Replace this with temporary service tokens
  service_password = ENV['OPENC3_SERVICE_PASSWORD']
  return true if service_password and service_password == token

  return false
end