Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thomasmichaelwallace/e722efeb713d6aeb7a61d15cb09af42f to your computer and use it in GitHub Desktop.
Save thomasmichaelwallace/e722efeb713d6aeb7a61d15cb09af42f to your computer and use it in GitHub Desktop.
A very simple custom authoriser.
const yourAuthorizationLogic = require('./yourAuthorizationLogic');
const generateIamPolicy = (principalId, Effect, Resource, context) => ({
principalId,
policyDocument: {
Version: '2012-10-17',
Statement: [{ Action: 'execute-api:Invoke', Effect, Resource }],
},
context,
});
const auth = (event, context, callback) => {
console.debug(`Attempting auth for ${JSON.stringify(event)}`);
const { methodArn, authorizationToken } = event;
return yourAuthorizationLogic(authorizationToken)
.then((user /* = { id, someContext, someMoreContext, ... } */) => {
console.info(`Authoized ${authorizationToken} as ${JSON.stringify(user)}`);
return callback(null, generateIamPolicy(user.id, 'Allow', methodArn, user));
// alternatively you can return a 403 using:
// callback(null, generateIamPolicy('user', 'Deny', methodArn)); to 403
})
.catch((error) => {
if (!error) {
return callback('Unauthorized'); // 401.
}
console.error(`Unable to authorise because of: ${JSON.stringify(error)}`);
return callback('Server Error'); // 500.
});
};
module.exports = { auth };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment