},
// obj can have fields move, chat, fen, drawOffer and/or score + message
- update: function(id, obj)
+ update: function(id, obj, cb)
{
db.parallelize(function() {
let query =
query += modifs + " WHERE id = " + id;
db.run(query);
}
+ let wrongMoveIndex = false;
if (obj.move)
{
- const m = obj.move;
+ // Security: only update moves if index is right
query =
- "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
- "(" + id + ",?," + m.played + "," + m.idx + ")";
- db.run(query, JSON.stringify(m.squares));
+ "SELECT MAX(idx) AS maxIdx " +
+ "FROM Moves " +
+ "WHERE gid = " + id;
+ db.get(query, (err,ret) => {
+ const m = obj.move;
+ if (!ret.maxIdx || ret.maxIdx + 1 == m.idx) {
+ query =
+ "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
+ "(" + id + ",?," + m.played + "," + m.idx + ")";
+ db.run(query, JSON.stringify(m.squares));
+ cb(null);
+ }
+ else cb({errmsg:"Wrong move index"});
+ });
}
+ else cb(null);
if (obj.chat)
{
query =
GameModel.getPlayers(gid, (err,players) => {
if (players.some(p => p.uid == req.userId))
{
- GameModel.update(gid, obj);
- if (obj.move || obj.score)
- {
- // Notify opponent if he enabled notifications:
- const oppid = players[0].uid == req.userId
- ? players[1].uid
- : players[0].uid;
- const messagePrefix = obj.move
- ? "New move in game: "
- : "Game ended: ";
- UserModel.tryNotify(oppid,
- messagePrefix + params.siteURL + "/#/game/" + gid);
- }
- res.json({});
+ GameModel.update(gid, obj, (err) => {
+ if (!err && (obj.move || obj.score))
+ {
+ // Notify opponent if he enabled notifications:
+ const oppid = players[0].uid == req.userId
+ ? players[1].uid
+ : players[0].uid;
+ const messagePrefix = obj.move
+ ? "New move in game: "
+ : "Game ended: ";
+ UserModel.tryNotify(oppid,
+ messagePrefix + params.siteURL + "/#/game/" + gid);
+ }
+ res.json(err || {});
+ });
}
});
}