Experimental symmetric randomness + deterministic option
[vchess.git] / server / routes / challenges.js
1 let router = require("express").Router();
2 const access = require("../utils/access");
3 const ChallengeModel = require("../models/Challenge");
4 const UserModel = require("../models/User"); //for name check
5 const params = require("../config/parameters");
6
7 router.post("/challenges", access.logged, access.ajax, (req,res) => {
8 if (ChallengeModel.checkChallenge(req.body.chall))
9 {
10 let challenge =
11 {
12 fen: req.body.chall.fen,
13 cadence: req.body.chall.cadence,
14 randomness: req.body.chall.randomness,
15 vid: req.body.chall.vid,
16 uid: req.userId,
17 to: req.body.chall.to, //string: user name (may be empty)
18 };
19 const insertChallenge = () => {
20 ChallengeModel.create(challenge, (err,ret) => {
21 res.json(err || {cid:ret.cid});
22 });
23 };
24 if (req.body.chall.to)
25 {
26 UserModel.getOne("name", challenge.to, (err,user) => {
27 if (!!err || !user)
28 res.json(err || {errmsg: "Typo in player name"});
29 else
30 {
31 challenge.to = user.id; //ready now to insert challenge
32 insertChallenge();
33 if (user.notify)
34 UserModel.notify(
35 user,
36 "New challenge: " + params.siteURL + "/#/?disp=corr");
37 }
38 });
39 }
40 else
41 insertChallenge();
42 }
43 });
44
45 router.get("/challenges", access.ajax, (req,res) => {
46 const uid = req.query.uid;
47 if (uid.match(/^[0-9]+$/))
48 {
49 ChallengeModel.getByUser(uid, (err,challenges) => {
50 res.json(err || {challenges:challenges});
51 });
52 }
53 });
54
55 router.delete("/challenges", access.logged, access.ajax, (req,res) => {
56 const cid = req.query.id;
57 if (cid.match(/^[0-9]+$/))
58 {
59 ChallengeModel.safeRemove(cid, req.userId);
60 res.json({});
61 }
62 });
63
64 module.exports = router;