Fix Lint all the controllers

Fix many undefined variables
Fix many unhandled error calls
This commit is contained in:
Berkeley Martinez
2015-05-21 11:07:40 -07:00
parent c5d3aa4bff
commit b58b725f9d
9 changed files with 759 additions and 573 deletions

View File

@ -1,27 +1,39 @@
/*eslint-disable no-unused-vars */
/** /**
* Created by nathanleniz on 5/15/15. * Created by nathanleniz on 5/15/15.
* Copyright (c) 2015, Free Code Camp * Copyright (c) 2015, Free Code Camp
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
var debug = require('debug')('freecc:cntr:challenges'), var R = require('ramda'),
Challenge = require('./../models/Challenge'), Challenge = require('./../models/Challenge'),
User = require('./../models/User'), User = require('./../models/User'),
resources = require('./resources'), resources = require('./resources'),
R = require('ramda'),
moment = require('moment'),
MDNlinks = require('./../seed_data/bonfireMDNlinks'); MDNlinks = require('./../seed_data/bonfireMDNlinks');
var challengeMapWithNames = resources.getChallengeMapWithNames(); var challengeMapWithNames = resources.getChallengeMapWithNames();
@ -31,9 +43,10 @@ function getMDNlinks(links) {
// takes in an array of links, which are strings // takes in an array of links, which are strings
var populatedLinks = []; var populatedLinks = [];
// for each key value, push the corresponding link from the MDNlinks object into a new array // for each key value, push the corresponding link
// from the MDNlinks object into a new array
if (links) { if (links) {
links.forEach(function (value, index) { links.forEach(function (value) {
populatedLinks.push(MDNlinks[value]); populatedLinks.push(MDNlinks[value]);
}); });
} }

View File

@ -1,7 +1,7 @@
var User = require('../models/User'), var R = require('ramda'),
resources = require('./resources'),
debug = require('debug')('freecc:cntr:challengeMap'), debug = require('debug')('freecc:cntr:challengeMap'),
R = require('ramda'); User = require('../models/User'),
resources = require('./resources');
var challengeTypes = { var challengeTypes = {
'HTML_CSS_JQ': 0, 'HTML_CSS_JQ': 0,
@ -13,7 +13,7 @@ var challengeTypes = {
}; };
module.exports = { module.exports = {
challengeMap: function challengeMap(req, res) { challengeMap: function challengeMap(req, res, next) {
var completedList = []; var completedList = [];
if (req.user) { if (req.user) {
@ -76,10 +76,10 @@ module.exports = {
}); });
function numberWithCommas(x) { function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} }
var date1 = new Date("10/15/2014"); var date1 = new Date('10/15/2014');
var date2 = new Date(); var date2 = new Date();
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24)); var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24));

View File

@ -0,0 +1,3 @@
{
"gitHubUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1521.3 Safari/537.36"
}

View File

@ -1,8 +1,6 @@
var _ = require('lodash'), var R = require('ramda'),
debug = require('debug')('freecc:cntr:fieldGuide'),
FieldGuide = require('./../models/FieldGuide'), FieldGuide = require('./../models/FieldGuide'),
resources = require('./resources'), resources = require('./resources');
R = require('ramda');
exports.returnIndividualFieldGuide = function(req, res, next) { exports.returnIndividualFieldGuide = function(req, res, next) {
var dashedName = req.params.fieldGuideName; var dashedName = req.params.fieldGuideName;
@ -12,30 +10,37 @@ exports.returnIndividualFieldGuide = function(req, res, next) {
if (req.user) { if (req.user) {
var completed = req.user.completedFieldGuides; var completed = req.user.completedFieldGuides;
var uncompletedFieldGuides = resources.allFieldGuideIds().filter(function (elem) { var uncompletedFieldGuides = resources.allFieldGuideIds()
.filter(function (elem) {
if (completed.indexOf(elem) === -1) { if (completed.indexOf(elem) === -1) {
return elem; return elem;
} }
}); });
req.user.uncompletedFieldGuides = uncompletedFieldGuides; req.user.uncompletedFieldGuides = uncompletedFieldGuides;
// TODO(berks): handle callback properly
req.user.save(); req.user.save();
} }
FieldGuide.find({'name': new RegExp(fieldGuideName, 'i')}, function(err, fieldGuideFromMongo) { FieldGuide.find(
{ name: new RegExp(fieldGuideName, 'i') },
function(err, fieldGuideFromMongo) {
if (err) { if (err) {
next(err); return next(err);
} }
if (fieldGuideFromMongo.length < 1) { if (fieldGuideFromMongo.length < 1) {
req.flash('errors', { req.flash('errors', {
msg: "404: We couldn't find a field guide entry with that name. Please double check the name." msg: "404: We couldn't find a field guide entry with that name. " +
'Please double check the name.'
}); });
return res.redirect('/field-guide'); return res.redirect('/field-guide');
} }
var fieldGuide = R.head(fieldGuideFromMongo); var fieldGuide = R.head(fieldGuideFromMongo);
var dashedNameFull = fieldGuide.name.toLowerCase().replace(/\s/g, '-').replace(/\?/g, ''); var dashedNameFull =
fieldGuide.name.toLowerCase().replace(/\s/g, '-').replace(/\?/g, '');
if (dashedNameFull !== dashedName) { if (dashedNameFull !== dashedName) {
return res.redirect('../field-guide/' + dashedNameFull); return res.redirect('../field-guide/' + dashedNameFull);
} }
@ -44,13 +49,15 @@ exports.returnIndividualFieldGuide = function(req, res, next) {
fieldGuideId: fieldGuide._id, fieldGuideId: fieldGuide._id,
description: fieldGuide.description.join('') description: fieldGuide.description.join('')
}); });
}); }
);
}; };
exports.showAllFieldGuides = function(req, res) { exports.showAllFieldGuides = function(req, res) {
var data = {}; var data = {};
data.fieldGuideList = resources.allFieldGuideNames(); data.fieldGuideList = resources.allFieldGuideNames();
data.fieldGuideIds = resources.allFieldGuideIds(); data.fieldGuideIds = resources.allFieldGuideIds();
if (req.user && req.user.completedFieldGuides) { if (req.user && req.user.completedFieldGuides) {
data.completedFieldGuides = req.user.completedFieldGuides; data.completedFieldGuides = req.user.completedFieldGuides;
} else { } else {
@ -64,16 +71,22 @@ exports.returnNextFieldGuide = function(req, res, next) {
return res.redirect('/field-guide/how-do-i-use-this-guide?'); return res.redirect('/field-guide/how-do-i-use-this-guide?');
} }
var displayedFieldGuides = FieldGuide.find({'_id': req.user.uncompletedFieldGuides[0]}); var displayedFieldGuides =
FieldGuide.find({'_id': req.user.uncompletedFieldGuides[0]});
displayedFieldGuides.exec(function(err, fieldGuide) { displayedFieldGuides.exec(function(err, fieldGuide) {
if (err) { if (err) { return next(err); }
return next(err);
}
fieldGuide = fieldGuide.pop(); fieldGuide = fieldGuide.pop();
if (typeof fieldGuide === 'undefined') { if (typeof fieldGuide === 'undefined') {
if (req.user.completedFieldGuides.length > 0) { if (req.user.completedFieldGuides.length > 0) {
req.flash('success', { req.flash('success', {
msg: "You've read all our current Field Guide entries. You can contribute to our Field Guide <a href='https://github.com/FreeCodeCamp/freecodecamp/blob/master/seed_data/field-guides.json'>here</a>." msg: [
"You've read all our current Field Guide entries. You can ",
'contribute to our Field Guide ',
"<a href='https://github.com/FreeCodeCamp/freecodecamp/blob/",
"staging/seed_data/field-guides.json'>here</a>."
].join('')
}); });
} }
return res.redirect('../field-guide/how-do-i-use-this-guide?'); return res.redirect('../field-guide/how-do-i-use-this-guide?');
@ -94,12 +107,10 @@ exports.completedFieldGuide = function (req, res, next) {
req.user.uncompletedFieldGuides.splice(index, 1); req.user.uncompletedFieldGuides.splice(index, 1);
} }
req.user.save(function (err, user) { req.user.save(function (err) {
if (err) { if (err) {
return next(err); return next(err);
} }
if (user) {
res.send(true); res.send(true);
}
}); });
}; };

View File

@ -1,16 +1,16 @@
/** var message =
* GET / 'Learn to Code JavaScript and get a Coding Job by Helping Nonprofits';
* Home page.
*/
exports.index = function(req, res, next) { exports.index = function(req, res, next) {
if (req.user && !req.user.profile.picture) { if (req.user && !req.user.profile.picture) {
req.user.profile.picture = 'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'; req.user.profile.picture =
'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png';
req.user.save(function(err) { req.user.save(function(err) {
if (err) { return next(err); } if (err) { return next(err); }
res.render('home', { title: message });
}); });
} else {
res.render('home', { title: message });
} }
res.render('home', {
title: 'Learn to Code JavaScript and get a Coding Job by Helping Nonprofits'
});
}; };

