Completed
Push — master ( 4bde78...e5a194 )
by John
01:03
created

Client.authorize_code()   A

Complexity

Conditions 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 5
rs 9.4285
1
require 'base64'
2
require 'faraday'
3
require 'faraday_middleware'
4
require 'faraday_middleware/oauth2_refresh'
5
require 'oauth2'
6
7
module RingCentralSdk::REST
8
  class Client
9
10
    ACCESS_TOKEN_TTL  = 600             # 10 minutes
11
    REFRESH_TOKEN_TTL = 36000           # 10 hours
12
    REFRESH_TOKEN_TTL_REMEMBER = 604800 # 1 week
13
    ACCOUNT_PREFIX    = '/account/'
14
    ACCOUNT_ID        = '~'
15
    AUTHZ_ENDPOINT    = '/restapi/oauth/authorize'
16
    TOKEN_ENDPOINT    = '/restapi/oauth/token'
17
    REVOKE_ENDPOINT   = '/restapi/oauth/revoke'
18
    API_VERSION       = 'v1.0'
19
    URL_PREFIX        = '/restapi'
20
21
    attr_reader :app_config
22
    attr_reader :http
23
    attr_reader :oauth2client
24
    attr_reader :token
25
    attr_reader :user_agent
26
    attr_reader :messages
27
28
    def initialize(app_key='', app_secret='', server_url=RingCentralSdk::RC_SERVER_SANDBOX, opts={})
29
      init_attributes()
30
      app_config = RingCentralSdk::REST::ConfigApp.new(app_key, app_secret, server_url, opts)
31
      app_config(app_config)
32
33
      if opts.key?(:username) && opts.key?(:password)
34
        extension = opts.key?(:extension) ? opts[:extension] : ''
35
        authorize_password(opts[:username], extension, opts[:password])
36
      end
37
38
      @messages = RingCentralSdk::REST::Messages.new(self)
39
    end
40
41
    def app_config(app_config)
42
      @app_config = app_config
43
      @oauth2client = new_oauth2_client()
44
    end
45
46
    def init_attributes()
47
      @token = nil
48
      @http = nil
49
      @user_agent = get_user_agent()
50
    end
51
52
    def api_version_url()
53
      return @app_config.server_url + URL_PREFIX + '/' + API_VERSION 
54
    end
55
56
    def create_url(url, add_server=false, add_method=nil, add_token=false)
57
      built_url = ''
58
      has_http = !url.index('http://').nil? && !url.index('https://').nil?
59
60
      if add_server && ! has_http
61
        built_url += @app_config.server_url
62
      end
63
64
      if url.index(URL_PREFIX).nil? && ! has_http
65
        built_url += URL_PREFIX + '/' + API_VERSION + '/'
66
      end
67
68
      if url.index('/') == 0
69
        if built_url =~ /\/$/
