diff --git a/src/controllers/captcha.js b/src/controllers/captcha.js index b1741b7..2e5e3c7 100644 --- a/src/controllers/captcha.js +++ b/src/controllers/captcha.js @@ -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(); \ No newline at end of file diff --git a/src/routers/captcha.js b/src/routers/captcha.js index 5579e34..ff13467 100644 --- a/src/routers/captcha.js +++ b/src/routers/captcha.js @@ -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; \ No newline at end of file diff --git a/src/services/captcha.js b/src/services/captcha.js index 17baa74..3ab9f12 100644 --- a/src/services/captcha.js +++ b/src/services/captcha.js @@ -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(); \ No newline at end of file