Skip to content

Instantly share code, notes, and snippets.

@diegofcornejo
Created October 15, 2022 03:07
Show Gist options
  • Save diegofcornejo/3b0b7c4ad44ebb3a733bcc02eb6cf14f to your computer and use it in GitHub Desktop.
Save diegofcornejo/3b0b7c4ad44ebb3a733bcc02eb6cf14f to your computer and use it in GitHub Desktop.
AWS Lambda - APIGateway create API Key and Usage plan key
'use strict';
var AWS = require('aws-sdk');
var apigateway = new AWS.APIGateway();
var docClient = new AWS.DynamoDB.DocumentClient();
function generateApiKey() {
return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, function(c) {
var r = Math.random() * 36 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(36);
});
}
exports.handler = async(event, context, callback) => {
let body = JSON.parse(event.body);
var done = function(code, message) {
let response = {
"statusCode": code,
"body": JSON.stringify(message)
};
callback(null, response);
};
let params = {
description: body.description,
enabled: body.status,
name: body.name,
value: generateApiKey()
};
var createApiKey = await apigateway.createApiKey(params).promise();
if (createApiKey.id) {
let params = {
keyId: createApiKey.id,
keyType: 'API_KEY',
usagePlanId: body.plan
};
var createUsagePlanKey = await apigateway.createUsagePlanKey(params).promise();
if (createUsagePlanKey.id) {
let params = {
TableName: "api-key",
Item: { "user": body.user, "id": createApiKey.value, "createdAt":new Date().getTime(), "name":body.name }
};
var insertDB = await docClient.put(params).promise();
if (Object.keys(insertDB).length > 0) {
done(400, insertDB);
}
else {
done(200, createApiKey);
}
}
else {
done(400, createUsagePlanKey);
}
}
else {
done(400, createApiKey);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment