Skip to content

Instantly share code, notes, and snippets.

@logemann
Last active July 20, 2020 11:38
Show Gist options
  • Save logemann/43510f97fdd1c142bb27e9f6bb37e8cd to your computer and use it in GitHub Desktop.
Save logemann/43510f97fdd1c142bb27e9f6bb37e8cd to your computer and use it in GitHub Desktop.
import Sns from "aws-sdk/clients/sns";
import axios from 'axios';
import * as querystring from 'querystring';
const reCapUrl = "https://www.google.com/recaptcha/api/siteverify";
// we got this from personal reCaptcha Google Page
const reCaptchaSecret = "xxxxxxxxxxxxxxxxxxxxxxxx" ;
function bodyToMap(parts: any) : Map<String, String>{
let result = new Map();
// grab the params
for (let i = 0, len = parts.length; i < len; i++) {
let kVal = parts[i].split('=');
// replace the + space then decode
let key = decodeURIComponent(kVal[0].replace(/\+/g, ' '));
result.set(key, decodeURIComponent(kVal[1].replace(/\+/g, ' ')));
}
return result;
}
export const handler = async (event: any = {}): Promise<any> => {
console.log("Starting ContactForm Processing for website okaycloud form.");
let body = event.body;
// process the urlencoded body of the form submit and put it in a
// map structure
let parts = body.split('&');
let result = bodyToMap(parts);
// its always a good idea to log so that we can inspect the params
// later in Amazon Cloudwatch
//console.log(result);
let data = querystring.stringify({
secret: reCaptchaSecret,
response: result.get("g-recaptcha-response")
});
//console.log(`Verify Post Data: ${JSON.stringify(data)}`);
//console.log(`Verify Post Data Form Encoded: ${data}`);
// verify the result by POSTing to google backend with secret and
// frontend recaptcha token as payload
let verifyResult = await axios.post(reCapUrl, data);
// if you like you can also print out the result of that. Its
// a bit verbose though
//console.log(`Success ist: ${JSON.stringify(verifyResult.data)}`);
if (verifyResult.data.success) {
let emailbody = `—— Contactform —-
Name: ${result.get('FULLNAME')}
Email: ${result.get('EMAIL')}
Tel: ${result.get('PHONE')}
Thema: ${result.get('SUBJECT')}
* Nachricht *
${result.get("MESSAGE")}
`;
let sns = new Sns();
let params = {
Message: emailbody,
Subject: `Contactform: ${result.get("SUBJECT")}`,
TopicArn: process.env.TOPIC_ARN
};
// we publish the created message to Amazon SNS now…
await sns.publish(params).promise();
// now we return a HTTP 302 together with a URL to redirect the
// browser to success URL (we put in google.com for simplicty)
return {
statusCode: 302,
headers: {
Location: "https://mydomain.com/contact_success.html",
}
};
} else {
console.log("reCaptcha check failed. Most likely SPAM.");
return {
statusCode: 302,
headers: {
Location: "https://mydomain.com/contact_failure.html",
}
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment