TODO: modalSettings + finish game.js for other scenarios
[vchess.git] / routes / challenge.js
CommitLineData
8d7e2786
BA
1var router = require("express").Router();
2var ObjectID = require("bson-objectid");
3var ChallengeModel = require('../models/Challenge');
4var UserModel = require('../models/User');
5var ObjectID = require("bson-objectid");
6var access = require("../utils/access");
7
8// Only AJAX requests here (from variant page and index)
9
10// variant page
11router.get("/challengesbyvariant", access.logged, access.ajax, (req,res) => {
12 if (req.query["uid"] != req.user._id)
13 return res.json({errmsg: "Not your challenges"});
14 let uid = ObjectID(req.query["uid"]);
15 let vid = ObjectID(req.query["vid"]);
16 ChallengeModel.getByVariant(uid, vid, (err, challengeArray) => {
17 res.json(err || {challenges: challengeArray});
18 });
19});
20
21// index
22router.get("/challengesbyplayer", access.logged, access.ajax, (req,res) => {
23 if (req.query["uid"] != req.user._id)
24 return res.json({errmsg: "Not your challenges"});
25 let uid = ObjectID(req.query["uid"]);
26 ChallengeModel.getByPlayer(uid, (err, challengeArray) => {
27 res.json(err || {challenges: challengeArray});
28 });
29});
30
31function createChallenge(vid, from, to, res)
32{
33 ChallengeModel.create(vid, from, to, (err, chall) => {
34 res.json(err || {
35 // A challenge can be sent using only name, thus 'to' is returned
36 to: chall.to,
37 cid: chall._id
38 });
39 });
40}
41
42// from[, to][,nameTo]
43router.post("/challenges", access.logged, access.ajax, (req,res) => {
44 if (req.body.from != req.user._id)
45 return res.json({errmsg: "Identity usurpation"});
46 let from = ObjectID(req.body.from);
47 let to = !!req.body.to ? ObjectID(req.body.to) : undefined;
48 let nameTo = !!req.body.nameTo ? req.body.nameTo : undefined;
49 let vid = ObjectID(req.body.vid);
50 if (!to && !!nameTo)
51 {
52 UserModel.getByName(nameTo, (err,user) => {
53 access.checkRequest(res, err, user, "Opponent not found", () => {
54 createChallenge(vid, from, user._id, res);
55 });
56 });
57 }
58 else if (!!to)
59 createChallenge(vid, from, to, res);
60 else
61 createChallenge(vid, from, undefined, res); //automatch
62});
63
64router.delete("/challenges", access.logged, access.ajax, (req,res) => {
65 let cid = ObjectID(req.query.cid);
66 ChallengeModel.getById(cid, (err,chall) => {
67 access.checkRequest(res, err, chall, "Challenge not found", () => {
68 if (!chall.from.equals(req.user._id) && !!chall.to && !chall.to.equals(req.user._id))
69 return res.json({errmsg: "Not your challenge"});
70 ChallengeModel.remove(cid, err => {
71 res.json(err || {});
72 });
73 });
74 });
75});
76
77module.exports = router;