forked from laardee/serverless-authentication-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
authorizeHandler.js
42 lines (36 loc) · 1.26 KB
/
authorizeHandler.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
'use strict';
// Config
require('dotenv').config();
const slsAuth = require('serverless-authentication');
const config = slsAuth.config;
const utils = slsAuth.utils;
// Authorize
//
// event.methodArn: "arn:aws:execute-api:<regionId>:<accountId>:<apiId>/<stage>/<method>/<resourcePath>/<userId>/<function>"
// ...will be parsed as...
// const resource = "arn:aws:execute-api:<regionId>:<accountId>:<apiId>/<stage>/*/<resourcePath>/<userId>/*"
const authorize = (event, callback) => {
const resourceParts = event.methodArn.split('/');
const stage = resourceParts[1];
let resource = `${resourceParts[0]}/${stage}/*/${resourceParts[3]}/${resourceParts[4]}`;
if (resourceParts.length > 5) {
resource += '/*';
}
let error = null;
let policy;
const authorizationToken = event.authorizationToken;
if (authorizationToken) {
try {
// this example uses simple expiration time validation
const providerConfig = config({ provider: '', stage });
const data = utils.readToken(authorizationToken, providerConfig.token_secret);
policy = utils.generatePolicy(data.id, 'Allow', resource);
} catch (err) {
error = 'Unauthorized';
}
} else {
error = 'Unauthorized';
}
callback(error, policy);
};
exports = module.exports = authorize;