Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Post update backend #77

Merged
merged 17 commits into from
Mar 24, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion gamersnet_backend/persistence/posts.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
'use strict';

const { ObjectID } = require('bson');
let MongoDB = require('./mongodb');
let ObjectId = require('mongodb').ObjectID;

async function getPost(_id) {
// connect wait for server to connect to db
let db = await MongoDB.open();

// once it connected, get the "posts" collection (aka a table in SQL)
let posts = db.collection('posts');

// wait for the server to find the specified post
let result = await posts.find({ _id : new ObjectID(_id)});
return result.toArray();
}

async function getAllPosts() {
// connect wait for server to connect to db
Expand Down Expand Up @@ -54,5 +68,39 @@ async function addPost(userID, description, gameName, numPlayers, gameTimeUTC, d
})
}

/**
* updates the specified post(by post id)
* All parameters should be string type to be consistent and avoid confusion
* @param {*} userID userId of the owner of this post
* @param {*} description
* @param {*} gameName
* @param {*} numPlayers
* @param {*} gameTimeUTC when it will be played
* @param {*} duration how long will it be played
* @param {*} location location of game
*/
async function updatePost_db(_id, description, gameName, numPlayers, gameTimeUTC, duration, location) {
humayraR marked this conversation as resolved.
Show resolved Hide resolved
// wait for db connection and get users collection
let db = await MongoDB.open();

let posts = db.collection('posts');

var updateValues = {
$set: {
description: description,
gameName: gameName,
numPlayers: numPlayers, //null in case of incorrect format
gameTimeUTC: gameTimeUTC,
duration: duration,
location: location
}
}
console.log("updating db...")

let updated = await posts.updateOne({ _id: new ObjectID(_id)}, updateValues)

console.log("Update operation complete.")
return updated
}
// make these two functions "public" to the rest of the project
module.exports = { getAllPosts, addPost, getValidPosts };
module.exports = { getPost, getAllPosts, addPost, getValidPosts, updatePost_db};
2 changes: 1 addition & 1 deletion gamersnet_backend/routes/posts/createPost.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async function createPost(request, response) {
let gameTimeUTC = new Date(body.gameTimeUTC);

await addPost(userID, body.description, body.gameName, numPlayers, gameTimeUTC, body.duration, body.location);
response.status(204).end();
response.status(201).end();
} else {
response.status(400).end();
}
Expand Down
17 changes: 15 additions & 2 deletions gamersnet_backend/routes/posts/getPosts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


// include our function from the database to add post
let {getAllPosts, getValidPosts} = require('../../persistence/posts');
let {getPost, getAllPosts, getValidPosts} = require('../../persistence/posts');

// this function handles the /post/getAllPosts/ endpoint
async function listAllPosts(request, response) {
Expand All @@ -17,6 +17,7 @@ async function listAllPosts(request, response) {
}
}

//list of posts that hasn't expired yet(the scheduled game time > current time)
async function listValidPosts(request, response) {
let results = await getValidPosts();
if(results != null) {
Expand All @@ -27,4 +28,16 @@ async function listValidPosts(request, response) {
}
}

module.exports = {listAllPosts, listValidPosts};
//search for post with the given id
async function getPostbyID(request, response) {
let _id = request.query._id
let results = await getPost(_id);
if(results != null) {
response.json(results);
response.status(200).end();
} else {
response.status(404).end();
}
}

module.exports = {listAllPosts, listValidPosts, getPostbyID};
11 changes: 10 additions & 1 deletion gamersnet_backend/routes/posts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,20 @@ const router = require('express').Router();

// include each route handler
let {createPost} = require('./createPost');
let {listAllPosts, listValidPosts} = require('./getPosts');
let {listAllPosts, listValidPosts, getPostbyID} = require('./getPosts');
let {updatePost} = require('./updatePost')


router.post('/createPost', createPost);
router.get('/listAllPosts', listAllPosts);
router.get('/listValidPosts', listValidPosts);
router.get('/getPostbyID', getPostbyID);
router.post('/updatePost', updatePost);

//test routes
// let {updatePost_unauthorized} = require('./updatePost')
// router.post('/updatePost_unauthorized', updatePost_unauthorized);


// return the above routes
module.exports = router;
82 changes: 82 additions & 0 deletions gamersnet_backend/routes/posts/updatePost.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
'use strict';

// include our function from the database to add post
let {updatePost_db, getPost} = require('../../persistence/posts');
let {verifyUserLoggedIn} = require('../utilities/tokenUtility')
let {getUserIDFromToken} = require('../../persistence/tokens.js')


/**
* Helper function: updates specific post. User doesn't need to be logged in.
* created this function to test update posts without worrying about tokens being expired.
* (Don't wanna go and change expiry time in db everytime I test :/ )
* @param {*} request
* @param {*} response
*
* PLEASE DON'T USE THIS IN FRONTEND !! For backend testing only.
*/
async function updatePost_unauthorized(request, response) {
let body = request.body;
//console.log(request)

if (body._id && body.description && body.gameTimeUTC && body.gameName) {
//input type are verified here
let numPlayers = parseInt(body.numPlayers);
let gameTimeUTC = new Date(body.gameTimeUTC);
let postID = body._id.$oid; //Object Id String

await updatePost_db(postID, body.description, body.gameName, numPlayers, gameTimeUTC, body.duration, body.location);

response.status(201).send("Updated post successfully.");
} else {
response.status(400).end();
}

}

/**
* this function handles the /post/updatePost/ endpoint
* Replaces the field values with the given ones in the db
* @param {*} request body should contain the postID(ObjectId or _id), description, gameName, numPlayers, gameTimeUTC, duration, location
* @param {*} response
*/
async function updatePost(request, response) {
let body = request.body;
let cookie = request.headers.cookie;

let loggedIn = false;

if (cookie) {
cookie = cookie.split('=')[1];
loggedIn = await verifyUserLoggedIn(cookie);
}

if (loggedIn) {
let tokenDocument = await getUserIDFromToken(cookie);

//get logged in user id from token
let loggedUserID = tokenDocument.userID;
let postUserID = null

let oldPost = await getPost(body._id.$oid)

if(oldPost.length > 0){ //if the post exists, this check also ensures that
// we don't get out of bounds error while getting userID
postUserID = oldPost[0].userID
}

console.log(loggedUserID.equals(postUserID))

if(loggedUserID.equals(postUserID)) {//only the user who created the post can update it.
console.log("Correct User.")
updatePost_unauthorized(request, response)
}
else{
response.status(401).send('You are not authorized to change this post. Only owner of this post can change it.'); //status code: unauthorized
}
} else {
response.status(401).send('User not logged in.'); //status code: unauthorized
}
}

module.exports = {updatePost_unauthorized, updatePost };