1 // AJAX methods to get, create, update or delete a problem
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;
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
) => {
19 return res
.json({problems: problems
});
23 function sanitizeUserInput(fen
, instructions
, solution
)
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";
35 instructions: instructions
,
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
);
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
);
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
);
67 module
.exports
= router
;