From a5ea7ad87928079c89c7e4a87a1d3eb819e87091 Mon Sep 17 00:00:00 2001 From: Stuart Taylor Date: Thu, 28 Jun 2018 23:04:11 +0100 Subject: [PATCH] feat(unsub-email): Add an annon unsubscribe route --- server/boot/randomAPIs.js | 62 +++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/server/boot/randomAPIs.js b/server/boot/randomAPIs.js index d3ac16c190d..571005cf12a 100644 --- a/server/boot/randomAPIs.js +++ b/server/boot/randomAPIs.js @@ -1,6 +1,10 @@ import request from 'request'; +import { isMongoId } from 'validator'; +import dedent from 'dedent'; + import constantStrings from '../utils/constantStrings.json'; import testimonials from '../resources/testimonials.json'; +import { wrapHandledError } from '../utils/create-handled-error'; const githubClient = process.env.GITHUB_ID; const githubSecret = process.env.GITHUB_SECRET; @@ -14,7 +18,7 @@ module.exports = function(app) { router.get('/twitch', twitch); router.get('/u/:email', unsubscribe); router.get('/unsubscribe/:email', unsubscribe); - router.get('/submit-cat-photo', submitCatPhoto); + router.get('/z', unsubscribeAnon); router.get( '/the-fastest-web-page-on-the-internet', theFastestWebPageOnTheInternet @@ -82,10 +86,6 @@ module.exports = function(app) { }); } - function submitCatPhoto(req, res) { - res.send('Submitted!'); - } - function bootcampCalculator(req, res) { res.render('resources/calculator', { title: 'Coding Bootcamp Cost Calculator' @@ -120,6 +120,56 @@ module.exports = function(app) { res.redirect('https://twitch.tv/freecodecamp'); } + function unsubscribeAnon(req, res, next) { + const { query: { unsubscribeId } } = req; + const isValid = unsubscribeId && isMongoId(unsubscribeId); + if (!isValid) { + throw wrapHandledError( + new Error('unsubscribeId is not a mongo ObjectId'), + { + message: dedent` + Oops... something is not right. We could not unsubscribe that email + address + `, + type: 'danger', + redirectTo: '/' + } + ); + } + User.findOne({ + where: { unsubscribeId } + }, (err, user) => { + if (err) { return next(err); } + if (!user || !user.email) { + throw wrapHandledError( + new Error('No user or user email to unsubscribe'), + { + message: dedent` + We couldn't find a user account to unsubscribe, are you clicking + a link from an email we sent? + `, + type: 'info', + redirectTo: '/' + } + ); + } + return user.update$({ + sendQuincyEmail: false + }).subscribe(() => { + req.flash( + 'info', + 'We\'ve successfully updated your Email preferences.' + ); + return res.redirect('/unsubscribed'); + }, + next, + () => { + return user.manualReload(); + } + ); + }); + } + function unsubscribe(req, res, next) { req.checkParams( 'email', @@ -162,7 +212,7 @@ module.exports = function(app) { req.flash('info', { msg: 'We\'ve successfully updated your Email preferences.' }); - return res.redirect('/unsubscribed/' + req.params.email); + return res.redirect('/unsubscribed'); }) .catch(next); });