added endpoints to fetch captchas

This commit is contained in:
leca 2025-05-03 23:53:09 +03:00
parent 86898fa117
commit 9c2fe1c856
3 changed files with 39 additions and 0 deletions

View File

@ -14,6 +14,28 @@ class CaptchaController {
}
return res.status(200).send({"message": "Success"});
}
async get(req, res) {
try {
const { id } = req.params;
const captcha = await CaptchaService.get(id);
if (captcha == undefined) return res.status(404).send({"message":"no such captcha found"});
return res.status(200).send({"message":"success", "captcha": captcha})
} catch (e) {
console.log(`Error upon requesting one captcha: ${e}`)
if (e.code == 'ENOENT') return res.status(404).send({"message": "The ID exists in the DB but I can't find an actual image. Please, contact the developer."})
return res.status(500).send({"message": "Unknown server error. Please, contact the developer."})
}
}
async get_all(req, res) {
try {
return res.status(200).send({"message":"success", "captchas": await CaptchaService.get_all()});
} catch (e) {
console.log(`Error upon requesting all captchas: ${e}`)
return res.status(500).send({"message": "Unknown server error. Please, contact the developer."})
}
}
}
export default new CaptchaController();

View File

@ -6,5 +6,7 @@ import auth from '../middlewares/auth.js';
const CaptchaRouter = new Router();
CaptchaRouter.post('/captcha/submit', auth.verify_user_jwt, CaptchaController.submit);
CaptchaRouter.get('/captcha/all', CaptchaController.get_all);
CaptchaRouter.get('/captcha/:id', CaptchaController.get);
export default CaptchaRouter;

View File

@ -2,6 +2,7 @@ import db from '../db.js';
import fs from 'fs/promises';
import config from '../config.js';
import { createHash } from 'crypto';
import captcha from '../controllers/captcha.js';
function base64ToArrayBuffer(base64) {
var binaryString = atob(base64);
@ -21,6 +22,20 @@ class CaptchaService {
await fs.writeFile(`${config.data_dir}/${hash}.jpeg`, b64, 'base64');
await db.query("INSERT INTO captchas (hash, solution, submitter) VALUES ($1, $2, $3)", [hash, solution, submitter]);
}
async get(id) {
const captcha = (await db.query("SELECT hash, solution FROM captchas WHERE id = $1", [id])).rows[0];
if (captcha == undefined) return undefined;
const path = `${config.data_dir}/${captcha.hash}.jpeg`;
const image = Buffer.from(await fs.readFile(path)).toString('base64');
return {"image": image, "solution": captcha.solution, "hash": captcha.hash};
}
async get_all() {
return (await db.query("SELECT id FROM captchas")).rows
}
}
export default new CaptchaService();