-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathget_workspace.mjs
More file actions
70 lines (54 loc) · 1.98 KB
/
get_workspace.mjs
File metadata and controls
70 lines (54 loc) · 1.98 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
import fs from 'fs/promises';
/**
* This program prints the current workspace using credentials stored in files
*/
const credsFile = 'creds.json'
const aacURLFile = 'aac_url.txt'
async function main() {
const accessToken = await getAccessToken();
const aacURL = (await fs.readFile(aacURLFile)).toString().trim();
console.log(await getCurrentWorkspace(aacURL, accessToken));
}
main();
/**
* This function reads the access and refresh token from the credentials file,
* refreshes the access token,
* and writes the new tokens back to the credentials file
*
* It returns a new access token that can be used to call APIs
*/
async function getAccessToken() {
// Load the credentials from their JSON file
const oldCreds = JSON.parse(await fs.readFile(credsFile));
// Get the second part of the access token, which is its payload
const payload = oldCreds.access_token.split('.')[1]
// Decode the base64-encoded access token
const info = JSON.parse(atob(payload))
// Create the body for the refresh request
const body = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: oldCreds.refresh_token,
client_id: info.client_id,
});
// Make the refresh request
const response = await fetch(`${info.iss}/token`, {
body,
method: 'POST'
});
const newCreds = await response.json();
// Overwrite the contents of the credentials file with the response of the refresh request, which includes the new access and refresh tokens
fs.writeFile(credsFile, JSON.stringify(newCreds));
return newCreds.access_token;
}
/**
* Gets the current workspace, and returns it as an object
*/
async function getCurrentWorkspace(aacURL, accessToken) {
// These headers are necessary in every request to the AAC API
const headers = {
'Authorization': `Bearer ${accessToken}`,
'User-Agent': 'myApp', // Describe your application here
}
const response = await fetch(`${aacURL}/iam/v1/workspaces/current`, { headers })
return await response.json()
}