adb75dae5460e4c22cdb365852dab5f7f58d1598
[vchess.git] / routes / problems.js
1 // AJAX methods to get, create, update or delete a problem
2
3 let router = require("express").Router();
4 const access = require("../utils/access");
5 const ProblemModel = require("../models/Problem");
6 const sanitizeHtml = require('sanitize-html');
7 const MaxNbProblems = 20;
8
9 // Get one problem
10 router.get("/problems/:vname([a-zA-Z0-9]+)/:pnum([0-9]+)", access.ajax, (req,res) => {
11 const vname = req.params["vname"];
12 const pnum = req.params["pnum"];
13 ProblemModel.getOne(vname, pnum, (err,problem) => {
14 if (!!err)
15 return res.json(err);
16 return res.json({problem: problem});
17 });
18 });
19
20 // Fetch N previous or next problems
21 router.get("/problems/:vname([a-zA-Z0-9]+)", access.ajax, (req,res) => {
22 const vname = req.params["vname"];
23 const directionStr = (req.query.direction == "forward" ? ">" : "<");
24 const lastDt = req.query.last_dt;
25 const type = req.query.type;
26 if (!lastDt.match(/[0-9]+/))
27 return res.json({errmsg: "Bad timestamp"});
28 if (!["others","mine"].includes(type))
29 return res.json({errmsg: "Bad type"});
30 ProblemModel.fetchN(vname, req.userId, type, directionStr, lastDt, MaxNbProblems,
31 (err,problems) => {
32 if (!!err)
33 return res.json(err);
34 return res.json({problems: problems});
35 }
36 );
37 });
38
39 function sanitizeUserInput(fen, instructions, solution)
40 {
41 if (!fen.match(/^[a-zA-Z0-9, /-]*$/))
42 return "Bad characters in FEN string";
43 instructions = sanitizeHtml(instructions);
44 solution = sanitizeHtml(solution);
45 if (instructions.length == 0)
46 return "Empty instructions";
47 if (solution.length == 0)
48 return "Empty solution";
49 return {
50 fen: fen,
51 instructions: instructions,
52 solution: solution
53 };
54 }
55
56 // Upload a problem (sanitize inputs)
57 router.post("/problems/:vname([a-zA-Z0-9]+)", access.logged, access.ajax, (req,res) => {
58 const vname = req.params["vname"];
59 const s = sanitizeUserInput(req.body["fen"], req.body["instructions"], req.body["solution"]);
60 if (typeof s === "string")
61 return res.json({errmsg: s});
62 ProblemModel.create(vname, s.fen, s.instructions, s.solution);
63 res.json({});
64 });
65
66 // Update a problem (also sanitize inputs)
67 router.put("/problems/:id([0-9]+)", access.logged, access.ajax, (req,res) => {
68 const pid = req.params["id"]; //problem ID
69 const s = sanitizeUserInput(req.body["fen"], req.body["instructions"], req.body["solution"]);
70 if (typeof s === "string")
71 return res.json({errmsg: s});
72 ProblemModel.update(pid, req.userId, fen, instructions, solution);
73 res.json({});
74 });
75
76 // Delete a problem
77 router.delete("/problems/:id([0-9]+)", access.logged, access.ajax, (req,res) => {
78 const pid = req.params["id"]; //problem ID
79 ProblemModel.delete(pid, req.userId);
80 res.json({});
81 });
82
83 module.exports = router;