captcha_aggregator/src/controllers/captcha.js

50 lines
2.2 KiB
JavaScript

import CaptchaService from "../services/captcha.js";
import jwt from 'jsonwebtoken';
import config from '../config.js';
class CaptchaController {
async submit(req, res) {
const { image, solution } = req.body;
if (!image) return res.status(400).send({ "message": "You must send image blob" });
if (!solution || solution.length != config.captcha_length) return res.status(400).send({ "message": "You must send a valid solution" });
for (let i = 0; i < solution.length; i++) {
let char = solution[i];
if (!char.match(config.alphabet)) {
console.log("Illegal symbol: " + char);
return res.status(400).send({ "message": `Illegal symbol ${char} at position ${i + 1}` });
}
}
try {
await CaptchaService.new(image, solution, jwt.decode(req.token).id);
} catch (e) {
console.log(`Error upon submitting: ${e}`);
return res.status(500).send({ "message": "Unknown server error. Please, contact the developer." });
}
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();