diff --git a/homepage/index.js b/homepage/index.js index f0adb1c..d974e93 100644 --- a/homepage/index.js +++ b/homepage/index.js @@ -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 };