feat: MC Report System - MySQL + Express + Vanilla JS SPA
This commit is contained in:
31
backend/routes/captcha.js
Normal file
31
backend/routes/captcha.js
Normal file
@@ -0,0 +1,31 @@
|
||||
const express = require('express');
|
||||
const crypto = require('crypto');
|
||||
const { query } = require('../db');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
await query("DELETE FROM captchas WHERE created_at < NOW() - INTERVAL 5 MINUTE");
|
||||
const id = crypto.randomUUID();
|
||||
const ops = ['+', '-', '\u00d7'];
|
||||
const op = ops[Math.floor(Math.random() * ops.length)];
|
||||
let a, b;
|
||||
if (op === '\u00d7') { a = Math.floor(Math.random() * 9) + 1; b = Math.floor(Math.random() * 9) + 1; }
|
||||
else { a = Math.floor(Math.random() * 20) + 1; b = Math.floor(Math.random() * 10) + 1; if (op === '-' && a < b) [a, b] = [b, a]; }
|
||||
const answer = op === '+' ? a + b : op === '-' ? a - b : a * b;
|
||||
const question = `${a} ${op} ${b} = ?`;
|
||||
await query('INSERT INTO captchas(id, question, answer) VALUES (?,?,?)', [id, question, String(answer)]);
|
||||
res.json({ id, question });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
async function verify(id, answer) {
|
||||
const rows = await query("SELECT * FROM captchas WHERE id = ? AND created_at > NOW() - INTERVAL 5 MINUTE", [id]);
|
||||
if (!rows.length) return false;
|
||||
await query('DELETE FROM captchas WHERE id = ?', [id]);
|
||||
return String(answer).trim() === rows[0].answer;
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
module.exports.verify = verify;
|
||||
Reference in New Issue
Block a user