-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecretsManager.js
More file actions
107 lines (91 loc) · 3.06 KB
/
Copy pathSecretsManager.js
File metadata and controls
107 lines (91 loc) · 3.06 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
104
105
106
107
'use strict'
const AWS = require('aws-sdk');
const https = require('https');
const querystring = require('querystring');
class SecretsManager {
/**
* Uses AWS Secrets Manager to retrieve a secret
*/
static async getSecret (secretName, region){
const config = { region : region }
let secretsManager = new AWS.SecretsManager(config);
try {
let secretValue = await secretsManager.getSecretValue({SecretId: secretName}).promise();
if ('SecretString' in secretValue) {
return secret = secretValue.SecretString;
} else {
let buff = new Buffer(secretValue.SecretBinary, 'base64');
return decodedBinarySecret = buff.toString('ascii');
}
} catch (err) {
throw err;
}
}
/**
* Uses HTTPS to get the new access token from refresh token
*/
static getNewAccessToken(token) {
return new Promise((resolve, reject) => {
const { postData, options } = preparePostDataAndOptions(token);
let req = https.request(options, (res) => {
handleResponse(res, resolve);
});
req.on('error', (err) => {
handleError(err, reject);
});
req.write(postData);
req.end();
});
}
static async updateSecret (secretName, region, newSecretValue){
const config = { region : region }
let secretsManager = new AWS.SecretsManager(config);
const params = {
SecretId: secretName,
SecretString: newSecretValue
};
try {
const result = await secretsManager.updateSecret(params).promise();
console.log(`Secret ${secretName} updated. ARN: ${result.ARN}`);
return result.ARN;
} catch (error) {
console.log(`Error updating secret ${secretName}: ${error}`);
throw error;
}
}
}
// functions
function preparePostDataAndOptions(refreshToken) {
let postData = querystring.stringify({
'grant_type': 'refresh_token',
'refresh_token': refreshToken,
'client_id':process.env.CLIENT_ID,
'client_secret':process.env.CLIENT_SECRET
});
let options = {
hostname: 'oauth.platform.intuit.com',
path: '/oauth2/v1/tokens/bearer',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData),
'Accept' : "application/json",
}
};
return { postData, options };
}
function handleResponse(res, resolve) {
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
}
resolve(body);
});
}
function handleError(err, reject) {
console.error('Error during HTTPS request', err);
reject(err);
}
module.exports = SecretsManager;