forked from GeorgeChan/captchapng
-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
91 lines (72 loc) · 2.77 KB
/
app.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Captcha PNG img generator
* @Author: Chakshu Gautam
* @Email: [email protected]
* @Version: 2.0
* @Date: 2020-08-18
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
const {v1: uuid} = require('uuid');
const captchapng = require('./captchapng');
const cors = require('cors')
const express = require('express');
const app = express()
const port = process.env.PORT || 9000
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('db.json');
const db = low(adapter);
app.use(cors({
origin: '*',
optionsSuccessStatus: 200,
}));
db.defaults({ captchas: []}).write();
app.listen(port, () => console.log(`listening on port: ${port}`))
app.get('/', (request, response) => {
const captchaParsed = parseInt(Math.random()*900000+100000);
var p = new captchapng(120, 30, captchaParsed); // width,height,numeric captcha
p.color(0, 0, 0, 0); // First color: background (red, green, blue, alpha)
p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha)
var img = p.getBase64();
var imgbase64 = new Buffer(img,'base64');
const token = uuid();
db.get('captchas').push({token, captchaParsed, timestamp: Math.floor(Date.now() / 1000)}).write();
console.log({token});
response.header({
'Content-Type': 'image/png',
token,
'access-control-expose-headers': 'token'
});
// Request token
response.send(imgbase64);
});
const removeOldCaptchas = () => {
// Delete all captchas that are more than 600 seconds old.
const now = Math.floor(Date.now() / 1000);
const allData = db.get('captchas').value();
console.log({now});
allData.filter(captcha => now - captcha.timestamp > 600).forEach(filteredCaptcha => {
db.get('captchas').remove({ token: filteredCaptcha.token }).write();
})
}
app.get('/verify', (request, response) => {
removeOldCaptchas();
try{
const userResponse = request.query.captcha;
const token = request.query.token;
const captcha = db.get('captchas').find({ token: token }).value();
if(!captcha) {response.status(400).send({status: "Token Not Found"}); return;}
deleteUsedCaptcha(token);
if (parseInt(userResponse) === (captcha && captcha.captchaParsed)) {
response.status(200).send({status: "Success"});
}else {
response.status(400).send({status: "Code Incorrect"});
}
}catch(err){
console.log({err});
response.status(500).send({status: "Internal Server Error"});
}
});
function deleteUsedCaptcha(token) {
db.get('captchas').remove({ token: token }).write();
}