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) {