1 var router
= require("express").Router();
2 var ObjectID
= require("bson-objectid");
3 var ChallengeModel
= require('../models/Challenge');
4 var UserModel
= require('../models/User');
5 var ObjectID
= require("bson-objectid");
6 var access
= require("../utils/access");
8 // Only AJAX requests here (from variant page and index)
11 router
.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
});
22 router
.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
});
31 function createChallenge(vid
, from, to
, res
)
33 ChallengeModel
.create(vid
, from, to
, (err
, chall
) => {
35 // A challenge can be sent using only name, thus 'to' is returned
42 // from[, to][,nameTo]
43 router
.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
);
52 UserModel
.getByName(nameTo
, (err
,user
) => {
53 access
.checkRequest(res
, err
, user
, "Opponent not found", () => {
54 createChallenge(vid
, from, user
._id
, res
);
59 createChallenge(vid
, from, to
, res
);
61 createChallenge(vid
, from, undefined, res
); //automatch
64 router
.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
=> {
77 module
.exports
= router
;