-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.rb
68 lines (56 loc) · 1.9 KB
/
auth.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
require 'base64'
require 'openssl'
module Naver
module Searchad
module Api
module Auth
class CustomerAcccountCredentials
TIMESTAMP_HEADER = 'X-Timestamp'.freeze
API_KEY_HEADER = 'X-API-KEY'.freeze
CUSTOMER_HEADER = 'X-Customer'.freeze
SIGNATURE_HEADER = 'X-Signature'.freeze
attr_reader :api_key
attr_reader :api_secret
attr_reader :customer_id
def initialize(api_key, api_secret, customer_id)
@api_key = api_key
@api_secret = api_secret
@customer_id = customer_id
end
def apply(hash, request_uri, method)
timestamp = Time.now.to_i
hash[TIMESTAMP_HEADER] = timestamp
hash[API_KEY_HEADER] = api_key
hash[CUSTOMER_HEADER] = customer_id
hash[SIGNATURE_HEADER] = generate_signature(api_secret, request_uri, method, timestamp)
end
private
def generate_signature(secret, request_uri, method, timestamp)
method = method.to_s.upcase if method.is_a?(Symbol)
Base64.encode64(OpenSSL::HMAC.digest(
OpenSSL::Digest::SHA256.new,
secret,
[timestamp, method, request_uri].join('.')
)).gsub("\n", '')
end
end
class DefaultCredentials
API_KEY_ENV_VAR = 'NAVER_API_KEY'.freeze
API_SECRET_ENV_VAR = 'NAVER_API_SECRET'.freeze
CUSTOMER_ID_ENV_VAR = 'NAVER_API_CLIENT_ID'.freeze
def self.from_env
CustomerAcccountCredentials.new(
ENV[API_KEY_ENV_VAR],
ENV[API_SECRET_ENV_VAR],
ENV[CUSTOMER_ID_ENV_VAR]
)
end
end
def get_application_default
DefaultCredentials.from_env
end
module_function :get_application_default
end
end
end
end