UNPKG

1.48 kBJavaScriptView Raw
1"use strict";
2
3/**
4 * Implementation of reCAPTCHA rate restriction.
5 *
6 * Will validate recaptcha using req.body.recaptchaResponse value.
7 *
8 * Requires ```node-recaptcha2``` package.
9 *
10 * @param {object} [settings] settings for recaptcha, or null to disable
11 * @param {string} settings.privateKey also known as secret key
12 * @param {string} settings.publicKey also known as site key
13 * @return {ExpressMiddlewareFunction}
14 */
15function recaptcha(settings = null)
16{
17 if (settings)
18 {
19 // make sure we have all the settings we need
20 const privateKey = settings.privateKey || false;
21 const publicKey = settings.publicKey || false;
22
23 if (privateKey && publicKey)
24 {
25 let Recaptcha = require('node-recaptcha2')
26 .Recaptcha;
27
28
29 return function (req, res, next)
30 {
31 if (!req.body.recaptchaResponse || typeof req.body.recaptchaResponse !== 'string' || req.body.recaptchaResponse.length < 1)
32 {
33 return res.error('reCAPTCHA response not included');
34 }
35 (new Recaptcha(publicKey, privateKey, {
36 remoteip: req.clientIp,
37 response: req.body.recaptchaResponse
38 }))
39 .verify((success, errCode) =>
40 {
41 if (!success)
42 {
43 res.error('Failed verifying reCAPTCHA');
44 }
45 else
46 {
47 next();
48 }
49 });
50 };
51 }
52 }
53
54 return function (req, res, next)
55 {
56 next();
57 };
58}
59
60module.exports = recaptcha;