-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.js
87 lines (75 loc) · 2.48 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import Koa from 'koa';
import koaStatic from 'koa-static';
import Router from '@koa/router';
import jwt from 'jsonwebtoken';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import bodyParser from 'koa-bodyparser';
import send from 'koa-send';
const __dirname = dirname(fileURLToPath(import.meta.url));
let yesVotes = 0;
let noVotes = 0;
const privateKey = readFileSync(join(__dirname, "key.priv"), "utf8");
const publicKey = readFileSync(join(__dirname, "key"), "utf8");
const msgs = readFileSync(join(__dirname, "errormessages"), "utf8").split("\n").filter(s => s.length > 0);
/** @type {import("./languages.json")} */
const languages = JSON.parse(readFileSync(join(__dirname, "languages.json"), "utf8"));
const languageRegex = /^[a-z]+$/;
const app = new Koa();
const router = new Router();
/**
* @param {string} language
* @returns {string}
*/
function generateToken(language) {
return jwt.sign({ language }, privateKey, { algorithm: "RS256" });
}
router.get("/localisation-file", async ctx => {
const token = ctx.cookies.get("lion-token");
/** @type {string} */
let language;
if (token) {
const payload = await new Promise((resolve, reject) => {
try {
jwt.verify(token, publicKey, (err, result) => err ? reject(err) : resolve(result));
} catch (e) {
reject(e);
}
});
language = payload.language;
} else {
language = languages[Math.floor(Math.random() * languages.length)].id;
ctx.cookies.set("lion-token", generateToken(language));
}
await send(ctx, language, {root: __dirname});
});
router.post("/localization-language", async ctx => {
const language = ctx.request.body?.language;
if (typeof language === "string") {
if (language.match(languageRegex)) {
ctx.cookies.set("lion-token", generateToken(language));
} else {
ctx.throw(400, msgs[Math.floor(Math.random() * msgs.length)]);
}
} else {
ctx.throw(400, "no language");
}
ctx.redirect("/");
});
router.get("/languages", async ctx => {
ctx.body = languages;
});
router.post("/y", async ctx => {
yesVotes++;
ctx.body = [yesVotes, noVotes];
});
router.post("/n", async ctx => {
noVotes++;
ctx.body = [yesVotes, noVotes];
});
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());
app.use(koaStatic(join(__dirname, "../public")));
app.listen(1337);