View File

@ -1,16 +1,11 @@
var async = require('async'), var moment = require('moment'),
Nonprofit = require('./../models/Nonprofit'), Nonprofit = require('./../models/Nonprofit'),
resources = require('./resources'), resources = require('./resources');
secrets = require('./../config/secrets'),
moment = require('moment'),
debug = require('debug')('freecc:cntr:nonprofits'),
R = require('ramda');
exports.nonprofitsDirectory = function(req, res) { exports.nonprofitsDirectory = function(req, res, next) {
Nonprofit.find({estimatedHours: { $gt: 0 } }, function(err, nonprofits) { Nonprofit.find({estimatedHours: { $gt: 0 } }, function(err, nonprofits) {
if (err) { if (err) { return next(err); }
next(err);
}
res.render('nonprofits/directory', { res.render('nonprofits/directory', {
title: 'Nonprofits we help', title: 'Nonprofits we help',
nonprofits: nonprofits nonprofits: nonprofits
@ -25,12 +20,17 @@ exports.areYouWithARegisteredNonprofit = function(req, res) {
}); });
}; };
exports.areTherePeopleThatAreAlreadyBenefitingFromYourServices = function(req, res) { exports.areTherePeopleThatAreAlreadyBenefitingFromYourServices =
res.render('nonprofits/are-there-people-that-are-already-benefiting-from-your-services', { function(req, res) {
res.render(
'nonprofits/' +
'are-there-people-that-are-already-benefiting-from-your-services',
{
title: 'Are there people already benefiting from your services', title: 'Are there people already benefiting from your services',
step: 2 step: 2
}); }
}; );
};
exports.okWithJavaScript = function(req, res) { exports.okWithJavaScript = function(req, res) {
res.render('nonprofits/ok-with-javascript', { res.render('nonprofits/ok-with-javascript', {
@ -83,11 +83,14 @@ exports.tellUsYourName = function(req, res) {
}; };
exports.yourNonprofitProjectApplicationHasBeenSubmitted = function(req, res) { exports.yourNonprofitProjectApplicationHasBeenSubmitted = function(req, res) {
res.render('nonprofits/your-nonprofit-project-application-has-been-submitted', { res.render(
'nonprofits/your-nonprofit-project-application-has-been-submitted',
{
title: 'Your Nonprofit Project application has been submitted!', title: 'Your Nonprofit Project application has been submitted!',
step: 10, step: 10,
getBackDay: moment().weekday(5).format('dddd') getBackDay: moment().weekday(5).format('dddd')
}); }
);
}; };
exports.otherSolutions = function(req, res) { exports.otherSolutions = function(req, res) {
@ -98,17 +101,19 @@ exports.otherSolutions = function(req, res) {
exports.returnIndividualNonprofit = function(req, res, next) { exports.returnIndividualNonprofit = function(req, res, next) {
var dashedName = req.params.nonprofitName; var dashedName = req.params.nonprofitName;
var nonprofitName = dashedName.replace(/\-/g, ' '); var nonprofitName = dashedName.replace(/\-/g, ' ');
Nonprofit.find({'name': new RegExp(nonprofitName, 'i')}, function(err, nonprofit) { Nonprofit.find(
{ name: new RegExp(nonprofitName, 'i') },
function(err, nonprofit) {
if (err) { if (err) {
next(err); return next(err);
} }
if (nonprofit.length < 1) { if (nonprofit.length < 1) {
req.flash('errors', { req.flash('errors', {
msg: "404: We couldn't find a nonprofit with that name. Please double check the name." msg: "404: We couldn't find a nonprofit with that name. " +
'Please double check the name.'
}); });
return res.redirect('/nonprofits'); return res.redirect('/nonprofits');
@ -116,36 +121,52 @@ exports.returnIndividualNonprofit = function(req, res, next) {
nonprofit = nonprofit.pop(); nonprofit = nonprofit.pop();
var dashedNameFull = nonprofit.name.toLowerCase().replace(/\s/g, '-'); var dashedNameFull = nonprofit.name.toLowerCase().replace(/\s/g, '-');
if (dashedNameFull != dashedName) { if (dashedNameFull !== dashedName) {
return res.redirect('../nonprofit/' + dashedNameFull); return res.redirect('../nonprofit/' + dashedNameFull);
} }
var buttonActive = false; var buttonActive = false;
if (req.user) { if (req.user) {
if (req.user.uncompletedBonfires.length === 0) { if (req.user.uncompletedBonfires.length === 0) {
if (req.user.completedCoursewares.length > 63) { if (req.user.completedCoursewares.length > 63) {
var hasShownInterest = nonprofit.interestedCampers.filter(function ( obj ) { var hasShownInterest =
nonprofit.interestedCampers.filter(function ( obj ) {
return obj.username === req.user.profile.username; return obj.username === req.user.profile.username;
}); });
if (hasShownInterest.length === 0) { if (hasShownInterest.length === 0) {
buttonActive = true; buttonActive = true;
} }
} }
} }
} }
res.render('nonprofits/show', { res.render('nonprofits/show', {
dashedName: dashedNameFull, dashedName: dashedNameFull,
title: nonprofit.name, title: nonprofit.name,
logoUrl: nonprofit.logoUrl, logoUrl: nonprofit.logoUrl,
estimatedHours: nonprofit.estimatedHours, estimatedHours: nonprofit.estimatedHours,
projectDescription: nonprofit.projectDescription, projectDescription: nonprofit.projectDescription,
approvedOther: nonprofit.approvedDeliverables.indexOf('other') > -1,
approvedWebsite: nonprofit.approvedDeliverables.indexOf('website') > -1, approvedOther:
approvedDonor: nonprofit.approvedDeliverables.indexOf('donor') > -1, nonprofit.approvedDeliverables.indexOf('other') > -1,
approvedInventory: nonprofit.approvedDeliverables.indexOf('inventory') > -1, approvedWebsite:
approvedVolunteer: nonprofit.approvedDeliverables.indexOf('volunteer') > -1, nonprofit.approvedDeliverables.indexOf('website') > -1,
approvedForm: nonprofit.approvedDeliverables.indexOf('form') > -1,
approvedCommunity: nonprofit.approvedDeliverables.indexOf('community') > -1, approvedDonor:
approvedELearning: nonprofit.approvedDeliverables.indexOf('eLearning') > -1, nonprofit.approvedDeliverables.indexOf('donor') > -1,
approvedInventory:
nonprofit.approvedDeliverables.indexOf('inventory') > -1,
approvedVolunteer:
nonprofit.approvedDeliverables.indexOf('volunteer') > -1,
approvedForm:
nonprofit.approvedDeliverables.indexOf('form') > -1,
approvedCommunity:
nonprofit.approvedDeliverables.indexOf('community') > -1,
approvedELearning:
nonprofit.approvedDeliverables.indexOf('eLearning') > -1,
websiteLink: nonprofit.websiteLink, websiteLink: nonprofit.websiteLink,
imageUrl: nonprofit.imageUrl, imageUrl: nonprofit.imageUrl,
whatDoesNonprofitDo: nonprofit.whatDoesNonprofitDo, whatDoesNonprofitDo: nonprofit.whatDoesNonprofitDo,
@ -154,7 +175,8 @@ exports.returnIndividualNonprofit = function(req, res, next) {
buttonActive: buttonActive, buttonActive: buttonActive,
currentStatus: nonprofit.currentStatus currentStatus: nonprofit.currentStatus
}); });
}); }
);
}; };
exports.showAllNonprofits = function(req, res) { exports.showAllNonprofits = function(req, res) {
@ -163,19 +185,26 @@ exports.showAllNonprofits = function(req, res) {
res.send(data); res.send(data);
}; };
exports.interestedInNonprofit = function(req, res) { exports.interestedInNonprofit = function(req, res, next) {
if (req.user) { if (req.user) {
Nonprofit.findOne({name: new RegExp(req.params.nonprofitName.replace(/-/, ' '), 'i')}, function(err, nonprofit) { Nonprofit.findOne(
{ name: new RegExp(req.params.nonprofitName.replace(/-/, ' '), 'i') },
function(err, nonprofit) {
if (err) { return next(err); } if (err) { return next(err); }
nonprofit.interestedCampers.push({"username": req.user.profile.username, nonprofit.interestedCampers.push({
"picture": req.user.profile.picture, username: req.user.profile.username,
"timeOfInterest": Date.now() picture: req.user.profile.picture,
timeOfInterest: Date.now()
}); });
nonprofit.save(function(err) { nonprofit.save(function(err) {
if (err) { return done(err); } if (err) { return next(err); }
req.flash('success', { msg: "Thanks for expressing interest in this nonprofit project! We've added you to this project as an interested camper!" }); req.flash('success', {
msg: 'Thanks for expressing interest in this nonprofit project! ' +
"We've added you to this project as an interested camper!"
});
res.redirect('back'); res.redirect('back');
}); });
}); }
);
} }
}; };

View File

@ -1,4 +1,15 @@
var async = require('async'), var async = require('async'),
path = require('path'),
moment = require('moment'),
Twit = require('twit'),
debug = require('debug')('freecc:cntr:resources'),
cheerio = require('cheerio'),
request = require('request'),
R = require('ramda'),
_ = require('lodash'),
fs = require('fs'),
constantStrings = require('constantStrings.json'),
User = require('../models/User'), User = require('../models/User'),
Challenge = require('./../models/Challenge'), Challenge = require('./../models/Challenge'),
Story = require('./../models/Story'), Story = require('./../models/Story'),
@ -8,16 +19,7 @@ var async = require('async'),
resources = require('./resources.json'), resources = require('./resources.json'),
secrets = require('./../config/secrets'), secrets = require('./../config/secrets'),
nonprofits = require('../seed_data/nonprofits.json'), nonprofits = require('../seed_data/nonprofits.json'),
fieldGuides = require('../seed_data/field-guides.json'), fieldGuides = require('../seed_data/field-guides.json');
moment = require('moment'),
Twit = require('twit'),
https = require('https'),
debug = require('debug')('freecc:cntr:resources'),
cheerio = require('cheerio'),
request = require('request'),
R = require('ramda'),
_ = require('lodash'),
fs = require('fs');
/** /**
* Cached values * Cached values
@ -45,11 +47,14 @@ Array.zip = function(left, right, combinerFunction) {
(function() { (function() {
if (!challengeMap) { if (!challengeMap) {
var localChallengeMap = {}; var localChallengeMap = {};
var files = fs.readdirSync(__dirname + '/../seed_data/challenges'); var files = fs.readdirSync(
path.join(__dirname, '/../seed_data/challenges')
);
var keyCounter = 0; var keyCounter = 0;
files = files.map(function (file) { files = files.map(function (file) {
return require(__dirname + return require(
'/../seed_data/challenges/' + file); path.join(__dirname, '/../seed_data/challenges/' + file)
);
}); });
files = files.sort(function (a, b) { files = files.sort(function (a, b) {
return a.order - b.order; return a.order - b.order;
@ -208,13 +213,16 @@ module.exports = {
res.redirect('http://freecode.slack.com'); res.redirect('http://freecode.slack.com');
} else { } else {
res.render('resources/chat', { res.render('resources/chat', {
title: "Watch us code live on Twitch.tv" title: 'Watch us code live on Twitch.tv'
}); });
} }
}, },
catPhotoSubmit: function catPhotoSubmit(req, res) { catPhotoSubmit: function catPhotoSubmit(req, res) {
res.send('Success! You have submitted your cat photo. Return to your website by typing any letter into your code editor.') res.send(
'Success! You have submitted your cat photo. Return to your website ' +
'by typing any letter into your code editor.'
);
}, },
nonprofits: function nonprofits(req, res) { nonprofits: function nonprofits(req, res) {
@ -247,8 +255,8 @@ module.exports = {
}); });
}, },
unsubscribe: function unsubscribe(req, res) { unsubscribe: function unsubscribe(req, res, next) {
User.findOne({email: req.params.email}, function(err, user) { User.findOne({ email: req.params.email }, function(err, user) {
if (user) { if (user) {
if (err) { if (err) {
return next(err); return next(err);
@ -268,52 +276,106 @@ module.exports = {
unsubscribed: function unsubscribed(req, res) { unsubscribed: function unsubscribed(req, res) {
res.render('resources/unsubscribed', { res.render('resources/unsubscribed', {
title: "You have been unsubscribed" title: 'You have been unsubscribed'
}); });
}, },
githubCalls: function(req, res) { githubCalls: function(req, res, next) {
var githubHeaders = {headers: {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1521.3 Safari/537.36'}, port:80 }; var githubHeaders = {
request('https://api.github.com/repos/freecodecamp/freecodecamp/pulls?client_id=' + secrets.github.clientID + '&client_secret=' + secrets.github.clientSecret, githubHeaders, function(err, status1, pulls) { headers: {
pulls = pulls ? Object.keys(JSON.parse(pulls)).length : "Can't connect to github"; 'User-Agent': constantStrings.gitHubUserAgent
request('https://api.github.com/repos/freecodecamp/freecodecamp/issues?client_id=' + secrets.github.clientID + '&client_secret=' + secrets.github.clientSecret, githubHeaders, function (err, status2, issues) { },
issues = ((pulls === parseInt(pulls)) && issues) ? Object.keys(JSON.parse(issues)).length - pulls : "Can't connect to GitHub"; port: 80
res.send({"issues": issues, "pulls" : pulls}); };
}); request(
[
'https://api.github.com/repos/freecodecamp/',
'freecodecamp/pulls?client_id=',
secrets.github.clientID,
'&client_secret=',
secrets.github.clientSecret
].join(''),
githubHeaders,
function(err, status1, pulls) {
if (err) { return next(err); }
pulls = pulls ?
Object.keys(JSON.parse(pulls)).length :
"Can't connect to github";
request(
[
'https://api.github.com/repos/freecodecamp/',
'freecodecamp/issues?client_id=',
secrets.github.clientID,
'&client_secret=',
secrets.github.clientSecret
].join(''),
githubHeaders,
function (err, status2, issues) {
if (err) { return next(err); }
issues = ((pulls === parseInt(pulls, 10)) && issues) ?
Object.keys(JSON.parse(issues)).length - pulls :
"Can't connect to GitHub";
res.send({
issues: issues,
pulls: pulls
}); });
}
);
}
);
}, },
trelloCalls: function(req, res, next) { trelloCalls: function(req, res, next) {
request('https://trello.com/1/boards/BA3xVpz9/cards?key=' + secrets.trello.key, function(err, status, trello) { request(
'https://trello.com/1/boards/BA3xVpz9/cards?key=' +
secrets.trello.key,
function(err, status, trello) {
if (err) { return next(err); } if (err) { return next(err); }
trello = (status && status.statusCode === 200) ? (JSON.parse(trello)) : "Can't connect to to Trello"; trello = (status && status.statusCode === 200) ?
(JSON.parse(trello)) :
"Can't connect to to Trello";
res.end(JSON.stringify(trello)); res.end(JSON.stringify(trello));
}); });
}, },
bloggerCalls: function(req, res, next) { bloggerCalls: function(req, res, next) {
request('https://www.googleapis.com/blogger/v3/blogs/2421288658305323950/posts?key=' + secrets.blogger.key, function (err, status, blog) { request(
'https://www.googleapis.com/blogger/v3/blogs/2421288658305323950/' +
'posts?key=' +
secrets.blogger.key,
function (err, status, blog) {
if (err) { return next(err); } if (err) { return next(err); }
blog = (status && status.statusCode === 200) ? JSON.parse(blog) : "Can't connect to Blogger";
blog = (status && status.statusCode === 200) ?
JSON.parse(blog) :
"Can't connect to Blogger";
res.end(JSON.stringify(blog)); res.end(JSON.stringify(blog));
}); }
);
}, },
about: function(req, res, next) { about: function(req, res, next) {
if (req.user) { if (req.user) {
if (!req.user.profile.picture || req.user.profile.picture === "https://s3.amazonaws.com/freecodecamp/favicons/apple-touch-icon-180x180.png") { if (
req.user.profile.picture = "https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png"; !req.user.profile.picture ||
req.user.profile.picture.indexOf('apple-touch-icon-180x180.png') !== -1
) {
req.user.profile.picture =
'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png';
// TODO(berks): unhandled callback
req.user.save(); req.user.save();
} }
} }
var date1 = new Date("10/15/2014"); var date1 = new Date('10/15/2014');
var date2 = new Date(); var date2 = new Date();
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24)); var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24));
var announcements = resources.announcements; var announcements = resources.announcements;
function numberWithCommas(x) { function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} }
User.count({}, function (err, c3) { User.count({}, function (err, c3) {
if (err) { if (err) {
@ -331,26 +393,28 @@ module.exports = {
}, },
randomPhrase: function() { randomPhrase: function() {
return resources.phrases[Math.floor( return resources.phrases[
Math.random() * resources.phrases.length)]; Math.floor(Math.random() * resources.phrases.length)
];
}, },
randomVerb: function() { randomVerb: function() {
return resources.verbs[Math.floor( return resources.verbs[
Math.random() * resources.verbs.length)]; Math.floor(Math.random() * resources.verbs.length)
];
}, },
randomCompliment: function() { randomCompliment: function() {
return resources.compliments[Math.floor( return resources.compliments[
Math.random() * resources.compliments.length)]; Math.floor(Math.random() * resources.compliments.length)
];
}, },
allFieldGuideIds: function() { allFieldGuideIds: function() {
if (allFieldGuideIds) { if (allFieldGuideIds) {
return allFieldGuideIds; return allFieldGuideIds;
} else { } else {
allFieldGuideIds = fieldGuides. allFieldGuideIds = fieldGuides.map(function (elem) {
map(function (elem) {
return elem._id; return elem._id;
}); });
return allFieldGuideIds; return allFieldGuideIds;
@ -361,11 +425,8 @@ module.exports = {
if (allFieldGuideNames) { if (allFieldGuideNames) {
return allFieldGuideNames; return allFieldGuideNames;
} else { } else {
allFieldGuideNames = fieldGuides. allFieldGuideNames = fieldGuides.map(function (elem) {
map(function (elem) { return { name: elem.name };
return {
name: elem.name
};
}); });
return allFieldGuideNames; return allFieldGuideNames;
} }
@ -375,11 +436,8 @@ module.exports = {
if (allNonprofitNames) { if (allNonprofitNames) {
return allNonprofitNames; return allNonprofitNames;
} else { } else {
allNonprofitNames = nonprofits. allNonprofitNames = nonprofits.map(function (elem) {
map(function (elem) { return { name: elem.name };
return {
name: elem.name
};
}); });
return allNonprofitNames; return allNonprofitNames;
} }
@ -397,15 +455,24 @@ module.exports = {
var $ = cheerio.load(body); var $ = cheerio.load(body);
var metaDescription = $("meta[name='description']"); var metaDescription = $("meta[name='description']");
var metaImage = $("meta[property='og:image']"); var metaImage = $("meta[property='og:image']");
var urlImage = metaImage.attr('content') ? metaImage.attr('content') : ''; var urlImage = metaImage.attr('content') ?
metaImage.attr('content') :
'';
var metaTitle = $('title'); var metaTitle = $('title');
var description = metaDescription.attr('content') ? metaDescription.attr('content') : ''; var description = metaDescription.attr('content') ?
result.title = metaTitle.text().length < 90 ? metaTitle.text() : metaTitle.text().slice(0, 87) + "..."; metaDescription.attr('content') :
'';
result.title = metaTitle.text().length < 90 ?
metaTitle.text() :
metaTitle.text().slice(0, 87) + '...';
result.image = urlImage; result.image = urlImage;
result.description = description; result.description = description;
callback(null, result); callback(null, result);
} else { } else {
callback('failed'); callback(new Error('failed'));
} }
}); });
})(); })();
@ -465,24 +532,33 @@ module.exports = {
} }
}, },
codepenResources: { codepenResources: {
twitter: function(req, res) { twitter: function(req, res, next) {
// sends out random tweets about javascript // sends out random tweets about javascript
var T = new Twit({ var T = new Twit({
consumer_key: secrets.twitter.consumerKey, 'consumer_key': secrets.twitter.consumerKey,
consumer_secret: secrets.twitter.consumerSecret, 'consumer_secret': secrets.twitter.consumerSecret,
access_token: secrets.twitter.token, 'access_token': secrets.twitter.token,
access_token_secret: secrets.twitter.tokenSecret 'access_token_secret': secrets.twitter.tokenSecret
}); });
var screenName;
if (req.params.screenName) { if (req.params.screenName) {
screenName = req.params.screenName; screenName = req.params.screenName;
} else { } else {
screenName = 'freecodecamp'; screenName = 'freecodecamp';
} }
T.get('statuses/user_timeline', {screen_name: screenName, count:10}, function(err, data, response) { T.get(
'statuses/user_timeline',
{
'screen_name': screenName,
count: 10
},
function(err, data) {
if (err) { return next(err); }
return res.json(data); return res.json(data);
}); }
);
}, },
twitterFCCStream: function() { twitterFCCStream: function() {
// sends out a tweet stream from FCC's account // sends out a tweet stream from FCC's account

View File

@ -1,16 +1,13 @@
/* eslint-disable no-catch-shadow, no-unused-vars */ var moment = require('moment'),
var R = require('ramda'), mongodb = require('mongodb'),
debug = require('debug')('freecc:cntr:story'), nodemailer = require('nodemailer'),
sanitizeHtml = require('sanitize-html'),
MongoClient = mongodb.MongoClient,
resources = require('./resources'),
secrets = require('../config/secrets'),
Story = require('./../models/Story'), Story = require('./../models/Story'),
Comment = require('./../models/Comment'), Comment = require('./../models/Comment'),
User = require('./../models/User'), User = require('./../models/User');
moment = require('moment'),
resources = require('./resources'),
mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient,
secrets = require('../config/secrets'),
nodemailer = require('nodemailer'),
sanitizeHtml = require('sanitize-html');
function hotRank(timeValue, rank) { function hotRank(timeValue, rank) {
/* /*
@ -128,7 +125,8 @@ exports.returnIndividualStory = function(req, res, next) {
if (story.length < 1) { if (story.length < 1) {
req.flash('errors', { req.flash('errors', {
msg: "404: We couldn't find a story with that name. Please double check the name." msg: "404: We couldn't find a story with that name. " +
'Please double check the name.'
}); });
return res.redirect('/news/'); return res.redirect('/news/');
@ -148,7 +146,7 @@ exports.returnIndividualStory = function(req, res, next) {
if (votedObj.length > 0) { if (votedObj.length > 0) {
userVoted = true; userVoted = true;
} }
} catch(err) { } catch(e) {
userVoted = false; userVoted = false;
} }
res.render('stories/index', { res.render('stories/index', {
@ -229,15 +227,14 @@ exports.upvote = function(req, res, next) {
); );
story.markModified('rank'); story.markModified('rank');
story.save(); story.save();
User.find({'_id': story.author.userId}, function(err, user) { User.find({ '_id': story.author.userId }, function(err, user) {
'use strict';
if (err) { if (err) {
return next(err); return next(err);
} }
user = user.pop(); user = user.pop();
user.progressTimestamps.push(Date.now() || 0); user.progressTimestamps.push(Date.now() || 0);
user.save(function (err, user) { user.save(function (err) {
req.user.save(function (err, user) { req.user.save(function (err) {
if (err) { if (err) {
return next(err); return next(err);
} }
@ -339,7 +336,9 @@ exports.storySubmission = function(req, res, next) {
if (link.search(/^https?:\/\//g) === -1) { if (link.search(/^https?:\/\//g) === -1) {
link = 'http://' + link; link = 'http://' + link;
} }
Story.count({'storyLink': new RegExp('^' + storyLink + '(?: [0-9]+)?$', 'i')}, function (err, storyCount) { Story.count(
{ storyLink: new RegExp('^' + storyLink + '(?: [0-9]+)?$', 'i') },
function (err, storyCount) {
if (err) { if (err) {
return res.status(500); return res.status(500);
} }
@ -384,7 +383,7 @@ exports.storySubmission = function(req, res, next) {
return res.status(500); return res.status(500);
} }
req.user.progressTimestamps.push(Date.now() || 0); req.user.progressTimestamps.push(Date.now() || 0);
req.user.save(function (err, user) { req.user.save(function (err) {
if (err) { if (err) {
return next(err); return next(err);
} }
@ -393,7 +392,8 @@ exports.storySubmission = function(req, res, next) {
storyLink: story.storyLink.replace(/\s/g, '-').toLowerCase() storyLink: story.storyLink.replace(/\s/g, '-').toLowerCase()
})); }));
}); });
}); }
);
}; };
exports.commentSubmit = function(req, res, next) { exports.commentSubmit = function(req, res, next) {
@ -513,8 +513,11 @@ exports.storySubmission = function(req, res, next) {
return next(err); return next(err);
} }
try { try {
// Based on the context retrieve the parent object of the comment (Story/Comment) // Based on the context retrieve the parent
Context.find({'_id': data.associatedPost}, function (err, associatedContext) { // object of the comment (Story/Comment)
Context.find(
{ '_id': data.associatedPost },
function (err, associatedContext) {
if (err) { if (err) {
return next(err); return next(err);
} }
@ -529,12 +532,21 @@ exports.storySubmission = function(req, res, next) {
}); });
} }
// Find the author of the parent object // Find the author of the parent object
User.findOne({'profile.username': associatedContext.author.username}, function(err, recipient) { User.findOne(
{ 'profile.username': associatedContext.author.username },
function(err, recipient) {
if (err) { if (err) {
return next(err); return next(err);
} }
// If the emails of both authors differ, only then proceed with email notification // If the emails of both authors differ,
if (typeof data.author !== 'undefined' && data.author.email && typeof recipient !== 'undefined' && recipient.email && (data.author.email !== recipient.email)) { // only then proceed with email notification
if (
typeof data.author !== 'undefined' &&
data.author.email &&
typeof recipient !== 'undefined' &&
recipient.email &&
(data.author.email !== recipient.email)
) {
var transporter = nodemailer.createTransport({ var transporter = nodemailer.createTransport({
service: 'Mandrill', service: 'Mandrill',
auth: { auth: {
@ -546,11 +558,16 @@ exports.storySubmission = function(req, res, next) {
var mailOptions = { var mailOptions = {
to: recipient.email, to: recipient.email,
from: 'Team@freecodecamp.com', from: 'Team@freecodecamp.com',
subject: data.author.username + ' replied to your post on Camper News', subject: data.author.username +
' replied to your post on Camper News',
text: [ text: [
'Just a quick heads-up: ' + data.author.username + ' replied to you on Camper News.', 'Just a quick heads-up: ',
data.author.username,
' replied to you on Camper News.',
'You can keep this conversation going.', 'You can keep this conversation going.',
'Just head back to the discussion here: http://freecodecamp.com/news/' + data.originalStoryLink, 'Just head back to the discussion here: ',
'http://freecodecamp.com/news/',
data.originalStoryLink,
'- the Free Code Camp Volunteer Team' '- the Free Code Camp Volunteer Team'
].join('\n') ].join('\n')
}; };
@ -561,10 +578,11 @@ exports.storySubmission = function(req, res, next) {
} }
}); });
} }
}); }
}); );
}
);
} catch (e) { } catch (e) {
// delete comment
return next(err); return next(err);
} }
}); });

View File

@ -102,8 +102,6 @@ exports.getEmailSignup = function(req, res) {
*/ */
exports.postEmailSignup = function(req, res, next) { exports.postEmailSignup = function(req, res, next) {
req.assert('email', 'valid email required').isEmail(); req.assert('email', 'valid email required').isEmail();
var errors = req.validationErrors(); var errors = req.validationErrors();
@ -134,7 +132,8 @@ exports.postEmailSignup = function(req, res, next) {
password: req.body.password, password: req.body.password,
profile: { profile: {
username: req.body.username.trim(), username: req.body.username.trim(),
picture: 'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png' picture:
'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'
} }
}); });
@ -149,7 +148,9 @@ exports.postEmailSignup = function(req, res, next) {
}); });
return res.redirect('/email-signup'); return res.redirect('/email-signup');
} }
User.findOne({'profile.username': req.body.username }, function(err, existingUsername) { User.findOne(
{ 'profile.username': req.body.username },
function(err, existingUsername) {
if (err) { if (err) {
return next(err); return next(err);
} }
@ -181,8 +182,10 @@ exports.postEmailSignup = function(req, res, next) {
text: [ text: [
'Greetings from San Francisco!\n\n', 'Greetings from San Francisco!\n\n',
'Thank you for joining our community.\n', 'Thank you for joining our community.\n',
'Feel free to email us at this address if you have any questions about Free Code Camp.\n', 'Feel free to email us at this address if you have ',
'And if you have a moment, check out our blog: blog.freecodecamp.com.\n', 'any questions about Free Code Camp.\n',
'And if you have a moment, check out our blog: ',
'blog.freecodecamp.com.\n',
'Good luck with the challenges!\n\n', 'Good luck with the challenges!\n\n',
'- the Volunteer Camp Counselor Team' '- the Volunteer Camp Counselor Team'
].join('') ].join('')
@ -220,9 +223,11 @@ exports.getAccountAngular = function(req, res) {
*/ */
exports.checkUniqueUsername = function(req, res, next) { exports.checkUniqueUsername = function(req, res, next) {
User.count({'profile.username': req.params.username.toLowerCase()}, function (err, data) { User.count(
{ 'profile.username': req.params.username.toLowerCase() },
function (err, data) {
if (err) { return next(err); } if (err) { return next(err); }
if (data == 1) { if (data === 1) {
return res.send(true); return res.send(true);
} else { } else {
return res.send(false); return res.send(false);
@ -234,14 +239,17 @@ exports.checkUniqueUsername = function(req, res, next) {
* Existing username check * Existing username check
*/ */
exports.checkExistingUsername = function(req, res, next) { exports.checkExistingUsername = function(req, res, next) {
User.count({'profile.username': req.params.username.toLowerCase()}, function (err, data) { User.count(
{ 'profile.username': req.params.username.toLowerCase() },
function (err, data) {
if (err) { return next(err); } if (err) { return next(err); }
if (data === 1) { if (data === 1) {
return res.send(true); return res.send(true);
} else { } else {
return res.send(false); return res.send(false);
} }
}); }
);
}; };
/** /**
@ -249,14 +257,17 @@ exports.checkExistingUsername = function(req, res, next) {
*/ */
exports.checkUniqueEmail = function(req, res, next) { exports.checkUniqueEmail = function(req, res, next) {
User.count({'email': decodeURIComponent(req.params.email).toLowerCase()}, function (err, data) { User.count(
{ email: decodeURIComponent(req.params.email).toLowerCase() },
function (err, data) {
if (err) { return next(err); } if (err) { return next(err); }
if (data === 1) { if (data === 1) {
return res.send(true); return res.send(true);
} else { } else {
return res.send(false); return res.send(false);
} }
}); }
);
}; };
@ -266,8 +277,13 @@ exports.checkUniqueEmail = function(req, res, next) {
*/ */
exports.returnUser = function(req, res, next) { exports.returnUser = function(req, res, next) {
User.find({'profile.username': req.params.username.toLowerCase()}, function(err, user) { User.find(
if (err) { debug('Username err: ', err); next(err); } { 'profile.username': req.params.username.toLowerCase() },
function(err, user) {
if (err) {
debug('Username err: ', err);
return next(err);
}
if (user[0]) { if (user[0]) {
user = user[0]; user = user[0];
@ -302,14 +318,21 @@ exports.returnUser = function(req, res, next) {
user.currentStreak = 1; user.currentStreak = 1;
var today = moment(Date.now()).format('YYYY-MM-DD'); var today = moment(Date.now()).format('YYYY-MM-DD');
if (moment(today).toString() === moment(timeKeys[0]).toString() || if (
moment(today).toString() === moment(timeKeys[0]).toString() ||
moment(today).subtract(1, 'd').toString() === moment(today).subtract(1, 'd').toString() ===
moment(timeKeys[0]).toString()) { moment(timeKeys[0]).toString()
for (var i = 1; i <= timeKeys.length; i++) { ) {
if (moment(timeKeys[i - 1]).subtract(1, 'd').toString() for (var _i = 1; _i <= timeKeys.length; _i++) {
=== moment(timeKeys[i]).toString()) {
debug(timeKeys[i - 1], timeKeys[i]); if (
moment(timeKeys[_i - 1]).subtract(1, 'd').toString() ===
moment(timeKeys[_i]).toString()
) {
debug(timeKeys[_i - 1], timeKeys[_i]);
tmpLongest++; tmpLongest++;
if (tmpLongest > user.currentStreak) { if (tmpLongest > user.currentStreak) {
user.currentStreak = tmpLongest; user.currentStreak = tmpLongest;
} }
@ -325,7 +348,6 @@ exports.returnUser = function(req, res, next) {
if (err) { if (err) {
return next(err); return next(err);
} }
});
var data = {}; var data = {};
var progressTimestamps = user.progressTimestamps; var progressTimestamps = user.progressTimestamps;
@ -338,6 +360,7 @@ exports.returnUser = function(req, res, next) {
var challenges = user.completedCoursewares.filter(function ( obj ) { var challenges = user.completedCoursewares.filter(function ( obj ) {
return !!obj.solution; return !!obj.solution;
}); });
res.render('account/show', { res.render('account/show', {
title: 'Camper ' + user.profile.username + '\'s portfolio', title: 'Camper ' + user.profile.username + '\'s portfolio',
username: user.profile.username, username: user.profile.username,
@ -366,17 +389,21 @@ exports.returnUser = function(req, res, next) {
}), }),
calender: data, calender: data,
moment: moment, moment: moment,
longestStreak: user.longestStreak + (user.longestStreak === 1 ? " day" : " days"), longestStreak: user.longestStreak +
currentStreak: user.currentStreak + (user.currentStreak === 1 ? " day" : " days") (user.longestStreak === 1 ? ' day' : ' days'),
currentStreak: user.currentStreak +
(user.currentStreak === 1 ? ' day' : ' days')
});
}); });
} else { } else {
req.flash('errors', { req.flash('errors', {
msg: "404: We couldn't find a page with that url. Please double check the link." msg: "404: We couldn't find a page with that url. " +
'Please double check the link.'
}); });
return res.redirect('/'); return res.redirect('/');
} }
}); }
);
}; };
@ -385,9 +412,9 @@ exports.returnUser = function(req, res, next) {
* Update profile information. * Update profile information.
*/ */
exports.updateProgress = function(req, res) { exports.updateProgress = function(req, res, next) {
User.findById(req.user.id, function(err, user) { User.findById(req.user.id, function(err, user) {
if (err) return next(err); if (err) { return next(err); }
user.email = req.body.email || ''; user.email = req.body.email || '';
user.profile.name = req.body.name || ''; user.profile.name = req.body.name || '';
user.profile.gender = req.body.gender || ''; user.profile.gender = req.body.gender || '';
@ -395,7 +422,7 @@ exports.updateProgress = function(req, res) {
user.profile.website = req.body.website || ''; user.profile.website = req.body.website || '';
user.save(function(err) { user.save(function(err) {
if (err) return next(err); if (err) { return next(err); }
req.flash('success', { msg: 'Profile information updated.' }); req.flash('success', { msg: 'Profile information updated.' });
res.redirect('/account'); res.redirect('/account');
}); });
@ -409,8 +436,8 @@ exports.updateProgress = function(req, res) {
exports.postUpdateProfile = function(req, res, next) { exports.postUpdateProfile = function(req, res, next) {
User.findById(req.user.id, function(err, user) { User.findById(req.user.id, function(err) {
if (err) return next(err); if (err) { return next(err); }
var errors = req.validationErrors(); var errors = req.validationErrors();
if (errors) { if (errors) {
req.flash('errors', errors); req.flash('errors', errors);
@ -422,18 +449,23 @@ exports.postUpdateProfile = function(req, res, next) {
return next(err); return next(err);
} }
var user = req.user; var user = req.user;
if (existingEmail && existingEmail.email != user.email) { if (existingEmail && existingEmail.email !== user.email) {
req.flash('errors', { req.flash('errors', {
msg: "An account with that email address already exists." msg: 'An account with that email address already exists.'
}); });
return res.redirect('/account'); return res.redirect('/account');
} }
User.findOne({ 'profile.username': req.body.username }, function(err, existingUsername) { User.findOne(
{ 'profile.username': req.body.username },
function(err, existingUsername) {
if (err) { if (err) {
return next(err); return next(err);
} }
var user = req.user; var user = req.user;
if (existingUsername && existingUsername.profile.username !== user.profile.username) { if (
existingUsername &&
existingUsername.profile.username !== user.profile.username
) {
req.flash('errors', { req.flash('errors', {
msg: 'An account with that username already exists.' msg: 'An account with that username already exists.'
}); });
@ -449,7 +481,10 @@ exports.postUpdateProfile = function(req, res, next) {
user.profile.codepenProfile = req.body.codepenProfile.trim() || ''; user.profile.codepenProfile = req.body.codepenProfile.trim() || '';
user.profile.twitterHandle = req.body.twitterHandle.trim() || ''; user.profile.twitterHandle = req.body.twitterHandle.trim() || '';
user.profile.bio = req.body.bio.trim() || ''; user.profile.bio = req.body.bio.trim() || '';
user.profile.picture = req.body.picture.trim() || 'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png';
user.profile.picture = req.body.picture.trim() ||
'https://s3.amazonaws.com/freecodecamp/' +
'camper-image-placeholder.png';
user.portfolio.website1Title = req.body.website1Title.trim() || ''; user.portfolio.website1Title = req.body.website1Title.trim() || '';
user.portfolio.website1Link = req.body.website1Link.trim() || ''; user.portfolio.website1Link = req.body.website1Link.trim() || '';
user.portfolio.website1Image = req.body.website1Image.trim() || ''; user.portfolio.website1Image = req.body.website1Image.trim() || '';
@ -478,7 +513,8 @@ exports.postUpdateProfile = function(req, res, next) {
} }
); );
}); });
}); }
);
}); });
}); });
}; };
@ -538,7 +574,7 @@ exports.getOauthUnlink = function(req, res, next) {
User.findById(req.user.id, function(err, user) { User.findById(req.user.id, function(err, user) {
if (err) { return next(err); } if (err) { return next(err); }
user[provider] = undefined; user[provider] = null;
user.tokens = user.tokens =
_.reject(user.tokens, function(token) { _.reject(user.tokens, function(token) {
return token.kind === provider; return token.kind === provider;
@ -557,7 +593,7 @@ exports.getOauthUnlink = function(req, res, next) {
* Reset Password page. * Reset Password page.
*/ */
exports.getReset = function(req, res) { exports.getReset = function(req, res, next) {
if (req.isAuthenticated()) { if (req.isAuthenticated()) {
return res.redirect('/'); return res.redirect('/');
} }
@ -607,8 +643,8 @@ exports.postReset = function(req, res, next) {
} }
user.password = req.body.password; user.password = req.body.password;
user.resetPasswordToken = undefined; user.resetPasswordToken = null;
user.resetPasswordExpires = undefined; user.resetPasswordExpires = null;
user.save(function(err) { user.save(function(err) {
if (err) { return done(err); } if (err) { return done(err); }