Skip to content

Instantly share code, notes, and snippets.

@biggora
Created August 17, 2014 08:29
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 biggora/f1cdc260e4ca6ce524fb to your computer and use it in GitHub Desktop.
Save biggora/f1cdc260e4ca6ce524fb to your computer and use it in GitHub Desktop.
Recaptcha usage for TrinteJS framework
/**
* Recaptcha builder
*
*
* Created by init script
* App based on TrinteJS MVC framework
* TrinteJS homepage http://www.trintejs.com
**/
var Recaptcha = require('recaptcha').Recaptcha;
var config = require("../configuration");
var captchaConf = config.recaptcha;
function buildRecaptcha(data) {
return new Recaptcha(captchaConf.public_key, captchaConf.private_key, data);
}
exports.createRecaptcha = function createRecaptcha() {
return function(req, res, next) {
res.locals({
recaptcha: {
form: buildRecaptcha().toHTML(),
valid: false,
error: false
}
});
next();
};
};
exports.verifyRecaptcha = function verifyRecaptcha(successTo) {
return function(req, res, next) {
buildRecaptcha({
remoteip: req.connection.remoteAddress,
challenge: req.body.recaptcha_challenge_field,
response: req.body.recaptcha_response_field
}).verify(function(success, error_code) {
var locals = {
recaptcha: {
form: buildRecaptcha().toHTML(),
error: false
}
};
if (success) {
locals.recaptcha.valid = true;
} else {
// Redisplay the form.
locals.recaptcha.valid = false;
locals.recaptcha.error = error_code;
}
res.locals(locals);
if (successTo) {
res.redirect(successTo);
} else {
next();
}
});
};
};
exports.middleware = function middleware() {
return function(req, res, next) {
if (req.method === 'POST' || req.method === 'PUT') {
buildRecaptcha({
remoteip: req.connection.remoteAddress,
challenge: req.body.recaptcha_challenge_field,
response: req.body.recaptcha_response_field
}).verify(function(success, error_code) {
var locals = {
recaptcha: {
form: buildRecaptcha().toHTML(),
error: false
}
};
if (success) {
locals.recaptcha.valid = true;
} else {
// Redisplay the form.
locals.recaptcha.valid = false;
locals.recaptcha.error = error_code;
}
res.locals(locals);
next();
});
} else {
res.locals({
recaptcha: {
form: buildRecaptcha().toHTML(),
valid: false,
error: false
}
});
next();
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment