diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000..e6174548 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,6 @@ +module.exports = { + trailingComma: "es5", + tabWidth: 2, + semi: true, + singleQuote: false, +}; diff --git a/.prettierrc.json b/.prettierrc.json deleted file mode 100644 index f0eb61e0..00000000 --- a/.prettierrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "trailingComma": "es5", - "tabWidth": 2, - "semi": true, - "singleQuote": false -} diff --git a/package.json b/package.json index 765d0d30..1dadc0f3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "devDependencies": { - "@types/node": "^12.12.7", + "@types/node": "^12.20.55", "@typescript-eslint/eslint-plugin": "^5.45.0", "eslint": "^8.28.0", "eslint-config-standard-with-typescript": "^23.0.0", @@ -9,8 +9,12 @@ "eslint-plugin-n": "^15.5.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^6.1.1", + "ncp": "^2.0.0", "typescript": "^4.9.3" }, + "files": [ + "logics" + ], "dependencies": { "@iarna/toml": "^2.2.5", "@types/inquirer": "^8.2.1", @@ -28,7 +32,8 @@ "main": "dist/bin/init.js", "scripts": { "clean": "shx rm -rf dist/*", - "build": "tsc && npm run format:write && npm run lint:fix", + "build": "tsc && npm run format:write && npm run lint:fix && npm run build:logics", + "build:logics": "ncp src/resources/logics dist/src/resources/logics", "watch": "tsc --watch", "prepack": "npm run clean && npm run build ", "format:check": "prettier --check .", diff --git a/src/resources/logics.ts b/src/resources/logics.ts index 7f9f68e9..5ec5728d 100644 --- a/src/resources/logics.ts +++ b/src/resources/logics.ts @@ -1,617 +1,33 @@ -export const LambdaLogics: Record> = { - "nodejs14.x": { - EmailAuthModule_PreSignUp: `exports.lambdaHandler = async event => { - event.response.autoConfirmUser = false; - event.response.autoVerifyEmail = false; - return event; - };`, - EmailAuthModule_DefineAuthChallenge: `exports.lambdaHandler = async event => { - if (event.request.session && - event.request.session.length >= 3 && - event.request.session.slice(-1)[0].challengeResult === false) { - // The user provided a wrong answer 3 times; fail auth - event.response.issueTokens = false; - event.response.failAuthentication = true; - } else if (event.request.session && - event.request.session.length && - event.request.session.slice(-1)[0].challengeResult === true) { - // The user provided the right answer; succeed auth - event.response.issueTokens = true; - event.response.failAuthentication = false; - } else { - // The user did not provide a correct answer yet; present challenge - event.response.issueTokens = false; - event.response.failAuthentication = false; - event.response.challengeName = 'CUSTOM_CHALLENGE'; - } - - return event; - }; - `, - EmailAuthModule_CreateAuthChallenge: ` - exports.lambdaHandler = async event => { - const connectionString = process.env.DB_CONNECTION_STRING - let password; - if(!event.request.session || !event.request.session.length) { - // new session, so fetch password from the db - const username = event.request.userAttributes.email; - const user =event.request.userAttributes.username; - const password = event.request.userAttributes.password; - } else { - const previousChallenge = event.request.session.slice(-1)[0]; - password = previousChallenge.challengeMetadata.match(/PASSWORD-(d*)/)[1]; - } - // This is sent back to the client app - event.response.publicChallengeParameters = { username: event.request.userAttributes.email }; - - // Add the secret login code to the private challenge parameters - // so it can be verified by the "Verify Auth Challenge Response" trigger - event.response.privateChallengeParameters = { password }; - - // Add the secret login code to the session so it is available - // in a next invocation of the "Create Auth Challenge" trigger - event.response.challengeMetadata = \`PASSWORD-\${password}\`; - return event; - - }`, - EmailAuthModule_VerifyAuthChallengeResponse: `const md5 = require('md5'); - exports.lambdaHandler = async event => { - const expectedAnswer = event.request.privateChallengeParameters.password; - if (md5(event.request.challengeAnswer) === expectedAnswer) { - event.response.answerCorrect = true; - } else { - event.response.answerCorrect = false; - } - return event; - };`, - EmailAuthModule_SignUpFunctions: ` - let response; - const aws = require('aws-sdk'); - const UserPoolID = process.env.UserPoolID - const UserPoolClientID = process.env.UserPoolClientID - exports.lambdaHandler = async (event, context) => { - try { - if(event.body!==undefined){ - event=JSON.parse(event.body) - } - // const ret = await axios(url); - const cognito = new aws.CognitoIdentityServiceProvider(); - const params = { - ClientId: UserPoolClientID, - Username:event.emailId, - Password: event.Password, - UserAttributes:[ - { - Name: 'email', - Value: event.emailId, - }, - { - Name: "name", - Value: event.name - }] - }; - console.log(params) - let res=await cognito.signUp(params).promise(); - response = { - 'statusCode': 200, - 'body': JSON.stringify(res) - } - } catch (err) { - console.log(err); - response = { - 'statusCode': 200, - 'body': JSON.stringify(err) - } - } - - return response - };`, - EmailAuthModule_ResendCode: ` - let response; - const aws = require('aws-sdk'); - const UserPoolID = process.env.UserPoolID - const UserPoolClientID = process.env.UserPoolClientID - exports.lambdaHandler = async (event, context) => { - try { - if(event.body!==undefined){ - event=JSON.parse(event.body) - } - const cognito = new aws.CognitoIdentityServiceProvider(); - - letparams = { - ClientId: UserPoolClientID, - Username: event.emailId - } - let res=await cognito.resendConfirmationCode(params).promise(); - - - response = { - 'statusCode': 200, - 'body': JSON.stringify({ - message: res, - - }) - } - } catch (err) { - console.log(err); - response = { - 'statusCode': 200, - 'body': JSON.stringify(err) - } - } - - return response - }; - `, - EmailAuthModule_ConfirmUser: ` - let response; - const aws = require('aws-sdk'); - const dynamoDB = new aws.DynamoDB.DocumentClient(); - const UserTable = process.env.userinfoTable - const UserPoolID = process.env.UserPoolID - const UserPoolClientID = process.env.UserPoolClientID - async function addUserData(userData) { - try { - console.log("[INFO] addUserData input",userData) - const params = { - TableName: UserTable, - Item: userData - - }; - letItems = await dynamoDB.put(params).promise(); - console.log("[INFO] addUserData output",Items) - return Items - - } - catch (err) { - throw err; - } - } - exports.lambdaHandler = async (event, context) => { - try { - if(event.body!==undefined){ - event=JSON.parse(event.body) - } - const cognito = new aws.CognitoIdentityServiceProvider(); - letparams = { - ClientId: UserPoolClientID, - ConfirmationCode: event.Code, - Username: event.emailId - } - let res=await cognito.confirmSignUp(params).promise(); - - letparams1 = { - UserPoolId: UserPoolID, - AttributesToGet: ["email","name","sub"], - - } - - - res=await cognito.listUsers(params1).promise(); - let user={} - let Attributes={} - res["Users"].map(ele=>{ - - Attributes = ele["Attributes"].find(ele=>ele.Name==="email"&&ele.Value==event.emailId) - if (Attributes!==undefined) { - ele["Attributes"].map(ele=>{ - user[ele.Name]=ele.Value - }) - } - - - }) - console.log(user) - await addUserData(user) - response = { - 'statusCode': 200, - 'body': JSON.stringify({ - message: res, - - }) - } - // await addUserData() - } catch (err) { - console.log(err); - response = { - 'statusCode': 200, - 'body': JSON.stringify(err) - } - } - - return response - }; - `, - EmailAuthModule_ConfirmForgotPassword: ` - let response; - const UserPoolID = process.env.UserPoolID - const UserPoolClientID = process.env.UserPoolClientID - const aws = require('aws-sdk'); - exports.lambdaHandler = async (event, context) => { - try { - if(event.body!==undefined){ - event=JSON.parse(event.body) - } - const cognito = new aws.CognitoIdentityServiceProvider(); - letparams = { - ClientId: UserPoolClientID, - ConfirmationCode: event.Code, - Username: event.emailId, - Password: event.password, /* required */ - } - let res=await cognito.confirmForgotPassword(params).promise(); - response = { - 'statusCode': 200, - 'body': JSON.stringify({ - message: res, - - }) - } - } catch (err) { - console.log(err); - response = { - 'statusCode': 200, - 'body': JSON.stringify(err) - } - } - - return response - }; - `, - EmailAuthModule_ForgotPassword: ` - let response; - const UserPoolID = process.env.UserPoolID - const UserPoolClientID = process.env.UserPoolClientID - const aws = require('aws-sdk'); - exports.lambdaHandler = async (event, context) => { - try { - if(event.body!==undefined){ - event=JSON.parse(event.body) - } - const cognito = new aws.CognitoIdentityServiceProvider(); - letparams = { - ClientId: UserPoolClientID, - Username: event.emailId - } - let res=await cognito.forgotPassword(params).promise(); - response = { - 'statusCode': 200, - 'body': JSON.stringify({ - message: res, - - }) - } - } catch (err) { - console.log(err); - response = { - 'statusCode': 200, - 'body': JSON.stringify(err) - } - } - - return response - }; - `, - EmailAuthModule_AuthorizerFunction: ` - import jwt from 'jsonwebtoken'; +import * as fs from "fs"; +import * as path from "path"; - // By default, API Gateway authorizations are cached (TTL) for 300 seconds. - // This policy will authorize all requests to the same API Gateway instance where the - // request is coming from, thus being efficient and optimising costs. - const generatePolicy = (principalId, methodArn) => { - const apiGatewayWildcard = methodArn.split('/', 2).join('/') + '/*'; - - return { - principalId, - policyDocument: { - Version: '2012-10-17', - Statement: [ - { - Action: 'execute-api:Invoke', - Effect: 'Allow', - Resource: apiGatewayWildcard, - }, - ], - }, - }; - }; - - export async function handler(event, context) { - if (!event.authorizationToken) { - throw 'Unauthorized'; - } - - const token = event.authorizationToken.replace('Bearer ', ''); - - try { - const claims = jwt.verify(token, process.env.AUTH0_PUBLIC_KEY); - const policy = generatePolicy(claims.sub, event.methodArn); - - return { - ...policy, - context: claims - }; - } catch (error) { - console.log(error); - throw 'Unauthorized'; - } - };`, - s3_lambda: `exports.lambdaHandler = async event => { - if (event.request.session && - event.request.session.length >= 3 && - event.request.session.slice(-1)[0].challengeResult === false) { - // The user provided a wrong answer 3 times; fail auth - event.response.issueTokens = false; - event.response.failAuthentication = true; - } else if (event.request.session && - event.request.session.length && - event.request.session.slice(-1)[0].challengeResult === true) { - // The user provided the right answer; succeed auth - event.response.issueTokens = true; - event.response.failAuthentication = false; - } else { - // The user did not provide a correct answer yet; present challenge - event.response.issueTokens = false; - event.response.failAuthentication = false; - event.response.challengeName = 'CUSTOM_CHALLENGE'; - } - - return event; - }; - `, - EmailAuthModule_Users: ` - - let response; - const aws = require('aws-sdk'); - const dynamoDB = new aws.DynamoDB.DocumentClient(); - const UserTable = process.env.userinfoTable - const UserPoolID = process.env.UserPoolID - const UserPoolClientID = process.env.UserPoolClientID - async function getUserData(id) { - try { - const params = { - TableName: UserTable, - Key: { email: id }, - }; - let{ Item } = await dynamoDB.get(params).promise(); - console.log("[INFO] getUserData output",Item) - return Item; - } - catch (err) { - throw err; - } - } - async function deleteUserData(id) { - try { - const params = { - TableName: UserTable, - Key: { email: id }, - }; - let{ Item } = await dynamoDB.delete(params).promise(); - console.log("[INFO] getUserData output",Item) - return Item; - } - catch (err) { - throw err; - } - } - async function addUserData(userData) { - try { - console.log("[INFO] addUserData input",userData) - const params = { - TableName: UserTable, - Item: userData - }; - letItems = await dynamoDB.put(params).promise(); - console.log("[INFO] addUserData output",Items) - return Items - } - catch (err) { - throw err; - } - } - exports.lambdaHandler = async (event, context) => { - try { - let res - console.log("events ",event.pathParameters["email"]) - if (event.httpMethod=="GET"){ - res =await getUserData(event.pathParameters["email"]) - - } - if (event.httpMethod=="PUT"){ - if(event.body!==undefined){ - event=JSON.parse(event.body) - } - res =await addUserData(event) - res={"message":"data updated"} - } - if (event.httpMethod=="DELETE"){ - res =await deleteUserData(event.pathParameters["email"]) - res={"message":"data deleted"} - - } - response = { - 'statusCode': 200, - 'body': JSON.stringify({ - data: res, - - }) - } - } catch (err) { - console.log(err); - response = { - 'statusCode': 200, - 'body': JSON.stringify(err) - } - } - - return response - }; - - `, - crud: `let response; - const aws = require('aws-sdk'); - const dynamoDB = new aws.DynamoDB.DocumentClient(); - const Table = process.env.Table - async function getData(id) { - try { - const params = { - TableName: Table, - Key: { id: id }, - }; - let{ Item } = await dynamoDB.get(params).promise(); - console.log("[INFO] getData output",Item) - return Item; - } - catch (err) { - throw err; - } - } - async function deleteData(id) { - try { - const params = { - TableName: Table, - Key: { id: id }, - }; - let{ Item } = await dynamoDB.delete(params).promise(); - console.log("[INFO] getData output",Item) - return Item; - } - catch (err) { - throw err; - } - } - async function addupdateData(userData) { - try { - console.log("[INFO] addupdateData input",userData) - const params = { - TableName: Table, - Item: userData - }; - letItems = await dynamoDB.put(params).promise(); - console.log("[INFO] addupdateData output",Items) - return Items - } - catch (err) { - throw err; - } - } - exports.lambdaHandler = async (event, context) => { - try { - let res - console.log("events ") - if (event.httpMethod=="POST"){ - if(event.body!==undefined){ - event=JSON.parse(event.body) - } - res =await addupdateData(event) - res={"message":"data updated"} - } - if (event.httpMethod=="GET"){ - res =await getData(event.pathParameters["id"]) - - } - if (event.httpMethod=="PUT"){ - if(event.body!==undefined){ - event=JSON.parse(event.body) - } - res =await addupdateData(event) - res={"message":"data updated"} - } - if (event.httpMethod=="DELETE"){ - res =await deleteData(event.pathParameters["id"]) - res={"message":"data deleted"} - - } - response = { - 'statusCode': 200, - 'body': JSON.stringify({ - data: res, - - }) - } - } catch (err) { - console.log(err); - response = { - 'statusCode': 200, - 'body': JSON.stringify(err) - } - } - - return response - };`, - rdstable: `const secret=process.env.Secret - const clustername=process.env.Clustername - const region=process.env.Region - const accountid=process.env.Accountid - const DBname= process.env.DBname - const data = require('data-api-client')({ - secretArn: secret, - resourceArn: "arn:aws:rds:"+region+":"+accountid+":cluster:"+clustername, - database: DBname // default database - }) - async function createTable(TableName) { - console.log(\`CREATE TABLE IF NOT EXISTS \`+TableName+\` ( - name VARCHAR(100) NOT NULL, - id VARCHAR(50) NOT NULL, - PRIMARY KEY (id) - )\`) - let response=await data.query( - \`CREATE TABLE IF NOT EXISTS \`+TableName+\`( - name VARCHAR(100) NOT NULL, - id VARCHAR(50) NOT NULL, - PRIMARY KEY (id) - )\`) - return response - } - async function insertData(values,params,TableName) { - console.log(\`INSERT INTO \`+ TableName+params+\` VALUES(:name,:id) \`,values) - let response=await data.query( - \`INSERT INTO \`+ TableName+params+\` VALUES(:name,:id) \`, - values) - - return response - } - async function getData(TableName) { - let response=await data.query( - \`SELECT * FROM \`+ TableName) - - return response - } - async function updateData(id,name,TableName) { - let response=await data.query( - \`UPDATE \`+ TableName +\` SET name = :name WHERE id = :id \`, - { name: name, id: id }) - return response - } - async function getDatabyID(id,TableName) { - let response=await data.query( - \`SELECT * FROM \`+ TableName +\` WHERE id = :id \`, - { id: id }) - return response - } - async function deleteDatabyID(id,TableName) { - let response=await data.query( - \`DELETE FROM \`+TableName+\` WHERE id = :id \`, - { id: id } ) - return response - } - exports.lambdaHandler = async (event) => { - - let TableName="userk" - let tablecreate=await createTable(TableName) - console.log("table creation",tablecreate) - let insertdata= await insertData({"name":"dgb","id":"32"},'(name,id)',TableName) - console.log("insertData",insertdata) - let getdata = await getData(TableName) - console.log("getdata",getdata) - let updatedata = await updateData("32","DGB",TableName) - console.log("updateData",updatedata) - let getdatabyid = await getDatabyID("32",TableName) - console.log("getDatabyID",getdatabyid) - let deletedatabyid = await deleteDatabyID("32",TableName) - console.log("deleteDatabyID",deletedatabyid) - };`, +export const LambdaLogicsFileMappings: Record> = { + "nodejs14.x": { + EmailAuthModule_PreSignUp: "emailAuthModulePreSignUp.js", + EmailAuthModule_DefineAuthChallenge: + "emailAuthModuleDefineAuthChallenge.js", + EmailAuthModule_CreateAuthChallenge: + "emailAuthModuleCreateAuthChallenge.js", + EmailAuthModule_VerifyAuthChallengeResponse: + "emailAuthModuleVerifyAuthChallengeResponse.js", + EmailAuthModule_SignUpFunctions: "emailAuthModuleSignUpFunctions.js", + EmailAuthModule_ResendCode: "emailAuthModuleResendCode.js", + EmailAuthModule_ConfirmUser: "emailAuthModuleConfirmUser.js", + EmailAuthModule_ConfirmForgotPassword: + "emailAuthModuleConfirmForgotPassword.js", + EmailAuthModule_ForgotPassword: "emailAuthModuleForgotPassword.js", + EmailAuthModule_AuthorizerFunction: "emailAuthModuleAuthorizerFunction.js", + s3_lambda: "s3Lambda.js", + EmailAuthModule_Users: "emailAuthModuleUsers.js", + crud: "crud.js", + rdstable: "rdsTable.js", }, "python3.9": {}, }; + +export function generateLambdaLogics(filename: string, language: string) { + const dirName = path.join(__dirname); + const filePath = path.join(dirName, `logics/${language}/${filename}`); + const fileContent = fs.readFileSync(filePath, "utf-8").toString(); + return fileContent; +} diff --git a/src/resources/logics/nodejs14.x/crud.js b/src/resources/logics/nodejs14.x/crud.js new file mode 100644 index 00000000..993aad64 --- /dev/null +++ b/src/resources/logics/nodejs14.x/crud.js @@ -0,0 +1,74 @@ +let response; +const aws = require("aws-sdk"); +const dynamoDB = new aws.DynamoDB.DocumentClient(); +const Table = process.env.Table; + +async function getData(id) { + const params = { + TableName: Table, + Key: { id: id }, + }; + let { Item } = await dynamoDB.get(params).promise(); + console.log("[INFO] getData output", Item); + return Item; +} +async function deleteData(id) { + const params = { + TableName: Table, + Key: { id: id }, + }; + let { Item } = await dynamoDB.delete(params).promise(); + console.log("[INFO] getData output", Item); + return Item; +} +async function addupdateData(userData) { + console.log("[INFO] addupdateData input", userData); + const params = { + TableName: Table, + Item: userData, + }; + let Items = await dynamoDB.put(params).promise(); + console.log("[INFO] addupdateData output", Items); + return Items; +} +exports.lambdaHandler = async (event) => { + try { + let res; + console.log("events "); + if (event.httpMethod == "POST") { + if (event.body !== undefined) { + event = JSON.parse(event.body); + } + await addupdateData(event); + res = { message: "data updated" }; + } + if (event.httpMethod == "GET") { + res = await getData(event.pathParameters["id"]); + } + if (event.httpMethod == "PUT") { + if (event.body !== undefined) { + event = JSON.parse(event.body); + } + await addupdateData(event); + res = { message: "data updated" }; + } + if (event.httpMethod == "DELETE") { + await deleteData(event.pathParameters["id"]); + res = { message: "data deleted" }; + } + response = { + statusCode: 200, + body: JSON.stringify({ + data: res, + }), + }; + } catch (err) { + console.log(err); + response = { + statusCode: 200, + body: JSON.stringify(err), + }; + } + + return response; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleAuthorizerFunction.js b/src/resources/logics/nodejs14.x/emailAuthModuleAuthorizerFunction.js new file mode 100644 index 00000000..3ce896cf --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleAuthorizerFunction.js @@ -0,0 +1,43 @@ +import jwt from "jsonwebtoken"; + +// By default, API Gateway authorizations are cached (TTL) for 300 seconds. +// This policy will authorize all requests to the same API Gateway instance where the +// request is coming from, thus being efficient and optimising costs. +const generatePolicy = (principalId, methodArn) => { + const apiGatewayWildcard = methodArn.split("/", 2).join("/") + "/*"; + + return { + principalId, + policyDocument: { + Version: "2012-10-17", + Statement: [ + { + Action: "execute-api:Invoke", + Effect: "Allow", + Resource: apiGatewayWildcard, + }, + ], + }, + }; +}; + +export async function handler(event, context) { + if (!event.authorizationToken) { + throw new Error("Unauthorized"); + } + + const token = event.authorizationToken.replace("Bearer ", ""); + + try { + const claims = jwt.verify(token, process.env.AUTH0_PUBLIC_KEY); + const policy = generatePolicy(claims.sub, event.methodArn); + + return { + ...policy, + context: claims, + }; + } catch (error) { + console.log(error); + throw new Error("Unauthorized"); + } +} diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleConfirmForgotPassword.js b/src/resources/logics/nodejs14.x/emailAuthModuleConfirmForgotPassword.js new file mode 100644 index 00000000..1a557f49 --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleConfirmForgotPassword.js @@ -0,0 +1,34 @@ +let response; +// User pool ID is available via this method - +// const UserPoolID = process.env.UserPoolID; +const UserPoolClientID = process.env.UserPoolClientID; +const aws = require("aws-sdk"); +exports.lambdaHandler = async (event, context) => { + try { + if (event.body !== undefined) { + event = JSON.parse(event.body); + } + const cognito = new aws.CognitoIdentityServiceProvider(); + let params = { + ClientId: UserPoolClientID, + ConfirmationCode: event.Code, + Username: event.emailId, + Password: event.password /* required */, + }; + const res = await cognito.confirmForgotPassword(params).promise(); + response = { + statusCode: 200, + body: JSON.stringify({ + message: res, + }), + }; + } catch (err) { + console.log(err); + response = { + statusCode: 200, + body: JSON.stringify(err), + }; + } + + return response; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleConfirmUser.js b/src/resources/logics/nodejs14.x/emailAuthModuleConfirmUser.js new file mode 100644 index 00000000..53b92ebd --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleConfirmUser.js @@ -0,0 +1,66 @@ +let response; +const aws = require("aws-sdk"); +const dynamoDB = new aws.DynamoDB.DocumentClient(); +const UserTable = process.env.userinfoTable; +const UserPoolID = process.env.UserPoolID; +const UserPoolClientID = process.env.UserPoolClientID; +async function addUserData(userData) { + console.log("[INFO] addUserData input", userData); + const params = { + TableName: UserTable, + Item: userData, + }; + let Items = await dynamoDB.put(params).promise(); + console.log("[INFO] addUserData output", Items); + return Items; +} +exports.lambdaHandler = async (event, context) => { + try { + if (event.body !== undefined) { + event = JSON.parse(event.body); + } + const cognito = new aws.CognitoIdentityServiceProvider(); + let params = { + ClientId: UserPoolClientID, + ConfirmationCode: event.Code, + Username: event.emailId, + }; + await cognito.confirmSignUp(params).promise(); + + params = { + UserPoolId: UserPoolID, + AttributesToGet: ["email", "name", "sub"], + }; + + let res = await cognito.listUsers(params).promise(); + let user = {}; + let Attributes = {}; + res["Users"].map((ele) => { + Attributes = ele["Attributes"].find( + (ele) => ele.Name === "email" && ele.Value == event.emailId + ); + if (Attributes !== undefined) { + ele["Attributes"].map((ele) => { + user[ele.Name] = ele.Value; + }); + } + }); + console.log(user); + await addUserData(user); + response = { + statusCode: 200, + body: JSON.stringify({ + message: res, + }), + }; + // await addUserData() + } catch (err) { + console.log(err); + response = { + statusCode: 200, + body: JSON.stringify(err), + }; + } + + return response; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleCreateAuthChallenge.js b/src/resources/logics/nodejs14.x/emailAuthModuleCreateAuthChallenge.js new file mode 100644 index 00000000..3933d929 --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleCreateAuthChallenge.js @@ -0,0 +1,26 @@ +exports.lambdaHandler = async (event) => { + let password; + if (!event.request.session || !event.request.session.length) { + // new session, so fetch password from the db + // Developer can fetch username and email from the event object - + // const username = event.request.userAttributes.email; + // const user = event.request.userAttributes.username; + password = event.request.userAttributes.password; + } else { + const previousChallenge = event.request.session.slice(-1)[0]; + password = previousChallenge.challengeMetadata.match(/PASSWORD-(d*)/)[1]; + } + // This is sent back to the client app + event.response.publicChallengeParameters = { + username: event.request.userAttributes.email, + }; + + // Add the secret login code to the private challenge parameters + // so it can be verified by the "Verify Auth Challenge Response" trigger + event.response.privateChallengeParameters = { password }; + + // Add the secret login code to the session so it is available + // in a next invocation of the "Create Auth Challenge" trigger + event.response.challengeMetadata = `PASSWORD - ${password}`; + return event; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleDefineAuthChallenge.js b/src/resources/logics/nodejs14.x/emailAuthModuleDefineAuthChallenge.js new file mode 100644 index 00000000..d076d0da --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleDefineAuthChallenge.js @@ -0,0 +1,26 @@ +exports.lambdaHandler = async (event) => { + if ( + event.request.session && + event.request.session.length >= 3 && + event.request.session.slice(-1)[0].challengeResult === false + ) { + // The user provided a wrong answer 3 times; fail auth + event.response.issueTokens = false; + event.response.failAuthentication = true; + } else if ( + event.request.session && + event.request.session.length && + event.request.session.slice(-1)[0].challengeResult === true + ) { + // The user provided the right answer; succeed auth + event.response.issueTokens = true; + event.response.failAuthentication = false; + } else { + // The user did not provide a correct answer yet; present challenge + event.response.issueTokens = false; + event.response.failAuthentication = false; + event.response.challengeName = "CUSTOM_CHALLENGE"; + } + + return event; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleForgotPassword.js b/src/resources/logics/nodejs14.x/emailAuthModuleForgotPassword.js new file mode 100644 index 00000000..3ce4ab7f --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleForgotPassword.js @@ -0,0 +1,32 @@ +let response; +// User pool ID is available via this method - +// const UserPoolID = process.env.UserPoolID; +const UserPoolClientID = process.env.UserPoolClientID; +const aws = require("aws-sdk"); +exports.lambdaHandler = async (event, context) => { + try { + if (event.body !== undefined) { + event = JSON.parse(event.body); + } + const cognito = new aws.CognitoIdentityServiceProvider(); + let params = { + ClientId: UserPoolClientID, + Username: event.emailId, + }; + let res = await cognito.forgotPassword(params).promise(); + response = { + statusCode: 200, + body: JSON.stringify({ + message: res, + }), + }; + } catch (err) { + console.log(err); + response = { + statusCode: 200, + body: JSON.stringify(err), + }; + } + + return response; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModulePreSignUp.js b/src/resources/logics/nodejs14.x/emailAuthModulePreSignUp.js new file mode 100644 index 00000000..4be1e708 --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModulePreSignUp.js @@ -0,0 +1,5 @@ +exports.lambdaHandler = async (event) => { + event.response.autoConfirmUser = false; + event.response.autoVerifyEmail = false; + return event; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleResendCode.js b/src/resources/logics/nodejs14.x/emailAuthModuleResendCode.js new file mode 100644 index 00000000..1b1b7bae --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleResendCode.js @@ -0,0 +1,34 @@ +let response; +const aws = require("aws-sdk"); +// User pool ID is available via this method - +// const UserPoolID = process.env.UserPoolID; +const UserPoolClientID = process.env.UserPoolClientID; +exports.lambdaHandler = async (event) => { + try { + if (event.body !== undefined) { + event = JSON.parse(event.body); + } + const cognito = new aws.CognitoIdentityServiceProvider(); + + let params = { + ClientId: UserPoolClientID, + Username: event.emailId, + }; + const res = await cognito.resendConfirmationCode(params).promise(); + + response = { + statusCode: 200, + body: JSON.stringify({ + message: res, + }), + }; + } catch (err) { + console.log(err); + response = { + statusCode: 200, + body: JSON.stringify(err), + }; + } + + return response; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleSignUpFunctions.js b/src/resources/logics/nodejs14.x/emailAuthModuleSignUpFunctions.js new file mode 100644 index 00000000..5af620b5 --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleSignUpFunctions.js @@ -0,0 +1,42 @@ +let response; +const aws = require("aws-sdk"); +// User pool ID is available via this method - +// const UserPoolID = process.env.UserPoolID; +const UserPoolClientID = process.env.UserPoolClientID; +exports.lambdaHandler = async (event) => { + try { + if (event.body !== undefined) { + event = JSON.parse(event.body); + } + const cognito = new aws.CognitoIdentityServiceProvider(); + const params = { + ClientId: UserPoolClientID, + Username: event.emailId, + Password: event.Password, + UserAttributes: [ + { + Name: "email", + Value: event.emailId, + }, + { + Name: "name", + Value: event.name, + }, + ], + }; + console.log(params); + let res = await cognito.signUp(params).promise(); + response = { + statusCode: 200, + body: JSON.stringify(res), + }; + } catch (err) { + console.log(err); + response = { + statusCode: 200, + body: JSON.stringify(err), + }; + } + + return response; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleUsers.js b/src/resources/logics/nodejs14.x/emailAuthModuleUsers.js new file mode 100644 index 00000000..5ceca036 --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleUsers.js @@ -0,0 +1,70 @@ +let response; +const aws = require("aws-sdk"); +const dynamoDB = new aws.DynamoDB.DocumentClient(); +const UserTable = process.env.userinfoTable; +// User pool ID & User pool client ID is available via this method - +// const UserPoolID = process.env.UserPoolID; +// const UserPoolClientID = process.env.UserPoolClientID; +async function getUserData(id) { + const params = { + TableName: UserTable, + Key: { email: id }, + }; + let { Item } = await dynamoDB.get(params).promise(); + console.log("[INFO] getUserData output", Item); + return Item; +} +async function deleteUserData(id) { + const params = { + TableName: UserTable, + Key: { email: id }, + }; + let { Item } = await dynamoDB.delete(params).promise(); + console.log("[INFO] getUserData output", Item); + return Item; +} +async function addUserData(userData) { + console.log("[INFO] addUserData input", userData); + const params = { + TableName: UserTable, + Item: userData, + }; + let Items = await dynamoDB.put(params).promise(); + console.log("[INFO] addUserData output", Items); + return Items; +} + +exports.lambdaHandler = async (event) => { + try { + let res; + console.log("events ", event.pathParameters["email"]); + if (event.httpMethod == "GET") { + res = await getUserData(event.pathParameters["email"]); + } + if (event.httpMethod == "PUT") { + if (event.body !== undefined) { + event = JSON.parse(event.body); + } + await addUserData(event); + res = { message: "data updated" }; + } + if (event.httpMethod == "DELETE") { + await deleteUserData(event.pathParameters["email"]); + res = { message: "data deleted" }; + } + response = { + statusCode: 200, + body: JSON.stringify({ + data: res, + }), + }; + } catch (err) { + console.log(err); + response = { + statusCode: 200, + body: JSON.stringify(err), + }; + } + + return response; +}; diff --git a/src/resources/logics/nodejs14.x/emailAuthModuleVerifyAuthChallengeResponse.js b/src/resources/logics/nodejs14.x/emailAuthModuleVerifyAuthChallengeResponse.js new file mode 100644 index 00000000..c1e3fe4f --- /dev/null +++ b/src/resources/logics/nodejs14.x/emailAuthModuleVerifyAuthChallengeResponse.js @@ -0,0 +1,11 @@ +const md5 = require("md5"); + +exports.lambdaHandler = async (event) => { + const expectedAnswer = event.request.privateChallengeParameters.password; + if (md5(event.request.challengeAnswer) === expectedAnswer) { + event.response.answerCorrect = true; + } else { + event.response.answerCorrect = false; + } + return event; +}; diff --git a/src/resources/logics/nodejs14.x/rdsTable.js b/src/resources/logics/nodejs14.x/rdsTable.js new file mode 100644 index 00000000..5f62ad7e --- /dev/null +++ b/src/resources/logics/nodejs14.x/rdsTable.js @@ -0,0 +1,96 @@ +const secret = process.env.Secret; +const clustername = process.env.Clustername; +const region = process.env.Region; +const accountid = process.env.Accountid; +const DBname = process.env.DBname; +const data = require("data-api-client")({ + secretArn: secret, + resourceArn: + "arn:aws:rds:" + region + ":" + accountid + ":cluster:" + clustername, + database: DBname, // default database +}); + +async function createTable(TableName) { + console.log( + `CREATE TABLE IF NOT EXISTS ` + + TableName + + ` ( + name VARCHAR(100) NOT NULL, + id VARCHAR(50) NOT NULL, + PRIMARY KEY (id) + )` + ); + let response = await data.query( + `CREATE TABLE IF NOT EXISTS ` + + TableName + + `( + name VARCHAR(100) NOT NULL, + id VARCHAR(50) NOT NULL, + PRIMARY KEY (id) + )` + ); + return response; +} + +async function insertData(values, params, TableName) { + console.log( + `INSERT INTO ` + TableName + params + ` VALUES(:name,:id) `, + values + ); + let response = await data.query( + `INSERT INTO ` + TableName + params + ` VALUES(:name,:id) `, + values + ); + + return response; +} + +async function getData(TableName) { + let response = await data.query(`SELECT * FROM ` + TableName); + + return response; +} + +async function updateData(id, name, TableName) { + let response = await data.query( + `UPDATE ` + TableName + ` SET name = :name WHERE id = :id `, + { name: name, id: id } + ); + return response; +} + +async function getDatabyID(id, TableName) { + let response = await data.query( + `SELECT * FROM ` + TableName + ` WHERE id = :id `, + { id: id } + ); + return response; +} + +async function deleteDatabyID(id, TableName) { + let response = await data.query( + `DELETE FROM ` + TableName + ` WHERE id = :id `, + { id: id } + ); + return response; +} + +exports.lambdaHandler = async (event) => { + let TableName = "userk"; + let tablecreate = await createTable(TableName); + console.log("table creation", tablecreate); + let insertdata = await insertData( + { name: "dgb", id: "32" }, + "(name,id)", + TableName + ); + console.log("insertData", insertdata); + let getdata = await getData(TableName); + console.log("getdata", getdata); + let updatedata = await updateData("32", "DGB", TableName); + console.log("updateData", updatedata); + let getdatabyid = await getDatabyID("32", TableName); + console.log("getDatabyID", getdatabyid); + let deletedatabyid = await deleteDatabyID("32", TableName); + console.log("deleteDatabyID", deletedatabyid); +}; diff --git a/src/resources/logics/nodejs14.x/s3Lambda.js b/src/resources/logics/nodejs14.x/s3Lambda.js new file mode 100644 index 00000000..f1191804 --- /dev/null +++ b/src/resources/logics/nodejs14.x/s3Lambda.js @@ -0,0 +1,27 @@ +const aws = require("aws-sdk"); + +const s3 = new aws.S3({ apiVersion: "2006-03-01" }); + +exports.handler = async (event) => { + console.log("Received event:", JSON.stringify(event, null, 2)); + + // Get the object from the event and show its content type + const bucket = event.Records[0].s3.bucket.name; + const key = decodeURIComponent( + event.Records[0].s3.object.key.replace(/\+/g, " ") + ); + const params = { + Bucket: bucket, + Key: key, + }; + try { + const { ContentType } = await s3.getObject(params).promise(); + console.log("CONTENT TYPE:", ContentType); + return ContentType; + } catch (err) { + console.log(err); + const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; + console.log(message); + throw new Error(message); + } +}; diff --git a/src/resources/resources.ts b/src/resources/resources.ts index ae0e9335..009cba3e 100644 --- a/src/resources/resources.ts +++ b/src/resources/resources.ts @@ -89,7 +89,6 @@ function swaggerGenerator(config: Record) { ); } const security: Array>> = []; - if ( config["security"] !== undefined && Object.keys(>config.security).length > 0 @@ -97,7 +96,6 @@ function swaggerGenerator(config: Record) { const apikeyObject = >config.security; if (Object.prototype.hasOwnProperty.call(config.security, "api_key")) { const apikey: Record> = {}; - apikey[ JSON.parse( JSON.stringify( @@ -119,14 +117,12 @@ function swaggerGenerator(config: Record) { security.push(authorizer); } } - const configObjects = >config.objects; configObjects.forEach((data: IcurdObject) => { const pathName = data["path"]; swaggerPaths[pathName] = attachMethods(data["methods"], data, security); return null; }); - swagger["paths"] = swaggerPaths; const doc = new yaml.Document(); doc.contents = swagger; @@ -177,7 +173,10 @@ const attachMethods = ( return result; }; -export function apigatewaypath(template: ISAMTemplateResource, path: string) { +export function getAPIGatewayPath( + template: ISAMTemplateResource, + path: string +) { const definationbody = JSON.parse(JSON.stringify(configs.APIGatewaySkeleton)); definationbody["Fn::Transform"]["Parameters"]["Location"] = path; template["Properties"]["DefinitionBody"] = definationbody; @@ -206,28 +205,23 @@ export const resourceGeneration = function ( if (resource_properties.Properties.Base.length > 0) { for (const baseProperties of resource_properties.Properties.Base) { - template[<"Properties">attributes][ - baseProperties - ] = config[baseProperties]; + template[<"Properties">attributes][baseProperties] = + config[baseProperties]; } } - if (resource_properties.Properties.Optional.length > 0) { - for (const optinalProperties of resource_properties.Properties.Optional) { - if ( - config[optinalProperties] !== undefined - ) { - template[<"Properties">attributes][ - optinalProperties - ] = config[optinalProperties]; + for (const optinalProperties of resource_properties.Properties + .Optional) { + if (config[optinalProperties] !== undefined) { + template[<"Properties">attributes][optinalProperties] = + config[optinalProperties]; } } } - - for (const defaultProperties of resource_properties.Properties.Default) { + for (const defaultProperties in resource_properties.Properties.Default) { template[<"Properties">attributes][ - defaultProperties["Key"] - ] = defaultProperties["Value"]; + resource_properties.Properties.Default[defaultProperties]["Key"] + ] = resource_properties.Properties.Default[defaultProperties]["Value"]; } } } @@ -239,7 +233,7 @@ export const resourceGeneration = function ( } if (resource_name == "apigateway") { if (Object.prototype.hasOwnProperty.call(config, "path")) { - template = apigatewaypath(template, config["path"]); + template = getAPIGatewayPath(template, config["path"]); } if (Object.prototype.hasOwnProperty.call(config, "objects")) { swaggerGenerator(config); diff --git a/src/utlities/utilities.ts b/src/utlities/utilities.ts index 16847b58..551b50bc 100644 --- a/src/utlities/utilities.ts +++ b/src/utlities/utilities.ts @@ -161,21 +161,27 @@ export function generateLambdaFiles( const j = (i); if (logic) { if (resources["resources"][j]["logicpath"] !== "") { - code = - logics.LambdaLogics[app_data.language][ + code = logics.generateLambdaLogics( + logics.LambdaLogicsFileMappings[app_data.language][ resources["resources"][j]["logicpath"] - ]; + ], + app_data.language + ); } else { if (resources["type"] == "components" || stacktype == "") { - code = - logics.LambdaLogics[app_data.language][ + code = logics.generateLambdaLogics( + logics.LambdaLogicsFileMappings[app_data.language][ resources["resources"][j]["name"] - ]; + ], + app_data.language + ); } else { - code = - logics.LambdaLogics[app_data.language][ + code = logics.generateLambdaLogics( + logics.LambdaLogicsFileMappings[app_data.language][ stacktype + "_" + resources["resources"][j]["name"] - ]; + ], + app_data.language + ); } }