File size: 1,336 Bytes
3206347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { URLSearchParams } from 'url';
import getCurrentUser from '../common/get-current-user.js';

const verifyCredentials = async ($) => {
  const oauthRedirectUrlField = $.app.auth.fields.find(
    (field) => field.key == 'oAuthRedirectUrl'
  );
  const redirectUri = oauthRedirectUrlField.value;
  const params = new URLSearchParams({
    grant_type: 'authorization_code',
    code: $.auth.data.code,
    redirect_uri: redirectUri,
  });

  const headers = {
    Authorization: `Basic ${Buffer.from(
      $.auth.data.clientId + ':' + $.auth.data.clientSecret
    ).toString('base64')}`,
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  const response = await $.http.post(
    `https://oauth.pipedrive.com/oauth/token`,
    params.toString(),
    { headers }
  );

  const {
    access_token: accessToken,
    api_domain: apiDomain,
    expires_in: expiresIn,
    refresh_token: refreshToken,
    scope: scope,
    token_type: tokenType,
  } = response.data;

  await $.auth.set({
    accessToken,
    apiDomain,
    expiresIn,
    refreshToken,
    scope,
    tokenType,
  });

  const user = await getCurrentUser($);

  const screenName = [user.name, user.company_domain]
    .filter(Boolean)
    .join(' @ ');

  await $.auth.set({
    userId: user.id,
    screenName,
  });
};

export default verifyCredentials;