Created
August 17, 2014 08:29
-
-
Save biggora/f1cdc260e4ca6ce524fb to your computer and use it in GitHub Desktop.
Recaptcha usage for TrinteJS framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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