diff --git a/src/data/database.js b/src/data/database.js index 3fd66c41..fdb50999 100644 --- a/src/data/database.js +++ b/src/data/database.js @@ -244,7 +244,7 @@ async function updateUserPassword(user_id, old_pass, new_pass) { /** * Count number of submissions */ -function countSubmissions() { +function countAllSubmissions() { return new Promise((resolve, reject) => { db.submissions.count({}, function(err, count) { if (err) reject(err); @@ -253,6 +253,19 @@ function countSubmissions() { }); } +/** + * Count number of submissions from user_id + * @param {String} user_id User's ID + */ +function countUserSubmissions(user_id) { + return new Promise((resolve, reject) => { + db.submissions.count({ user_id }, function(err, count) { + if (err) reject(err); + else resolve(count); + }); + }); +} + /** * Verify page, count, size value so it will work */ @@ -272,7 +285,7 @@ function verifySubsQuery(page, size, count, maxSize) { * @returns {Promise>} Array of submission if success */ async function readAllSubmissions(page, size, count) { - const maxSize = await countSubmissions(); + const maxSize = await countAllSubmissions(); ({ page, size, count } = verifySubsQuery(page, size, count, maxSize)); return new Promise((resolve, reject) => { @@ -339,7 +352,14 @@ function readSubmission(sub_id) { if (err) reject(err); else if (docs === null) reject(new Error(`Invalid Submission's ID: ${sub_id}`)); - else resolve(docs); + else + readUserByID(docs.user_id) + .then((res) => { + docs.username = res.username; + }) + .finally(() => { + resolve(docs); + }); } ); }); @@ -355,8 +375,8 @@ function readSubmission(sub_id) { * @returns {Promise>} Array of user's submissions if success */ async function readUserSubmission(user_id, page, size, count) { - const username = await readUserByID(user_id); - const maxSize = await countSubmissions(); + const userData = await readUserByID(user_id); + const maxSize = await countUserSubmissions(user_id); ({ page, size, count } = verifySubsQuery(page, size, count, maxSize)); return new Promise((resolve, reject) => { @@ -381,7 +401,7 @@ async function readUserSubmission(user_id, page, size, count) { if (err) reject(err); else { let serialized = docs.map((doc) => { - doc.username = username; + doc.username = userData.username; return doc; }); resolve({ @@ -554,6 +574,8 @@ module.exports = { readUserPassHash, updateUserName, updateUserPassword, + countAllSubmissions, + countUserSubmissions, readAllSubmissions, readSubmission, readUserSubmission, diff --git a/src/routes/subs.js b/src/routes/subs.js index 5382f752..e9435892 100644 --- a/src/routes/subs.js +++ b/src/routes/subs.js @@ -56,7 +56,8 @@ router router.get("/:id", (req, res) => { readSubmission(req.params.id).then( (docs) => { - if (docs.user_id === req.user._id) res.send(docs); + if (docs.user_id === req.user._id || req.user.isAdmin) + res.send(docs); else res.sendStatus(401); }, (err) => {