-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaptcha.js
51 lines (46 loc) · 1.4 KB
/
captcha.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
var {badrequest} = require('./response');
var QUESTIONS = {
'Are you human?': true,
'Are you a robot?': false
};
var Q = 'nocms-captcha-question';
var A = 'nocms-captcha-answer';
exports.middleware = function captcha(next, app) {
return function captcha(req) {
if (!req.session.data.isAuthorized && req.method.toLowerCase() == 'post') {
var answer = req.params[A];
if (!answer || typeof(answer) != 'string') {
req.session.data[Q] = null;
return badrequest();
}
var answer = answer.toLowerCase().trim();
// weird switch statement to get cheap undef
var boolAnswer = {'yes': true,
'no': false
}[answer];
if (boolAnswer === undefined) {
return badrequest();
}
var question = req.session.data[Q];
if (QUESTIONS[question] === boolAnswer) {
req.session.data[Q] = null;
return next(req);
} else {
return badrequest();
}
} else {
return next(req);
}
};
};
/**
* set question in session data
* @returns question tags
*/
exports.getQuestion = function(req) {
// kind of random order
var questions = Object.keys(QUESTIONS);
var rnd = parseInt(Math.random() * questions.length, 10);
req.session.data[Q] = questions[rnd];
return questions[rnd];
};