Fix news notification system
[vchess.git] / server / routes / challenges.js
CommitLineData
ab4f4bf2
BA
1let router = require("express").Router();
2const access = require("../utils/access");
3const ChallengeModel = require("../models/Challenge");
052d17ea 4const UserModel = require("../models/User"); //for name check
fe4c7e67 5const params = require("../config/parameters");
8d7e2786 6
052d17ea 7router.post("/challenges", access.logged, access.ajax, (req,res) => {
866842c3 8 if (ChallengeModel.checkChallenge(req.body.chall))
1f49533d 9 {
866842c3
BA
10 let challenge =
11 {
12 fen: req.body.chall.fen,
13 cadence: req.body.chall.cadence,
7ba4a5bc 14 randomness: req.body.chall.randomness,
866842c3
BA
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) => {
51145f8c 27 if (err || !user)
866842c3
BA
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
bebcc8d4 41 insertChallenge();
866842c3
BA
42 }
43});
44
45router.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});
bf20f404 51 });
bf20f404 52 }
4edfed6c
BA
53});
54
1f49533d 55router.delete("/challenges", access.logged, access.ajax, (req,res) => {
77fd7298 56 const cid = req.query.id;
866842c3
BA
57 if (cid.match(/^[0-9]+$/))
58 {
59 ChallengeModel.safeRemove(cid, req.userId);
60 res.json({});
61 }
1f49533d 62});
8d7e2786
BA
63
64module.exports = router;