-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
35 lines (31 loc) · 966 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const hcaptcha = require('hcaptcha');
// validate takes an hCaptcha secret and returns
// an express middleware function
const validate = (secret) => (req, res, next) => {
// get token from the body
// requires the body parser JSON middleware
// on the app that uses this middleware
const token = req.body && req.body.token;
// call next with an error if no token present
if (!token) {
const err = new Error('bad request - no token provided in body');
err.status = 400;
return next(err);
}
// verify the hcaptcha and continue on success
// call next with an error if verification errors or fails
return hcaptcha.verify(secret, token)
.then((data) => {
req.hcaptcha = data;
if (data.success) {
return next();
}
const err = new Error(`bad request - ${data['error-codes']}`);
err.status = 400;
return next(err);
})
.catch(next);
};
module.exports.middleware = {
validate,
};