-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
91 lines (73 loc) · 2.25 KB
/
index.js
File metadata and controls
91 lines (73 loc) · 2.25 KB
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
const express = require('express');
const crypto = require('crypto');
const app = express();
const port = 3000;
app.use(express.json());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
next();
});
const captchaStore = new Map();
setInterval(() => {
const now = Date.now();
for (const [id, data] of captchaStore.entries()) {
if (now - data.createdAt > 10 * 60 * 1000) {
captchaStore.delete(id);
}
}
}, 60 * 1000);
function generateCaptchaCode(length = 6) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for (let i = 0; i < length; i++) {
const randomIndex = crypto.randomInt(0, chars.length);
code += chars[randomIndex];
}
return code;
}
app.get('/api/captcha', (req, res) => {
const captchaCode = generateCaptchaCode();
const captchaId = crypto.randomBytes(16).toString('hex');
captchaStore.set(captchaId, {
text: captchaCode,
createdAt: Date.now()
});
res.json({
captchaId: captchaId,
code: captchaCode
});
});
app.post('/api/verify-captcha', (req, res) => {
const { captchaId, userInput } = req.body;
if (!captchaId || !userInput) {
return res.status(400).json({
success: false,
message: 'CaptchaId et userInput sont requis'
});
}
const storedCaptcha = captchaStore.get(captchaId);
if (!storedCaptcha) {
return res.status(400).json({
success: false,
message: 'Captcha invalide ou expiré'
});
}
const isValid = userInput.toUpperCase() === storedCaptcha.text.toUpperCase();
captchaStore.delete(captchaId);
res.json({
success: isValid,
message: isValid ? 'Captcha validé avec succès' : 'Captcha incorrect'
});
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
success: false,
message: 'Erreur interne du serveur'
});
});
app.listen(port, () => {
console.log(`API Captcha démarrée sur le port ${port}`);
});