| 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 | // Fetch N previous or next problems |
| 10 | router.get("/problems/:vname([a-zA-Z0-9]+)", access.ajax, (req,res) => { |
| 11 | const vname = req.params["vname"]; |
| 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"}); |
| 16 | ProblemModel.fetchN(vname, directionStr, lastDt, MaxNbProblems, (err,problems) => { |
| 17 | if (!!err) |
| 18 | return res.json(err); |
| 19 | return res.json({problems: problems}); |
| 20 | }); |
| 21 | }); |
| 22 | |
| 23 | function sanitizeUserInput(fen, instructions, solution) |
| 24 | { |
| 25 | if (!fen.match(/^[a-zA-Z0-9, /-]*$/)) |
| 26 | return "Bad characters in FEN string"; |
| 27 | instructions = sanitizeHtml(instructions); |
| 28 | solution = sanitizeHtml(solution); |
| 29 | if (instructions.length == 0) |
| 30 | return "Empty instructions"; |
| 31 | if (solution.length == 0) |
| 32 | return "Empty solution"; |
| 33 | return { |
| 34 | fen: fen, |
| 35 | instructions: instructions, |
| 36 | solution: solution |
| 37 | }; |
| 38 | } |
| 39 | |
| 40 | // Upload a problem (sanitize inputs) |
| 41 | router.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({}); |
| 48 | }); |
| 49 | |
| 50 | // Update a problem (also sanitize inputs) |
| 51 | router.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 |
| 61 | router.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 | }); |
| 66 | |
| 67 | module.exports = router; |