forked from diegozanon/serverless-notifications
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
67 lines (56 loc) · 1.81 KB
/
handler.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
'use strict';
const AWS = require('aws-sdk');
const iot = new AWS.Iot();
const sts = new AWS.STS();
const roleName = 'serverless-notifications';
module.exports.auth = (event, context, callback) => {
// get the endpoint address
iot.describeEndpoint({}, (err, data) => {
if (err) return callback(err);
const iotEndpoint = data.endpointAddress;
const region = getRegion(iotEndpoint);
// get the account id which will be used to assume a role
sts.getCallerIdentity({}, (err, data) => {
if (err) return callback(err);
const params = {
RoleArn: `arn:aws:iam::${data.Account}:role/${roleName}`,
RoleSessionName: getRandomInt().toString()
};
// assume role returns temporary keys
sts.assumeRole(params, (err, data) => {
if (err) return callback(err);
const res =
buildResponseObject(iotEndpoint,
region,
data.Credentials.AccessKeyId,
data.Credentials.SecretAccessKey,
data.Credentials.SessionToken);
callback(null, res);
});
});
});
};
const buildResponseObject = (iotEndpoint, region, accessKey, secretKey, sessionToken) => {
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
iotEndpoint: iotEndpoint,
region: region,
accessKey: accessKey,
secretKey: secretKey,
sessionToken: sessionToken
})
};
};
const getRegion = (iotEndpoint) => {
const partial = iotEndpoint.replace('.amazonaws.com', '');
const iotIndex = iotEndpoint.indexOf('iot');
return partial.substring(iotIndex + 4);
};
// Get random Int
const getRandomInt = () => {
return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
};