-
Notifications
You must be signed in to change notification settings - Fork 13
/
generalAuthorizer.js
48 lines (45 loc) · 1.25 KB
/
generalAuthorizer.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
const jsonwebtoken = require('jsonwebtoken');
const parseArn = arn => {
const [left, right] = arn.split('/', 2);
const [,, service, region, accountId, apiId] = left.split(':');
const [stage, method, resourcePath] = right.split('/');
return {
service, region, accountId, apiId, stage, method, resourcePath,
};
};
module.exports.handler = async event => {
const token = event.authorizationToken.split(' ')[1];
try {
const decodedToken = jsonwebtoken.verify(token, process.env.SECRET);
const { service, region, accountId, apiId, stage } = parseArn(event.methodArn);
const userId = decodedToken.sub;
return {
principalId: userId,
policyDocument: {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Resource: `arn:aws:${service}:${region}:${accountId}:${apiId}/${stage}/*`,
Action: ['execute-api:Invoke'],
},
],
}
};
} catch (err) {
console.error('error validating token', err);
return {
principalId: 'unknown',
policyDocument: {
Version: '2012-10-17',
Statement: [
{
Effect: 'Deny',
Resource: '*',
Action: [],
},
],
}
};
}
};