Added handling of CAPTCHA.

This commit is contained in:
Alexander Andreev 2022-06-25 03:28:48 +04:00
parent 6c45d2661e
commit 228fc885ca
Signed by: Arav
GPG Key ID: 0388CC8FAA51063F

View File

@ -11,6 +11,7 @@ const config = require("./config");
const guestbook = require("./guestbook");
const mindflow = require("./mindflow");
const util = require("../shared/util");
const { URLSearchParams } = require("url");
const articles_meta = {
@ -46,6 +47,27 @@ async function getProcesses() {
}
}
async function getNewCaptcha() {
try {
return await fetch("http://127.0.0.1:19322/").then(r => r.text());
} catch {
return null;
}
}
async function solveCaptcha(id, answer) {
try {
let body = new URLSearchParams();
body.append('answer', answer);
let result = fetch(`http://127.0.0.1:19322/${id}`, { method: "POST", body: body } );
return await result.then(r => {
return r.status == 200, r.status;
});
} catch {
return false;
}
}
function setRoutes() {
return koaRouter().get('/', async ctx => {
await ctx.render('index', {
@ -114,7 +136,8 @@ function setRoutes() {
tz: util.getClientTimezone(ctx),
owner: config.guestbook.owner,
posts: posts,
pages_count: Math.ceil(await guestbook.getPostsCount() / page_size) });
pages_count: Math.ceil(await guestbook.getPostsCount() / page_size),
captcha_id: await getNewCaptcha() });
})
.post('/guestbook', bodyParser, async ctx => {
const post = ctx.request.body;
@ -123,10 +146,18 @@ function setRoutes() {
post.hide_website = post.hide_website !== undefined;
try {
let check, status = await solveCaptcha(post.captcha_id, post.captcha_answer);
if (!check) {
if (status == 404) {
throw "CAPTCHA expired";
} else {
throw "wrong CAPTCHA";
}
}
if (await guestbook.addPost(post))
ctx.redirect("/guestbook");
} catch(err) {
if (typeof err == 'object' && err instanceof MysqlError) {
ctx.response.status = 500;
ctx.response.body = { error: `Database failed so your post wasn't added. Here's your message:`, message: post.message };