Skip to content

Instantly share code, notes, and snippets.

@guljarpd
Last active June 30, 2020 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save guljarpd/7a1514f156a952a3c680db7da73c6de9 to your computer and use it in GitHub Desktop.
Save guljarpd/7a1514f156a952a3c680db7da73c6de9 to your computer and use it in GitHub Desktop.
/* ----------------------------------- preSignUp -------------------------------------------*/
exports.handler = async (event) => {
// Confirm the user
event.response.autoConfirmUser = true;
// Set the email as verified if it is in the request
if (event.request.userAttributes.hasOwnProperty("email")) {
event.response.autoVerifyEmail = true;
}
// Set the phone number as verified if it is in the request
if (event.request.userAttributes.hasOwnProperty("phone_number")) {
event.response.autoVerifyPhone = true;
}
console.log(event);
return event;
};
/* ---------------------------------------- defineAuthChallenge ---------------------------*/
exports.handler = async (event) => {
console.log(event.request.session);
console.log(event)
if(event.request.userNotFound){
// If user not found true.
event.response.issueTokens = null;
event.response.failAuthentication = null;
} else 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';
}
console.log(event);
return event;
};
/* ------------------------------------ createAuthChallenge ---------------------------------*/
const aws = require('aws-sdk');
//
exports.handler = async event => {
console.log(event);
let secretLoginCode = "";
if (!event.request.session || !event.request.session.length) {
// This is a new auth session
// Generate a new secret login code and mail it to the user
// secretLoginCode = cryp.randomDigits(4).join('');
secretLoginCode = Math.floor(1000 + Math.random() * 9000);
if(event.request.userAttributes.email){
await sendEmail(event.request.userAttributes.email, secretLoginCode);
}else if(event.request.userAttributes.phone_number){
await sendSMS(event.request.userAttributes.phone_number, secretLoginCode);
}
} else {
// There's an existing session. Don't generate new digits but
// re-use the code from the current session. This allows the user to
// make a mistake when keying in the code and to then retry, rather
// the needing to e-mail the user an all new code again.
const previousChallenge = event.request.session.slice(-1)[0];
secretLoginCode = previousChallenge.challengeMetadata.match(/CODE-(\d*)/)[1];
}
// This is sent back to the client app
// event.response.publicChallengeParameters = {
// email: 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 = {
secretLoginCode: secretLoginCode
};
// 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 = `CODE-${secretLoginCode}`;
console.log(event);
return event;
};
async function sendEmail(emailAddress, secretLoginCode) {
//
const ses = new aws.SES();
const params = {
Destination: {
ToAddresses: [emailAddress]
},
Message: {
Body: {
Html: {
Charset: 'UTF-8',
Data: `<html>
<body>
<p>Hey there!</p>
<p>Your <strong>OTP ${secretLoginCode}</strong>.
<br>Don't share with anyone.
</p>
</body>
</html>`
},
Text: {
Charset: 'UTF-8',
Data: `Your secret login code: ${secretLoginCode}`
}
},
Subject: {
Charset: 'UTF-8',
Data: `${secretLoginCode} is your OTP for login`
}
},
Source: 'Name <name@example.com>'
};
console.log(params);
await ses.sendEmail(params).promise();
}
async function sendSMS(phoneNumber, secretLoginCode){
aws.config.update({ region: "ap-southeast-1" });
const sns = new aws.SNS();
await sns.setSMSAttributes({
attributes: {
DefaultSMSType: 'Transactional'
}
}).promise();
var params = {
Message: secretLoginCode + ' is the OTP for login.',
PhoneNumber: phoneNumber
};
console.log(params);
await sns.publish(params).promise();
}
/* ------------------------------------------ verifyAuthChallenge -------------------------- */
exports.handler = async (event) => {
console.log(event);
const expectedAnswer = event.request.privateChallengeParameters.secretLoginCode;
if (event.request.challengeAnswer === expectedAnswer) {
event.response.answerCorrect = true;
} else {
event.response.answerCorrect = false;
}
console.log(event);
return event;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment