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{ 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 => { 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", } }; } };