forked from ManageIQ/manageiq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_manager.rb
67 lines (52 loc) · 1.57 KB
/
token_manager.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require 'securerandom'
#
# Supporting class for Managing Tokens, i.e. Authentication Tokens for REST API, etc.
#
class TokenManager
RESTRICTED_OPTIONS = [:expires_on]
DEFAULT_NS = "default"
def initialize(namespace = DEFAULT_NS, options = {})
@namespace = namespace
@options = {:token_ttl => -> { 10.minutes }}.merge(options)
end
def gen_token(token_options = {})
token = SecureRandom.hex(16)
ttl = token_options.delete(:token_ttl_override) || token_ttl
token_data = {:token_ttl => ttl, :expires_on => Time.now.utc + ttl}
token_store.write(token,
token_data.merge!(prune_token_options(token_options)),
:expires_in => token_ttl)
token
end
def reset_token(token)
token_data = token_store.read(token)
return {} if token_data.nil?
ttl = token_data[:token_ttl]
token_data[:expires_on] = Time.now.utc + ttl
token_store.write(token,
token_data,
:expires_in => ttl)
end
def token_get_info(token, what = nil)
return {} unless token_valid?(token)
token_data = token_store.read(token)
return nil if token_data.nil?
what.nil? ? token_data : token_data[what]
end
def token_valid?(token)
!token_store.read(token).nil?
end
def invalidate_token(token)
token_store.delete(token)
end
def token_ttl
@options[:token_ttl].call
end
private
def token_store
TokenStore.acquire(@namespace, token_ttl)
end
def prune_token_options(token_options = {})
token_options.except(*RESTRICTED_OPTIONS)
end
end