forked from uphold/rest-api-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersonal-access-token.js
More file actions
103 lines (85 loc) · 2.32 KB
/
personal-access-token.js
File metadata and controls
103 lines (85 loc) · 2.32 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* 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.USERNAME + ":" + process.env.PASSWORD).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 list of authentication methods, using basic authentication (username and password).
*/
export async function getAuthenticationMethods() {
try {
const response = await axios.request({
method: "GET",
url: `${process.env.BASE_URL}/v0/me/authentication_methods`,
headers: {
Authorization: `Basic ${auth}`,
},
});
return response.data;
} catch (error) {
formatError(error);
}
}
/**
* Create a Personal Access Token (PAT), using basic authentication (username and password).
* The time-based one-time password (TOTP) parameter
* is typically provided by an OTP application, e.g. Google Authenticator.
*/
export async function createNewPAT(totp) {
const headers = {
Authorization: `Basic ${auth}`,
"content-type": "application/json",
};
// Set OTP headers if the totp parameter is passed.
if (totp.OTPMethodId) {
headers["OTP-Method-Id"] = totp.OTPMethodId;
headers["OTP-Token"] = totp.OTPToken;
}
try {
const response = await axios.request({
method: "POST",
url: `${process.env.BASE_URL}/v0/me/tokens`,
data: { description: process.env.PAT_DESCRIPTION },
headers,
});
return response.data;
} catch (error) {
formatError(error);
}
}
/**
* Get list of Personal Access Tokens (PATs), using an existing PAT.
*/
export async function getUserPATs(accessToken) {
try {
const response = await axios.request({
method: "GET",
url: `${process.env.BASE_URL}/v0/me/tokens`,
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
formatError(error);
}
}