Class: AliExpress::Auth

Inherits:
Base
  • Object
show all
Defined in:
lib/aliexpress/auth.rb

Class Method Summary collapse

Methods inherited from Base

access_token, client_id, client_secret, currency, get, language, logger, post, refresh_token

Class Method Details

.authorize(state = nil) ⇒ Object



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
# File 'lib/aliexpress/auth.rb', line 4

def authorize(state = nil)
  oauth_client = client
  oauth_params = params(state || SecureRandom.hex(24))
  oauth_params[:_aop_signature] = sign(oauth_params)
  logger.debug oauth_params
  url = oauth_client.authorize_url(oauth_params)

  if RUBY_PLATFORM == 'x86_64-darwin16'
    begin
      system('open', url)
    rescue Exception => e # rubocop:disable Lint/RescueException
      logger.debug "Call to open failed: #{e.message}"
    end
  end

  $stdout.puts "Open #{url} in your browser, and then enter the code below."
  $stdout.print 'authorization_code> '
  authorization_code = $stdin.gets

  token = oauth_client.get_token(
    code: authorization_code,
    grant_type: 'authorization_code',
    need_refresh_token: 'true',
    parse: :json,
    redirect_uri: 'urn:ietf:wg:oauth:2.0:oob'
  ).to_hash

  token
end

.refreshObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/aliexpress/auth.rb', line 34

def refresh
  if refresh_token
    response = post(
      api_call: 'getToken',
      api_namespace: 'system.oauth2',
      api_version: '1',
      # protocol: 'http',
      auth: false,
      sign: false,
      params: {
        grant_type: 'refresh_token',
        client_id: client_id,
        client_secret: client_secret,
        refresh_token: refresh_token
      }
    )
    AliExpress.access_token = response['access_token']
  else
    raise Exception, 'You must have a refresh_token to refresh authorization. You need to call `AliExpress::Auth.authorize` and follow the instructions to generate one.'
  end
end