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;
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
) => {
16 return res
.json({problem: problem
});
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
,
34 return res
.json({problems: problems
});
39 function sanitizeUserInput(fen
, instructions
, solution
)
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";
51 instructions: instructions
,
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
);
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
);
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
);
83 module
.exports
= router
;