1 | const qs = require('querystring')
|
2 |
|
3 | class OAuth {
|
4 | constructor(client) {
|
5 | this.client = client
|
6 | }
|
7 |
|
8 | getAuthorizationUrl(newData) {
|
9 | const initialParams = {}
|
10 | if (this.client.clientId) initialParams.client_id = this.client.clientId
|
11 | if (this.client.redirectUri) initialParams.redirect_uri = this.client.redirectUri
|
12 |
|
13 | const params = Object.assign({}, initialParams, newData)
|
14 | return `https://app.hubspot.com/oauth/authorize?${qs.stringify(params)}`
|
15 | }
|
16 |
|
17 | getAccessToken(newData) {
|
18 | const initialData = {
|
19 | grant_type: 'authorization_code',
|
20 | client_id: this.client.clientId,
|
21 | client_secret: this.client.clientSecret,
|
22 | redirect_uri: this.client.redirectUri,
|
23 | }
|
24 | const form = Object.assign({}, initialData, newData)
|
25 |
|
26 | return this.client._request({
|
27 | method: 'POST',
|
28 | path: '/oauth/v1/token',
|
29 | form,
|
30 | })
|
31 | }
|
32 |
|
33 | refreshAccessToken(newData) {
|
34 | const initialData = {
|
35 | grant_type: 'refresh_token',
|
36 | client_id: this.client.clientId,
|
37 | client_secret: this.client.clientSecret,
|
38 | redirect_uri: this.client.redirectUri,
|
39 | refresh_token: this.client.refreshToken,
|
40 | }
|
41 | const form = Object.assign({}, initialData, newData)
|
42 |
|
43 | return this.client
|
44 | ._request({
|
45 | method: 'POST',
|
46 | path: '/oauth/v1/token',
|
47 | form,
|
48 | })
|
49 | .then((results) => {
|
50 | const updatedAt = Math.floor(Date.now() / 1000)
|
51 | this.client.setAccessToken(results.access_token, results.expires_in, updatedAt)
|
52 | return results
|
53 | })
|
54 | }
|
55 |
|
56 | getPortalInfo(accessToken) {
|
57 | const token = accessToken || this.client.accessToken
|
58 | return this.client._request({
|
59 | method: 'GET',
|
60 | path: `/oauth/v1/access-tokens/${token}`,
|
61 | })
|
62 | }
|
63 | }
|
64 |
|
65 | module.exports = OAuth
|