-
Notifications
You must be signed in to change notification settings - Fork 39
/
authorization_token.rb
89 lines (77 loc) · 2.28 KB
/
authorization_token.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
module MangoPay
module AuthorizationToken
# See http://docs.mangopay.com/api-references/authenticating/
class Manager
class << self
def storage
@@storage ||= StaticStorage.new
end
def storage= (storage)
@@storage = storage
end
def get_token
token = storage.get
env_key = get_environment_key_for_token
if token.nil? || token['timestamp'].nil? || token['timestamp'] <= Time.now || token['environment_key'] != env_key
token = MangoPay.request(:post, "/#{MangoPay.version_code}/oauth/token", {}, {}, {}, Proc.new do |req|
cfg = MangoPay.configuration
req.basic_auth cfg.client_id, cfg.client_apiKey
req.body = 'grant_type=client_credentials'
req.add_field('Content-Type', 'application/x-www-form-urlencoded')
end)
token['timestamp'] = Time.now + (token['expires_in'].to_i - 10)
token['environment_key'] = env_key
storage.store token
end
token
end
def get_environment_key_for_token
cfg = MangoPay.configuration
key = "#{cfg.root_url}|#{cfg.client_id}|#{cfg.client_apiKey}"
key = Digest::MD5.hexdigest(key)
key
end
end
end
class StaticStorage
def get
@@token ||= nil
end
def store(token)
@@token = token
end
end
class FileStorage
require 'yaml'
@temp_dir
def initialize(temp_dir = nil)
@temp_dir = temp_dir || MangoPay.configuration.temp_dir
if !@temp_dir
raise "Path to temporary folder is not defined"
end
end
def get
begin
f = File.open(file_path, File::RDONLY)
f.flock(File::LOCK_SH)
txt = f.read
f.close
YAML.load(txt) || nil
rescue Errno::ENOENT
nil
end
end
def store(token)
File.open(file_path, File::RDWR | File::CREAT, 0644) do |f|
f.flock(File::LOCK_EX)
f.truncate(0)
f.rewind
f.puts(YAML.dump(token))
end
end
def file_path
File.join(@temp_dir, "MangoPay.AuthorizationToken.FileStore.tmp")
end
end
end
end