LearningSalesForceCommerceC.../int_recaptcha/cartridge/controllers/ContactUs.js

56 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-12-22 09:45:09 -08:00
'use strict';
2021-12-22 10:20:13 -08:00
var base = module.superModule;
2021-12-22 09:45:09 -08:00
var server = require('server');
2021-12-22 10:20:13 -08:00
server.extend(base);
2021-12-22 10:05:38 -08:00
// First, let's extend the ContactUs-Landing route
// to add recaptcha data to the template view
2021-12-22 09:45:09 -08:00
server.append('Landing', function(req, res, next) {
res.setViewData({
2021-12-22 10:05:38 -08:00
// Recaptcha API script URL
2021-12-22 09:45:09 -08:00
recaptchaUrl: 'https://www.google.com/recaptcha/api.js',
siteKey: '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI' // Test Site Key from Google
});
next();
});
2021-12-22 10:05:38 -08:00
// Now we need to extend ContactUs-Subscribe, to add our logic
// that invokes the recaptcha service
// We prepend here to ensure that an invalid response is caught before the email is sent
server.prepend('Subscribe', function(req, res, next) {
var recaptchaService = require('*/cartridge/scripts/services/recaptcha');
2021-12-22 09:45:09 -08:00
// Token automatically added to request by recaptcha
var token = req.form['g-recaptcha-response'];
// Add required parameters for validation call
var params = {
// This is a test secret from Google
2021-12-22 10:05:38 -08:00
// In practice, do not hardcode this.
// It's better to store in a custom preference or service credential configuration
secret: '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe',
2021-12-22 09:45:09 -08:00
response: token
};
// Calls recaptcha service
// Returns a Service class instance
2021-12-22 10:05:38 -08:00
// (start with a hardcoded fail)
2021-12-22 09:45:09 -08:00
var validationResult = recaptchaService.call(params);
// Actual response from Google
var response = verificationResult.object;
if (!response.success) {
// Handle failure by returning error to the client
res.json({
success: false,
msg: 'Recaptcha Validation Failure'
});
}
next();
});
module.exports = server.exports();