-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathclient-credentials-flow.js
73 lines (60 loc) · 1.57 KB
/
client-credentials-flow.js
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Dependencies.
*/
import axios from "axios";
import dotenv from "dotenv";
import path from "path";
// Dotenv configuration.
dotenv.config({ path: path.resolve() + "/.env" });
// Authentication credentials.
const auth = Buffer.from(process.env.CLIENT_ID + ":" + process.env.CLIENT_SECRET).toString("base64");
/**
* Format API error response for printing in console.
*/
function formatError(error) {
const responseStatus = `${error.response.status} (${error.response.statusText})`;
console.log(
`Request failed with HTTP status code ${responseStatus}`,
JSON.stringify({
url: error.config.url,
response: error.response.data
}, null, 2)
);
throw error;
}
/**
* Get a new access token, using client credentials authentication (client ID and secret).
*/
export async function getAccessToken() {
try {
const response = await axios.request({
method: "POST",
url: `${process.env.BASE_URL}/oauth2/token`,
data: "grant_type=client_credentials",
headers: {
Authorization: `Basic ${auth}`,
"content-type": "application/x-www-form-urlencoded",
},
});
return response.data;
} catch (error) {
formatError(error);
}
}
/**
* Get data about the currently authenticated user.
*/
export async function getUserInfo(accessToken) {
try {
const response = await axios.request({
method: "GET",
url: `${process.env.BASE_URL}/v0/me`,
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
formatError(error);
}
}