From c9242a95f3b1aa753f13cc7960bc2ef011b50d11 Mon Sep 17 00:00:00 2001 From: Andrew Zhu Date: Tue, 5 Feb 2019 15:14:11 -0800 Subject: [PATCH] add createCharacter, transferCharacter endpoints --- app/Routes/API.js | 47 +++++++++++++++++++++++++++++--- app/lib/functions/permissions.js | 7 +++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/app/Routes/API.js b/app/Routes/API.js index 2ca20b7c..f041f37a 100644 --- a/app/Routes/API.js +++ b/app/Routes/API.js @@ -104,19 +104,58 @@ Router.map(function () { where: "server" }).post( function () { - ifPostOK(this, "createCharacter", () => { + this.response.setHeader("Content-Type", "application/json"); + const header = this.request.headers; + const key = header && header['authorization']; + ifKeyValid(key, this.response, "createCharacter", () => { + const character = this.request.body; + let error; + character.owner = userIdFromKey(key); + let id = Characters.insert(character, (err) => { + if (err) + error = err.message; + }); + + if (error) { + this.response.writeHead(400, "Failed to insert character"); + this.response.end(JSON.stringify({err: error})); + } else { + this.response.end(JSON.stringify({id: id})); + } }); } ); - this.route("transferCharacterOwnership", { // POST /api/character/:_id/owner + this.route("transferCharacterOwnership", { // PUT /api/character/:_id/owner path: "/api/character/:_id/owner", where: "server" - }).post( + }).put( function () { - ifPostOK(this, "transferCharacterOwnership", () => { + this.response.setHeader("Content-Type", "application/json"); + const header = this.request.headers; + const key = header && header['authorization']; + const charId = this.params._id; + ifKeyValid(key, this.response, "transferCharacterOwnership", () => { + if (isOwner(charId, userIdFromKey(key))) { + const newOwner = this.request.body['id']; + let error; + Characters.update({_id: charId}, {"$set": {owner: newOwner}}, null, + (err) => { + if (err) + error = err.message; + }); + if (error) { + this.response.writeHead(400, "Failed to update character"); + this.response.end(JSON.stringify({err: error})); + } else { + this.response.end(JSON.stringify({success: true})); + } + } else { + this.response.writeHead(403, "You do not have permission to transfer this character"); + this.response.end(); + } }); } ); diff --git a/app/lib/functions/permissions.js b/app/lib/functions/permissions.js index 8f160297..495d429b 100644 --- a/app/lib/functions/permissions.js +++ b/app/lib/functions/permissions.js @@ -1,3 +1,10 @@ +isOwner = function(charId, userId) { + userId = userId || Meteor.userId(); + var char = Characters.findOne(charId, {fields: {owner: 1}}); + if (!char) return true; + return (userId === char.owner); +}; + canEditCharacter = function(charId, userId){ userId = userId || Meteor.userId(); var char = Characters.findOne(charId, {fields: {owner: 1, writers: 1}});