Class: Otc::Request
- Inherits:
-
Object
show all
- Defined in:
- lib/otc/request.rb
Defined Under Namespace
Classes: ApiError, UnauthorizedError
Class Method Summary
collapse
Class Method Details
.base_uri(service:, path:) ⇒ Object
10
11
12
|
# File 'lib/otc/request.rb', line 10
def base_uri(service:, path:)
"https://#{service}.#{Configuration.region!}.otc.t-systems.com#{path}"
end
|
.get(service:, path:, authenticated_request: true) ⇒ Object
50
51
52
53
54
55
|
# File 'lib/otc/request.rb', line 50
def get(service:, path:, authenticated_request: true)
uri = URI.parse(base_uri(service: service, path: path))
= { "X-Auth-Token" => token } if authenticated_request
req = Net::HTTP::Get.new(uri.request_uri, )
send(req, uri)
end
|
.post(service:, path:, body:) ⇒ Object
57
58
59
60
61
62
|
# File 'lib/otc/request.rb', line 57
def post(service:, path:, body:)
uri = URI.parse(base_uri(service: service, path: path))
req = Net::HTTP::Post.new(uri.request_uri, "Content-Type" => "application/json;charset=utf8")
req.body = body
send(req, uri)
end
|
.send(req, uri) ⇒ Object
64
65
66
67
68
69
70
71
|
# File 'lib/otc/request.rb', line 64
def send(req, uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.request(req).tap do |response|
raise UnauthorizedError, "could not authorize request" if response.code == "401"
raise ApiError, "error during api call: #{response.body}" if response.code.to_i >= 300
end
end
|
.token ⇒ Object
returns the token if it is still valid (not older than 20 hours) else obtains a new token
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
|
# File 'lib/otc/request.rb', line 16
def token
latest_timestamp = @_token ? @_token[:timestamp] : nil
twenty_hours = 20 * 60 * 60
if latest_timestamp.nil? || latest_timestamp < (Time.now - twenty_hours).to_i
body = {
auth: {
identity: {
methods: ["password"],
password: {
user: {
name: Configuration.username!,
password: Configuration.password!,
domain: { name: Configuration.domainname! }
}
}
},
scope: {
project: { id: Configuration.project! }
}
}
}
response = post(service: "iam", path: "/v3/auth/tokens", body: body.to_json)
@_token = {
token: response.fetch("X-Subject-Token"),
timestamp: Time.now.to_i
}
end
@_token.fetch(:token)
end
|