Sanitize inputs on server side
[vchess.git] / server / routes / games.js
index 73a8bf7..e9d9ab4 100644 (file)
@@ -9,11 +9,22 @@ var params = require("../config/parameters");
 // From main hall, start game between players 0 and 1
 router.post("/games", access.logged, access.ajax, (req,res) => {
   const gameInfo = req.body.gameInfo;
-       if (!gameInfo.players.some(p => p.id == req.userId))
+       if (!Array.isArray(gameInfo.players) ||
+    !gameInfo.players.some(p => p.id == req.userId))
+  {
                return res.json({errmsg: "Cannot start someone else's game"});
+  }
   const cid = req.body.cid;
+  // Check all entries of gameInfo + cid:
+  let error = GameModel.checkGameInfo(gameInfo);
+  if (!error)
+  {
+    if (!cid.toString().match(/^[0-9]+$/))
+      error = "Wrong challenge ID";
+  }
+  if (!!error)
+    return res.json({errmsg:error});
   ChallengeModel.remove(cid);
-       const fen = req.body.fen;
        GameModel.create(
     gameInfo.vid, gameInfo.fen, gameInfo.timeControl, gameInfo.players,
                (err,ret) => {
@@ -34,7 +45,7 @@ router.get("/games", access.ajax, (req,res) => {
   {
     GameModel.getOne(gameId, (err,game) => {
                  access.checkRequest(res, err, game, "Game not found", () => {
-                         res.json({game: game});
+        res.json({game: game});
                  });
          });
   }
@@ -44,7 +55,7 @@ router.get("/games", access.ajax, (req,res) => {
     const userId = req.query["uid"];
     const excluded = !!req.query["excluded"];
     GameModel.getByUser(userId, excluded, (err,games) => {
-                 if (!!err)
+                       if (!!err)
         return res.json({errmsg: err.errmsg || err.toString()});
                        res.json({games: games});
          });
@@ -54,13 +65,25 @@ router.get("/games", access.ajax, (req,res) => {
 // New move + fen update + score, potentially
 // TODO: if newmove fail, takeback in GUI
 router.put("/games", access.logged, access.ajax, (req,res) => {
-       const gid = req.body.gid;
-       const obj = req.body.newObj;
+  const gid = req.body.gid;
+  let error = "";
+  if (!gid.toString().match(/^[0-9]+$/))
+    error = "Wrong game ID";
+  const obj = req.body.newObj;
+       error = GameModel.checkGameUpdate(obj);
+  if (!!error)
+    return res.json({errmsg: error});
        GameModel.update(gid, obj, (err) => {
                if (!!err)
       return res.json(err);
-    if (!!req.body.offlineOpp) //TODO: refresh this...
-      UserModel.tryNotify(req.body.offlineOpp, "New move in game " + gid);
+    // Notify opponent if he enabled notifications:
+    GameModel.getPlayers(gid, (err2,players) => {
+      if (!!err2)
+        return res.json(err);
+      const oppid = (players[0].id == req.userId ? players[1].id : players[0].id);
+      UserModel.tryNotify(oppid,
+        "New move in game: " + params.siteURL + "/game/" + gid);
+    });
     res.json({});
        });
 });