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