70
          built_url += url.gsub(/^\//, '')
71
        else
72
          built_url += url
73
        end
74
      else # no /
75
        if built_url =~ /\/$/
76
          built_url += url
77
        else
78
          built_url += '/' + url
79
        end
80
      end
81
82
      return built_url
83
    end
84
85
    def create_urls(urls, add_server=false, add_method=nil, add_token=false)
86
      unless urls.is_a?(Array)
87
        raise "URLs is not an array"
88
      end
89
      built_urls = []
90
      urls.each do |url|
91
        built_urls.push(create_url(url, add_server, add_method, add_token))
92
      end
93
      return built_urls
94
    end
95
96
    def authorize_url(opts={})
97
      @oauth2client.auth_code.authorize_url(_add_redirect_uri(opts))
98
    end
99
100
    def authorize_code(code, opts={})
101
      token = @oauth2client.auth_code.get_token(code, _add_redirect_uri(opts))
102
      set_token(token)
103
      return token
104
    end
105
106
    def _add_redirect_uri(opts={})
107
      if !opts.key?(:redirect_uri) && @app_config.redirect_url.to_s.length > 0
108
        opts[:redirect_uri] = @app_config.redirect_url.to_s
109
      end
110
      return opts
111
    end
112
113
    def authorize_password(username, extension='', password='', remember=false)
114
      token = @oauth2client.password.get_token(username, password, {
115
        extension: extension,
116
        headers: { 'Authorization' => 'Basic ' + get_api_key() } })
117
      set_token(token)
118
      return token
119
    end
120
121
    def authorize_user(user, remember=false)
122
      authorize_password(user.username, user.extension, user.password)
123
    end
124
125
    def set_token(token)
126
      if token.is_a?(Hash)
127
        token = OAuth2::AccessToken::from_hash(@oauth2client, token)
128
      end
129
130
      unless token.is_a?(OAuth2::AccessToken)
131
        raise "Token is not a OAuth2::AccessToken"
132
      end
133
134
      @token = token
135
136
      @http = Faraday.new(:url => api_version_url()) do |conn|
137
        conn.request :oauth2_refresh, @token
138
        conn.request :json
139
        conn.request :url_encoded
140
        conn.headers['User-Agent'] = @user_agent
141
        conn.headers['Rc-User-Agent'] = @user_agent
142
        conn.response :json, :content_type => /\bjson$/
143
        conn.adapter Faraday.default_adapter
144
      end
145
    end
146
147
    def new_oauth2_client()
148
      return OAuth2::Client.new(@app_config.key, @app_config.secret,
149
        site: @app_config.server_url,
150
        authorize_url: AUTHZ_ENDPOINT,
151
        token_url: TOKEN_ENDPOINT)
152
    end
153
154
    def set_oauth2_client(client=nil)
155
      if client.nil?
156
        @oauth2client = new_oauth2_client()
157
      elsif client.is_a?(OAuth2::Client)
158
        @oauth2client = client
159
      else
160
        fail "client is not an OAuth2::Client"
161
      end
162
    end
163
164
    def get_api_key()
165
      api_key = (@app_config.key.is_a?(String) && @app_config.secret.is_a?(String)) \
166
        ? Base64.encode64("#{@app_config.key}:#{@app_config.secret}").gsub(/[\s\t\r\n]/,'') : ''
167
      return api_key
168
    end
169
170
    def send_request(request_sdk = {})
171
      if request_sdk.is_a?(Hash)
172
        request_sdk = RingCentralSdk::REST::Request::Simple.new(request_sdk)
173
      elsif !request_sdk.is_a?(RingCentralSdk::REST::Request::Base)
174
        fail 'Request is not a RingCentralSdk::REST::Request::Base'
175
      end
176
177
      res = nil
178
179
      method = request_sdk.method.downcase
180
      case method
181
      when 'delete'
182
        res = @http.delete { |req| req = inflate_request(req, request_sdk) }
183
      when 'get'
184
        res = @http.get { |req| req = inflate_request(req, request_sdk) }
185
      when 'post'
186
        res = @http.post { |req| req = inflate_request(req, request_sdk) }
187
      when 'put'
188
        res = @http.put { |req| req = inflate_request(req, request_sdk) }
189
      else
190
        fail "#{method} not support"
191
      end
192
      return res
193
    end
194
195
    def inflate_request(req_faraday, req_sdk)
196
      req_faraday.url req_sdk.url
197
      req_faraday.body = req_sdk.body if req_sdk.body
198
      if req_sdk.params.is_a? Hash 
199
        req_sdk.params.each { |k,v| req_faraday.params[k] = v }
200
      end
201
      if req_sdk.headers.is_a? Hash 
202
        req_sdk.headers.each { |k,v| req_faraday.headers[k] = v }
203
      end
204
205
      ct = req_sdk.content_type
206
      if !ct.nil? && ct.to_s.length > 0
207
        req_faraday.headers['Content-Type'] = ct.to_s
208
      end
209
      return req_faraday
210
    end
211
212
    def get_user_agent()
213
      ua = "ringcentral-sdk-ruby/#{RingCentralSdk::VERSION} %s/%s %s" % [
214
        (RUBY_ENGINE rescue nil or "ruby"),
215
        RUBY_VERSION,
216
        RUBY_PLATFORM
217
      ]
218
      return ua.strip
219
    end
220
221
    def create_subscription()
222
      return RingCentralSdk::REST::Subscription.new(self)
223
    end
224
225
    alias_method :authorize, :authorize_password
226
    alias_method :login, :authorize_password
227
    private :api_version_url
228
  end
229
end
230