is there anything wrong with my code? i use express and mongoose
router.get('/c/:hashtoken', validateEmailToken, catchAsync(async(req,res)=>{
const hashtoken = req.params.hashtoken
const hashtoken2 = createHash('sha256').update(hashtoken).digest('hex')
const realHashTokens = await EmailToken.find({hashtoken2})
if(realHashTokens.length===0){
req.flash('error','Incorrect email verification token or Your account has been activated')
return res.redirect('/')
}
const toDeleteTokenId = []
for(let realHashToken of realHashTokens){
let theUser = await User.findById(realHashToken.user)
theUser.active = true
await theUser.save()
toDeleteTokenId.push(realHashToken._id)
}
for (let theId of toDeleteTokenId){
await EmailToken.findByIdAndDelete(theId)
}
req.flash('success','Success! Your account has been activated')
return res.redirect('/')
}))
the page has never responded. it keeps loading, but user becomes active if i checked in the database
CodePudding user response:
set an error handler or wrap in try/catch
router.get('/c/:hashtoken', validateEmailToken, catchAsync(async(req,res)=>{
try {
const hashtoken = req.params.hashtoken
const hashtoken2 = createHash('sha256').update(hashtoken).digest('hex')
const realHashTokens = await EmailToken.find({hashtoken2})
if(realHashTokens.length===0){
req.flash('error','Incorrect email verification token or Your account has been activated')
return res.redirect('/')
}
const toDeleteTokenId = []
for(let realHashToken of realHashTokens){
let theUser = await User.findById(realHashToken.user)
theUser.active = true
await theUser.save()
toDeleteTokenId.push(realHashToken._id)
}
for (let theId of toDeleteTokenId){
await EmailToken.findByIdAndDelete(theId)
}
req.flash('success','Success! Your account has been activated')
return res.redirect('/')
}
catch(e) {
console.error(e)
// res.sendStatus(500)
req.flash('error', e.message)
return res.redirect('/')
}
}))
CodePudding user response:
I have solved the problem. the User model in this code has post mongoose middleware and within that function, I call next() even though there's no other post middleware after that so the server responds with long responds and the page keeps loading.