From 85a1212da512a7717267b82e5a8abbe794de5dae Mon Sep 17 00:00:00 2001 From: Mrugesh Mohapatra Date: Thu, 23 Jun 2016 11:11:56 +0530 Subject: [PATCH] Error messages for invalid tokens from email links This commit, adds error messages for users hiting the confirm endpoint with invalid, or expired tokens from emailed links. --- common/models/user.js | 55 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/common/models/user.js b/common/models/user.js index 3a6e446834..fa2623ddad 100644 --- a/common/models/user.js +++ b/common/models/user.js @@ -90,13 +90,66 @@ module.exports = function(User) { }); debug('setting up user hooks'); + + User.beforeRemote('confirm', function(ctx, _, next) { + + if (!ctx.req.query) { + return ctx.res.redirect('/'); + } + + const uid = ctx.req.query.uid; + const token = ctx.req.query.token; + const redirect = ctx.req.query.redirect; + + return User.findById(uid, (err, user) => { + + if (err || !user) { + ctx.req.flash('error', { + msg: dedent`Oops, something went wrong, please try again later` + }); + return ctx.res.redirect('/'); + } + + if (!user.verificationToken && !user.emailVerified) { + ctx.req.flash('info', { + msg: dedent`Looks like we have your email. But you haven't + verified it yet, please login and request a fresh verification + link.` + }); + return ctx.res.redirect(redirect); + } + + if (!user.verificationToken && user.emailVerified) { + ctx.req.flash('info', { + msg: dedent`Looks like you have already verified your email. + Please login to continue.` + }); + return ctx.res.redirect(redirect); + } + + if (user.verificationToken && user.verificationToken !== token) { + ctx.req.flash('info', { + msg: dedent`Looks like you have clicked an invalid link. + Please login and request a fresh one.` + }); + return ctx.res.redirect(redirect); + } + + return next(); + }); + }); + User.afterRemote('confirm', function(ctx) { + if (!ctx.req.query) { + return ctx.res.redirect('/'); + } + const redirect = ctx.req.query.redirect; ctx.req.flash('success', { msg: [ 'Your email has been confirmed!' ] }); - ctx.res.redirect('/'); + return ctx.res.redirect(redirect); }); User.beforeRemote('create', function({ req, res }, _, next) {