Skip to content

Instantly share code, notes, and snippets.

@francorisso
Created October 1, 2021 10:19
Show Gist options
  • Save francorisso/4bbc467f36e68a917bf1e81a809d7627 to your computer and use it in GitHub Desktop.
Save francorisso/4bbc467f36e68a917bf1e81a809d7627 to your computer and use it in GitHub Desktop.
const jwt = require('jsonwebtoken');
const SECRET_KEY = process.env.JWT_SECRET;
const PERMISSION = {
principalId: 'user',
policyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: 'execute-api:Invoke',
Effect: 'Allow',
Resource: [
// fill here the resources
],
},
],
},
};
function extractTokenFromHeader(e) {
if (e.authorizationToken && e.authorizationToken.split(' ')[0] === 'Bearer') {
return e.authorizationToken.split(' ')[1];
} else {
return e.authorizationToken;
}
}
exports.createToken = ({ id, name, organization }) => {
const EXPIRES_IN = 60 * 60 * 1000;
return jwt.sign(
{
exp: Math.floor((Date.now() + EXPIRES_IN) / 1000),
customer: {
id,
name,
organization,
},
},
SECRET_KEY
);
};
exports.tokenValidation = async (event, ctx, callback) => {
try {
const token = extractTokenFromHeader(event);
const decoded = jwt.verify(token, SECRET_KEY);
ctx.customer = decoded.customer;
return callback(null, {
...PERMISSION,
principalId: decoded.customer.id,
});
} catch (e) {
return callback('Unauthorized');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment