From 53869bcf6c7f5185e988bf3e0c9e06b3876d300c Mon Sep 17 00:00:00 2001 From: Wingysam Date: Fri, 23 Nov 2018 10:12:28 -0500 Subject: [PATCH] Check to make sure move is valid --- routes/wishlist/index.js | 17 +++++++++++++++-- views/wishlist.pug | 9 +++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/routes/wishlist/index.js b/routes/wishlist/index.js index 49fec34..c6c0914 100644 --- a/routes/wishlist/index.js +++ b/routes/wishlist/index.js @@ -34,9 +34,17 @@ module.exports = (db) => { router.get('/:user', verifyAuth(), async (req, res) => { try { const dbUser = await db.get(req.params.user); - res.render('wishlist', { title: `Wishlist - ${dbUser._id}`, wishlist: dbUser.wishlist }); + const wishlistReverse = [...dbUser.wishlist].reverse(); + const lastCanSeeValue = wishlistReverse.find(element => (element.addedBy === req.params.user)); + const lastCanSee = dbUser.wishlist.indexOf(lastCanSeeValue); + res.render('wishlist', { + title: `Wishlist - ${dbUser._id}`, + wishlist: dbUser.wishlist, + lastCanSee + }); } catch (error) { - res.redirect('/wishlist'); + req.flash('error', error); + return res.redirect('/wishlist'); } }); @@ -131,6 +139,11 @@ module.exports = (db) => { if (wish.id === req.params.itemId) return moveFromIndex = wishlist.indexOf(wish); }); const moveToIndex = wishlist.findIndex(wish => ( wishlist.indexOf(wish) > moveFromIndex && wish.addedBy === req.user._id )); + if (moveToIndex < 0 || moveToIndex > wishlist.length) { + console.log(moveToIndex, '<', 0, '||', moveToIndex, '>', wishlist.length); + req.flash('error', 'Invalid move'); + return res.redirect(`/wishlist/${req.params.user}`); + } [ wishlist[moveFromIndex], wishlist[moveToIndex] ] = [ wishlist[moveToIndex], wishlist[moveFromIndex] ]; if (req.params.direction === 'up') wishlist.reverse(); doc.wishlist = wishlist; diff --git a/views/wishlist.pug b/views/wishlist.pug index 43965e1..f29e8ae 100644 --- a/views/wishlist.pug +++ b/views/wishlist.pug @@ -1,7 +1,7 @@ extends layout.pug block content - for item in wishlist + each item, index in wishlist if req.user._id === item.addedBy || req.params.user !== req.user._id .box span @@ -25,15 +25,16 @@ block content .field.inline .control.inline input.inline.button.is-warning(type='submit' value='Remove') - if req.user._id === req.params.user + - console.log(lastCanSee); + if req.user._id === req.params.user && index !== 0 && index !== lastCanSee form.inline(method='POST', action=`/wishlist/${req.params.user}/move/up/${item.id}`) .field.inline .control.inline - input.inline.button(type='submit' value='Move up') + input.inline.button(type='submit' value='Move item up') form.inline(method='POST', action=`/wishlist/${req.params.user}/move/down/${item.id}`) .field.inline .control.inline - input.inline.button(type='submit' value='Move down') + input.inline.button(type='submit' value='Move item down') form(method='POST') .field label.label Item URL or Name