Class: Brightpearl::Auth

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

Class Method Summary collapse

Class Method Details

.oauth_url(state:, redirect_uri:) ⇒ Object



3
4
5
# File 'lib/brightpearl/auth.rb', line 3

def self.oauth_url(state:, redirect_uri:)
  "https://oauth.brightpearl.com/authorize/#{Brightpearl.config.}?response_type=code&client_id=#{Brightpearl.config.app_ref}&redirect_uri=#{redirect_uri}&state=#{state}"
end

.request_token(auth_token:, redirect_uri:) ⇒ Object



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

def self.request_token(auth_token:, redirect_uri:)
  token_endpoint = "https://oauth.brightpearl.com/token/#{Brightpearl.config.}"
  body = {
    grant_type: "authorization_code",
    code: auth_token,
    client_id: Brightpearl.config.app_ref,
    client_secret: Brightpearl.config.app_secret,
    redirect_uri: redirect_uri, # SAME AS THE ONE USED ON oauth_url
  }

  response = HTTParty.post(token_endpoint, 
    body: body,
    headers: {
      'Content-Type' => 'application/x-www-form-urlencoded',
      'charset' => 'utf-8'
    }
  )
  json = JSON.parse(response.body)
  raise Brightpearl::RequestError.new(json["error_description"] || json["error"], response: json, status: 400) if response.code == 400

  return {
    payload: json,
    data: {
      token: json["access_token"],
      refresh_token: json["refresh_token"],
      api_domain: json["api_domain"],
    }
  }
end

.use_refresh_token(refresh_token: nil, autoupdate: true) ⇒ Object



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

def self.use_refresh_token(refresh_token: nil, autoupdate: true)
  token_endpoint = "https://oauth.brightpearl.com/token/#{Brightpearl.config.}"
  rtoken = refresh_token || Brightpearl.config.refresh_token
  body = {
    grant_type: "refresh_token",
    refresh_token: rtoken,
    client_id: Brightpearl.config.app_ref,
  }
  response = HTTParty.post(token_endpoint, 
    body: body,
    headers: { "Content-Type": "application/x-www-form-urlencoded", 'charset' => 'utf-8' }
  )

  json = JSON.parse(response.body)
  if json["access_token"] && autoupdate
    Brightpearl.config.token = json["access_token"]
    Brightpearl.config.refresh_token = json["refresh_token"]
  end

  return {
    payload: json,
    data: {
      token: json["access_token"],
      refresh_token: json["refresh_token"],
      api_domain: json["api_domain"]
    }
  }

end