Merge branch 'master' into ux-improvements

Conflicts:
	controllers/resources.js
	controllers/user.js
	seed_data/challenges.json
	views/account/show.jade
	views/coursewares/showHTML.jade
	views/coursewares/showJS.jade
	views/partials/bonfires.jade
This commit is contained in:
Michael Q Larson
2015-03-21 16:25:39 -07:00
108 changed files with 9238 additions and 1645 deletions
+4 -3
View File
@@ -23,14 +23,15 @@ exports.returnNextChallenge = function(req, res) {
res.redirect('challenges/0');
}
} else {
res.render('home', {
title: 'Learn to Code and Become a Software Engineer',
});
return res.redirect('../challenges/0');
}
};
exports.returnChallenge = function(req, res) {
var challengeNumber = parseInt(req.params.challengeNumber) || 0;
if (challengeNumber === 2) {
return res.redirect('../challenges/3');
}
if (challengeNumber > highestChallengeNumber) {
req.flash('errors', {
msg: "It looks like you've either completed all the challenges we have available or requested a challenge we don't have."
+166 -29
View File
@@ -1,14 +1,20 @@
var User = require('../models/User'),
var async = require('async'),
User = require('../models/User'),
Challenge = require('./../models/Challenge'),
Bonfire = require('./../models/Bonfire'),
Story = require('./../models/Story'),
Comment = require('./../models/Comment'),
resources = require('./resources.json'),
questions = resources.questions,
steps = resources.steps,
secrets = require('./../config/secrets'),
Challenge = require('./../models/Challenge'),
bonfires = require('../seed_data/bonfires.json');
coursewares = require('../seed_data/coursewares.json');
Client = require('node-rest-client').Client,
client = new Client(),
debug = require('debug')('freecc:cntr:bonfires');
bonfires = require('../seed_data/bonfires.json'),
coursewares = require('../seed_data/coursewares.json'),
moment = require('moment'),
https = require('https'),
debug = require('debug')('freecc:cntr:resources'),
cheerio = require('cheerio'),
request = require('request'),
R = require('ramda');
/**
* GET /
@@ -22,6 +28,45 @@ module.exports = {
});
},
sitemap: function sitemap(req, res, next) {
var appUrl = 'http://www.freecodecamp.com';
var now = moment(new Date()).format('YYYY-MM-DD');
User.find({'profile.username': {'$ne': '' }}, function(err, users) {
if (err) {
debug('User err: ', err);
return next(err);
}
Challenge.find({}, function (err, challenges) {
if (err) {
debug('User err: ', err);
return next(err);
}
Bonfire.find({}, function (err, bonfires) {
if (err) {
debug('User err: ', err);
return next(err);
}
Story.find({}, function (err, stories) {
if (err) {
debug('User err: ', err);
return next(err);
}
res.header('Content-Type', 'application/xml');
res.render('resources/sitemap', {
appUrl: appUrl,
now: now,
users: users,
challenges: challenges,
bonfires: bonfires,
stories: stories
});
});
});
});
});
},
deployAWebsite: function deployAWebsite(req, res) {
res.render('resources/deploy-a-website', {
title: 'Deploy a Dynamic Website in 7 Minutes'
@@ -46,6 +91,12 @@ module.exports = {
});
},
guideToOurNonprofitProjects: function guideToOurNonprofitProjects(req, res) {
res.render('resources/guide-to-our-nonprofit-projects', {
title: 'A guide to our Nonprofit Projects'
});
},
controlShortcuts: function controlShortcuts(req, res) {
res.render('resources/control-shortcuts', {
title: 'These Control Shortcuts will save you Hours'
@@ -81,25 +132,37 @@ module.exports = {
title: 'JavaScript in your Inbox'
});
},
nodeSchoolChallenges: function(req, res) {
res.render('resources/nodeschool-challenges', {
title: 'NodeSchool Challenges'
});
},
githubCalls: function(req, res) {
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 };
client.get('https://api.github.com/repos/freecodecamp/freecodecamp/pulls?client_id=' + secrets.github.clientID + '&client_secret=' + secrets.github.clientSecret, githubHeaders, function(pulls, res3) {
request('https://api.github.com/repos/freecodecamp/freecodecamp/pulls?client_id=' + secrets.github.clientID + '&client_secret=' + secrets.github.clientSecret, githubHeaders, function(err, status1, pulls) {
pulls = pulls ? Object.keys(JSON.parse(pulls)).length : "Can't connect to github";
client.get('https://api.github.com/repos/freecodecamp/freecodecamp/issues?client_id=' + secrets.github.clientID + '&client_secret=' + secrets.github.clientSecret, githubHeaders, function (issues, res4) {
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";
res.send({"issues": issues, "pulls" : pulls});
});
});
},
trelloCalls: function(req, res) {
client.get('https://trello.com/1/boards/BA3xVpz9/cards?key=' + secrets.trello.key, function(trello, res2) {
trello = trello ? (JSON.parse(trello)).length : "Can't connect to to Trello";
trelloCalls: function(req, res, next) {
request('https://trello.com/1/boards/BA3xVpz9/cards?key=' + secrets.trello.key, function(err, status, trello) {
if (err) { return next(err); }
trello = (status && status.statusCode == 200) ? (JSON.parse(trello)).length : "Can't connect to to Trello";
res.send({"trello": trello});
});
},
bloggerCalls: function(req, res) {
client.get('https://www.googleapis.com/blogger/v3/blogs/2421288658305323950/posts?key=' + secrets.blogger.key, function (blog, res5) {
var blog = blog.length > 100 ? JSON.parse(blog) : "";
bloggerCalls: function(req, res, next) {
request('https://www.googleapis.com/blogger/v3/blogs/2421288658305323950/posts?key=' + secrets.blogger.key, function (err, status, blog) {
if (err) { return next(err); }
blog = (status && status.statusCode == 200) ? JSON.parse(blog) : '';
res.send({
blog1Title: blog ? blog["items"][0]["title"] : "Can't connect to Blogger",
blog1Link: blog ? blog["items"][0]["url"] : "http://blog.freecodecamp.com",
@@ -115,7 +178,13 @@ module.exports = {
});
},
about: function(req, res) {
about: function(req, res, next) {
if (req.user) {
if (!req.user.profile.picture || req.user.profile.picture === "https://s3.amazonaws.com/freecodecamp/favicons/apple-touch-icon-180x180.png") {
req.user.profile.picture = "https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png";
req.user.save();
}
}
var date1 = new Date("10/15/2014");
var date2 = new Date();
var progressTimestamps = req.user.progressTimestamps;
@@ -136,20 +205,24 @@ module.exports = {
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var daysRunning = Math.ceil(timeDiff / (1000 * 3600 * 24));
var announcements = resources.announcements;
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
User.count({}, function (err, c3) {
if (err) {
debug('User err: ', err);
next(err);
return next(err);
}
User.count({'points': {'$gt': 53}}, function (err, all) {
if (err) {
debug('User err: ', err);
next(err);
return next(err);
}
res.render('resources/learn-to-code', {
title: 'About Free Code Camp and Our Team of Volunteers',
daysRunning: daysRunning,
c3: c3,
c3: numberWithCommas(c3),
all: all,
announcements: announcements
});
@@ -172,10 +245,6 @@ module.exports = {
return compliments[Math.floor(Math.random() * compliments.length)];
},
numberOfBonfires: function() {
return bonfires.length - 1;
},
allBonfireIds: function() {
return bonfires.map(function(elem) {
return {
@@ -214,7 +283,7 @@ module.exports = {
return {
_id: elem._id,
difficulty: elem.difficulty
}
};
})
.sort(function(a, b) {
return a.difficulty - b.difficulty;
@@ -243,9 +312,77 @@ module.exports = {
},
whichEnvironment: function() {
return process.env.NODE_ENV;
},
getURLTitle: function(url, callback) {
debug('got url in meta scraping function', url);
(function () {
var result = {title: '', image: '', url: '', description: ''};
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var $ = cheerio.load(body);
var metaDescription = $("meta[name='description']");
var metaImage = $("meta[property='og:image']");
var urlImage = metaImage.attr('content') ? metaImage.attr('content') : '';
var description = metaDescription.attr('content') ? metaDescription.attr('content') : '';
result.title = $('title').text().length < 141 ? $('title').text() : $('title').text().slice(0, 137) + " ...";
result.image = urlImage;
result.description = description;
callback(null, result);
} else {
callback('failed');
}
});
})();
},
updateUserStoryPictures: function(userId, picture, username, cb) {
var counter = 0,
foundStories,
foundComments;
Story.find({'author.userId': userId}, function(err, stories) {
if (err) {
return cb(err);
}
foundStories = stories;
counter++;
saveStoriesAndComments();
});
Comment.find({'author.userId': userId}, function(err, comments) {
if (err) {
return cb(err);
}
foundComments = comments;
counter++;
saveStoriesAndComments();
});
function saveStoriesAndComments() {
if (counter !== 2) {
return;
}
var tasks = [];
R.forEach(function(comment) {
comment.author.picture = picture;
comment.author.username = username;
comment.markModified('author');
tasks.push(function(cb) {
comment.save(cb);
});
}, foundComments);
R.forEach(function(story) {
story.author.picture = picture;
story.author.username = username;
story.markModified('author');
tasks.push(function(cb) {
story.save(cb);
});
}, foundStories);
async.parallel(tasks, function(err) {
if (err) { return cb(err); }
cb();
});
}
}
};
+1 -1
View File
@@ -1,7 +1,7 @@
{
"announcements": [
["Some of Code School's courses are no longer free. We're switching to NodeSchool.io for our Node.js and Express.js challenges.", "http://freecodecamp.com/nodeschool-challenges"],
["Screen Hero is now free on Windows and Mac! Follow these special instructions to install it.", "http://freecodecamp.com/install-screenhero"],
["Bonfire is now live with 30+ challenges! If you haven't started CoderByte, do these instead.", "http://freecodecamp.com/bonfires"],
["Once you finish all the challenges, we welcome you to attend our Nonprofit Project Office Hours every Monday and Thursday Night at 9 pm EST.", "https://gitter.im/FreeCodeCamp/NonprofitProjects"]
],
"questions": [{
+431
View File
@@ -0,0 +1,431 @@
var R = require('ramda'),
debug = require('debug')('freecc:cntr:story'),
Story = require('./../models/Story'),
Comment = require('./../models/Comment'),
User = require('./../models/User'),
moment = require('../public/js/lib/moment/moment.js'),
resources = require('./resources'),
mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient,
secrets = require('../config/secrets'),
sanitizeHtml = require('sanitize-html');
function hotRank(timeValue, rank) {
/*
* Hotness ranking algorithm: http://amix.dk/blog/post/19588
* tMS = postedOnDate - foundationTime;
* Ranking...
* f(ts, 1, rank) = log(10)z + (ts)/45000;
*/
var hotness;
var z = Math.log(rank) / Math.log(10);
hotness = z + (timeValue / 115200000);
return hotness;
}
exports.hotJSON = function(req, res) {
var story = Story.find({}).sort({'timePosted': -1}).limit(1000);
story.exec(function(err, stories) {
if (err) {
res.send(500);
return next(err);
}
var foundationDate = 1413298800000;
var sliceVal = stories.length >= 100 ? 100 : stories.length;
return res.json(stories.map(function(elem) {
return elem;
}).sort(function(a, b) {
return hotRank(b.timePosted - foundationDate, b.rank, b.headline) - hotRank(a.timePosted - foundationDate, a.rank, a.headline);
}).slice(0, sliceVal));
});
};
exports.recentJSON = function(req, res, next) {
var story = Story.find({}).sort({'timePosted': -1}).limit(100);
story.exec(function(err, stories) {
if (err) {
res.status(500);
return next(err);
}
res.json(stories);
});
};
exports.hot = function(req, res) {
res.render('stories/index', {
title: 'Hot stories currently trending on Camper News',
page: 'hot'
});
};
exports.submitNew = function(req, res) {
res.render('stories/index', {
title: 'Submit a new story to Camper News',
page: 'submit'
});
};
exports.search = function(req, res) {
res.render('stories/index', {
title: 'Search the archives of Camper News',
page: 'search'
});
};
exports.recent = function(req, res) {
res.render('stories/index', {
title: 'Recently submitted stories on Camper News',
page: 'recent'
});
};
exports.preSubmit = function(req, res) {
var data = req.query;
var cleanData = sanitizeHtml(data.url, {
allowedTags: [],
allowedAttributes: []
}).replace(/&quot;;/g, '"');
if (data.url.replace(/&/g, '&amp;') !== cleanData) {
req.flash('errors', {
msg: 'The data for this post is malformed'
});
return res.render('stories/index', {
page: 'stories/submit'
});
}
var title = data.title || '';
var image = data.image || '';
var description = data.description || '';
return res.render('stories/index', {
title: "Confirm your Camper News story submission",
page: 'storySubmission',
storyURL: data.url,
storyTitle: title,
storyImage: image,
storyMetaDescription: description
});
};
exports.returnIndividualStory = function(req, res, next) {
var dashedName = req.params.storyName;
var storyName = dashedName.replace(/\-/g, ' ');
Story.find({'storyLink' : new RegExp(storyName, 'i')}, function(err, story) {
if (err) {
next(err);
}
if (story.length < 1) {
req.flash('errors', {
msg: "404: We couldn't find a story with that name. Please double check the name."
});
return res.redirect('/stories/');
}
story = story.pop();
var dashedNameFull = story.storyLink.toLowerCase().replace(/\s/g, '-');
if (dashedNameFull !== dashedName) {
return res.redirect('../stories/' + dashedNameFull);
}
var userVoted = false;
try {
var votedObj = story.upVotes.filter(function(a){
return a['upVotedByUsername'] === req.user['profile']['username'];
})
if (votedObj.length > 0){
userVoted = true;
}
} catch(err){
userVoted = false;
}
res.render('stories/index', {
title: story.headline,
link: story.link,
author: story.author,
description: story.description,
rank: story.upVotes.length,
upVotes: story.upVotes,
comments: story.comments,
id: story._id,
timeAgo: moment(story.timePosted).fromNow(),
image: story.image,
page: 'show',
storyMetaDescription: story.metaDescription,
hasUserVoted: userVoted
});
});
};
exports.getStories = function(req, res) {
MongoClient.connect(secrets.db, function(err, database) {
database.collection('stories').find({
"$text": {
"$search": req.body.data.searchValue
}
}, {
headline: 1,
timePosted: 1,
link: 1,
description: 1,
rank: 1,
upVotes: 1,
author: 1,
comments: 1,
image: 1,
storyLink: 1,
metaDescription: 1,
textScore: {
$meta: "textScore"
}
}, {
sort: {
textScore: {
$meta: "textScore"
}
}
}).toArray(function(err, items) {
if (items !== null && items.length !== 0) {
return res.json(items);
}
return res.status(404);
});
});
};
exports.upvote = function(req, res, next) {
var data = req.body.data;
Story.find({'_id': data.id}, function(err, story) {
if (err) {
res.status(500);
return next(err);
}
story = story.pop();
story.rank++;
story.upVotes.push(
{
upVotedBy: data.upVoter._id,
upVotedByUsername: data.upVoter.profile.username
}
);
story.markModified('rank');
story.save();
return res.send(story);
});
};
exports.comments = function(req, res, next) {
var data = req.params.id;
Comment.find({'_id': data}, function(err, comment) {
if (err) {
res.status(500);
return next(err);
}
comment = comment.pop();
return res.send(comment);
});
};
exports.newStory = function(req, res) {
if (!req.user) {
return res.status(500);
}
var url = req.body.data.url;
var cleanURL = sanitizeHtml(url, {
allowedTags: [],
allowedAttributes: []
}).replace(/&quot;/g, '"');
if (cleanURL !== url) {
req.flash('errors', {
msg: "The URL you submitted doesn't appear valid"
});
return res.json({
alreadyPosted: true,
storyURL: '/stories/submit'
});
}
if (url.search(/^https?:\/\//g) === -1) {
url = 'http://' + url;
}
Story.find({'link': url}, function(err, story) {
if (err) {
return res.status(500);
}
if (story.length) {
req.flash('errors', {
msg: "Someone's already posted that link. Here's the discussion."
});
return res.json({
alreadyPosted: true,
storyURL: '/stories/' + story.pop().storyLink
});
}
resources.getURLTitle(url, processResponse);
});
function processResponse(err, story) {
if (err) {
res.json({
alreadyPosted: false,
storyURL: url,
storyTitle: '',
storyImage: '',
storyMetaDescription: ''
});
} else {
res.json({
alreadyPosted: false,
storyURL: url,
storyTitle: story.title,
storyImage: story.image,
storyMetaDescription: story.description
});
}
}
};
exports.storySubmission = function(req, res) {
var data = req.body.data;
if (req.user._id.toString() !== data.author.userId.toString()) {
return res.status(500);
}
var storyLink = data.headline
.replace(/\'/g, '')
.replace(/\"/g, '')
.replace(/,/g, '')
.replace(/[^a-z0-9]/gi, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
var link = data.link;
if (link.search(/^https?:\/\//g) === -1) {
link = 'http://' + link;
}
var story = new Story({
headline: sanitizeHtml(data.headline, {
allowedTags: [],
allowedAttributes: []
}).replace(/&quot;/g, '"'),
timePosted: Date.now(),
link: link,
description: sanitizeHtml(data.description, {
allowedTags: [],
allowedAttributes: []
}).replace(/&quot;/g, '"'),
rank: 1,
upVotes: data.upVotes,
author: data.author,
comments: [],
image: data.image,
storyLink: storyLink,
metaDescription: data.storyMetaDescription
});
story.save(function(err) {
if (err) {
return res.status(500);
}
res.send(JSON.stringify({
storyLink: story.storyLink.replace(/\s/g, '-').toLowerCase()
}));
});
};
exports.commentSubmit = function(req, res) {
var data = req.body.data;
if (req.user._id.toString() !== data.author.userId.toString()) {
return res.status(500);
}
var sanitizedBody = sanitizeHtml(data.body,
{
allowedTags: [],
allowedAttributes: []
}).replace(/&quot;/g, '"');
if (data.body !== sanitizedBody) {
req.flash('errors', {
msg: 'HTML is not allowed'
});
return res.send(true);
}
var comment = new Comment({
associatedPost: data.associatedPost,
body: sanitizedBody,
rank: 0,
upvotes: 0,
author: data.author,
comments: [],
topLevel: true,
commentOn: Date.now()
});
commentSave(comment, Story, res);
};
exports.commentOnCommentSubmit = function(req, res) {
var data = req.body.data;
if (req.user._id.toString() !== data.author.userId.toString()) {
return res.status(500);
}
var sanitizedBody = sanitizeHtml(data.body,
{
allowedTags: [],
allowedAttributes: []
}).replace(/&quot;/g, '"');
if (data.body !== sanitizedBody) {
req.flash('errors', {
msg: 'HTML is not allowed'
});
return res.send(true);
}
var comment = new Comment({
associatedPost: data.associatedPost,
body: sanitizedBody,
rank: 0,
upvotes: 0,
author: data.author,
comments: [],
topLevel: false,
commentOn: Date.now()
});
commentSave(comment, Comment, res);
};
function commentSave(comment, Context, res) {
comment.save(function(err, data) {
if (err) {
return res.status(500);
}
try {
Context.find({'_id': comment.associatedPost}, function (err, associatedStory) {
if (err) {
return res.status(500);
}
associatedStory = associatedStory.pop();
if (associatedStory) {
associatedStory.comments.push(data._id);
associatedStory.save(function (err) {
if (err) {
res.status(500);
}
res.send(true);
});
}
});
} catch (e) {
// delete comment
return res.status(500);
}
});
}
+397 -352
View File
@@ -7,9 +7,10 @@ var _ = require('lodash'),
secrets = require('../config/secrets'),
moment = require('moment'),
Challenge = require('./../models/Challenge'),
debug = require('debug')('freecc:cntr:challenges');
debug = require('debug')('freecc:cntr:challenges'),
resources = require('./resources');
//TODO(Berks): Refactor to use module.exports = {} pattern.
/**
* GET /signin
@@ -17,10 +18,10 @@ var _ = require('lodash'),
*/
exports.getSignin = function(req, res) {
if (req.user) return res.redirect('/');
res.render('account/signin', {
title: 'Free Code Camp Login'
});
if (req.user) return res.redirect('/');
res.render('account/signin', {
title: 'Free Code Camp Login'
});
};
/**
@@ -29,28 +30,28 @@ exports.getSignin = function(req, res) {
*/
exports.postSignin = function(req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password cannot be blank').notEmpty();
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password cannot be blank').notEmpty();
var errors = req.validationErrors();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/signin');
}
passport.authenticate('local', function(err, user, info) {
if (err) return next(err);
if (!user) {
req.flash('errors', { msg: info.message });
return res.redirect('/signin');
if (errors) {
req.flash('errors', errors);
return res.redirect('/signin');
}
req.logIn(user, function(err) {
if (err) return next(err);
req.flash('success', { msg: 'Success! You are logged in.' });
res.redirect(req.session.returnTo || '/');
});
})(req, res, next);
passport.authenticate('local', function(err, user, info) {
if (err) return next(err);
if (!user) {
req.flash('errors', { msg: info.message });
return res.redirect('/signin');
}
req.logIn(user, function(err) {
if (err) return next(err);
req.flash('success', { msg: 'Success! You are logged in.' });
res.redirect(req.session.returnTo || '/');
});
})(req, res, next);
};
/**
@@ -59,8 +60,8 @@ exports.postSignin = function(req, res, next) {
*/
exports.signout = function(req, res) {
req.logout();
res.redirect('/');
req.logout();
res.redirect('/');
};
/**
@@ -69,10 +70,10 @@ exports.signout = function(req, res) {
*/
exports.getEmailSignin = function(req, res) {
if (req.user) return res.redirect('/');
res.render('account/email-signin', {
title: 'Sign in to your Free Code Camp Account'
});
if (req.user) return res.redirect('/');
res.render('account/email-signin', {
title: 'Sign in to your Free Code Camp Account'
});
};
/**
@@ -81,10 +82,10 @@ exports.getEmailSignin = function(req, res) {
*/
exports.getEmailSignup = function(req, res) {
if (req.user) return res.redirect('/');
res.render('account/email-signup', {
title: 'Create Your Free Code Camp Account'
});
if (req.user) return res.redirect('/');
res.render('account/email-signup', {
title: 'Create Your Free Code Camp Account'
});
};
/**
@@ -93,63 +94,95 @@ exports.getEmailSignup = function(req, res) {
*/
exports.postEmailSignup = function(req, res, next) {
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/email-signup');
debug(errors);
}
var user = new User({
email: req.body.email.trim(),
password: req.body.password,
profile : {
username: req.body.username.trim()
req.assert('email', 'valid email required').isEmail();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/email-signup');
}
});
User.findOne({ email: req.body.email }, function(err, existingUser) {
if (err) { return next(err); }
var possibleUserData = req.body;
if (existingUser) {
req.flash('errors', {
msg: 'Account with that email address already exists.'
});
return res.redirect('/email-signup');
if (possibleUserData.password.length < 8) {
req.flash('errors', {
msg: 'Your password is too short'
});
return res.redirect('email-signup');
}
user.save(function(err) {
if (err) { return next(err); }
req.logIn(user, function(err) {
if (err) { return next(err); }
res.redirect('/email-signup');
});
if (possibleUserData.username.length < 5 || possibleUserData.length > 20) {
req.flash('errors', {
msg: 'Your username must be between 5 and 20 characters'
});
return res.redirect('email-signup');
}
var user = new User({
email: req.body.email.trim(),
password: req.body.password,
profile : {
username: req.body.username.trim(),
picture: 'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'
}
});
var transporter = nodemailer.createTransport({
service: 'Mandrill',
auth: {
user: secrets.mandrill.user,
pass: secrets.mandrill.password
}
User.findOne({ email: req.body.email }, function(err, existingEmail) {
if (err) {
return next(err);
}
if (existingEmail) {
req.flash('errors', {
msg: 'Account with that email address already exists.'
});
return res.redirect('/email-signup');
}
User.findOne({'profile.username': req.body.username }, function(err, existingUsername) {
if (err) {
return next(err);
}
if (existingUsername) {
req.flash('errors', {
msg: 'Account with that username already exists.'
});
return res.redirect('/email-signup');
}
user.save(function(err) {
if (err) { return next(err); }
req.logIn(user, function(err) {
if (err) { return next(err); }
res.redirect('/email-signup');
});
});
var transporter = nodemailer.createTransport({
service: 'Mandrill',
auth: {
user: secrets.mandrill.user,
pass: secrets.mandrill.password
}
});
var mailOptions = {
to: user.email,
from: 'Team@freecodecamp.com',
subject: 'Welcome to Free Code Camp!',
text: [
'Greetings from San Francisco!\n\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',
"And if you have a moment, check out our blog: blog.freecodecamp.com.\n",
'Good luck with the challenges!\n\n',
'- the Volunteer Camp Counselor Team'
].join('')
};
transporter.sendMail(mailOptions, function(err) {
if (err) { return err; }
});
});
});
var mailOptions = {
to: user.email,
from: 'Team@freecodecamp.com',
subject: 'Welcome to Free Code Camp!',
text: [
'Greetings from San Francisco!\n\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',
"And if you have a moment, check out our blog: blog.freecodecamp.com.\n",
'Good luck with the challenges!\n\n',
'- the Volunteer Camp Counselor Team'
].join('')
};
transporter.sendMail(mailOptions, function(err) {
if (err) { return err; }
});
});
};
/**
@@ -168,7 +201,7 @@ exports.getStreak = function(req, res) {
exports.getAccount = function(req, res) {
res.render('account/account', {
title: 'Manage your Free Code Camp Account'
title: 'Manage your Free Code Camp Account'
});
};
@@ -176,9 +209,9 @@ exports.getAccount = function(req, res) {
* Angular API Call
*/
exports.getAccountAngular = function(req, res) {
exports.getAccountAngular = function(req, res) {
res.json({
user: req.user
user: req.user
});
};
@@ -187,13 +220,13 @@ exports.getAccount = function(req, res) {
*/
exports.checkUniqueUsername = function(req, res) {
User.count({'profile.username': req.params.username.toLowerCase()}, function (err, data) {
if (data == 1) {
return res.send(true);
} else {
return res.send(false);
}
});
User.count({'profile.username': req.params.username.toLowerCase()}, function (err, data) {
if (data == 1) {
return res.send(true);
} else {
return res.send(false);
}
});
};
/**
@@ -214,13 +247,13 @@ exports.checkExistingUsername = function(req, res) {
*/
exports.checkUniqueEmail = function(req, res) {
User.count({'email': decodeURIComponent(req.params.email).toLowerCase()}, function (err, data) {
if (data == 1) {
return res.send(true);
} else {
return res.send(false);
}
});
User.count({'email': decodeURIComponent(req.params.email).toLowerCase()}, function (err, data) {
if (data == 1) {
return res.send(true);
} else {
return res.send(false);
}
});
};
@@ -309,66 +342,78 @@ exports.updateProgress = function(req, res) {
*/
exports.postUpdateProfile = function(req, res, next) {
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/account');
}
User.findOne({ email: req.body.email }, function(err, existingEmail) {
if (err) {
return next(err);
}
var user = req.user;
if (existingEmail && existingEmail.email != user.email) {
req.flash('errors', {
msg: "An account with that email address already exists."
});
return res.redirect('/account');
}
User.findOne({ username: req.body.username }, function(err, existingUsername) {
if (err) {
return next(err);
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/account');
}
var user = req.user;
if (existingUsername && existingUsername.profile.username != user.profile.username) {
req.flash('errors', {
msg: 'An account with that username already exists.'
});
return res.redirect('/account');
}
var user = req.user;
user.email = req.body.email.trim() || '';
user.profile.name = req.body.name.trim() || '';
user.profile.username = req.body.username.trim() || '';
user.profile.location = req.body.location.trim() || '';
user.profile.githubProfile = req.body.githubProfile.trim() || '';
user.profile.linkedinProfile = req.body.linkedinProfile.trim() || '';
user.profile.codepenProfile = req.body.codepenProfile.trim() || '';
user.profile.twitterHandle = req.body.twitterHandle.trim() || '';
user.profile.bio = req.body.bio.trim() || '';
user.profile.picture = req.body.picture.trim() || '';
user.portfolio.website1Title = req.body.website1Title.trim() || '';
user.portfolio.website1Link = req.body.website1Link.trim() || '';
user.portfolio.website1Image = req.body.website1Image.trim() || '';
user.portfolio.website2Title = req.body.website2Title.trim() || '';
user.portfolio.website2Link = req.body.website2Link.trim() || '';
user.portfolio.website2Image = req.body.website2Image.trim() || '';
user.portfolio.website3Title = req.body.website3Title.trim() || '';
user.portfolio.website3Link = req.body.website3Link.trim() || '';
user.portfolio.website3Image = req.body.website3Image.trim() || '';
User.findOne({ email: req.body.email }, function(err, existingEmail) {
if (err) {
return next(err);
}
var user = req.user;
if (existingEmail && existingEmail.email != user.email) {
req.flash('errors', {
msg: "An account with that email address already exists."
});
return res.redirect('/account');
}
User.findOne({ 'profile.username': req.body.username }, function(err, existingUsername) {
if (err) {
return next(err);
}
var user = req.user;
if (existingUsername && existingUsername.profile.username !== user.profile.username) {
req.flash('errors', {
msg: 'An account with that username already exists.'
});
return res.redirect('/account');
}
user.email = req.body.email.trim() || '';
user.profile.name = req.body.name.trim() || '';
user.profile.username = req.body.username.trim() || '';
user.profile.location = req.body.location.trim() || '';
user.profile.githubProfile = req.body.githubProfile.trim() || '';
user.profile.linkedinProfile = req.body.linkedinProfile.trim() || '';
user.profile.codepenProfile = req.body.codepenProfile.trim() || '';
user.profile.twitterHandle = req.body.twitterHandle.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.portfolio.website1Title = req.body.website1Title.trim() || '';
user.portfolio.website1Link = req.body.website1Link.trim() || '';
user.portfolio.website1Image = req.body.website1Image.trim() || '';
user.portfolio.website2Title = req.body.website2Title.trim() || '';
user.portfolio.website2Link = req.body.website2Link.trim() || '';
user.portfolio.website2Image = req.body.website2Image.trim() || '';
user.portfolio.website3Title = req.body.website3Title.trim() || '';
user.portfolio.website3Link = req.body.website3Link.trim() || '';
user.portfolio.website3Image = req.body.website3Image.trim() || '';
user.save(function (err) {
if (err) return next(err);
req.flash('success', {msg: 'Profile information updated.'});
res.redirect('/account');
user.save(function (err) {
if (err) {
return next(err);
}
resources.updateUserStoryPictures(
user._id.toString(),
user.profile.picture,
user.profile.username,
function(err) {
if (err) { return next(err); }
req.flash('success', {
msg: 'Profile information updated.'
});
res.redirect('/account');
}
);
});
});
});
});
});
});
};
/**
@@ -377,29 +422,29 @@ exports.postUpdateProfile = function(req, res, next) {
*/
exports.postUpdatePassword = function(req, res, next) {
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirmPassword', 'Passwords do not match')
.equals(req.body.password);
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirmPassword', 'Passwords do not match')
.equals(req.body.password);
var errors = req.validationErrors();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/account');
}
if (errors) {
req.flash('errors', errors);
return res.redirect('/account');
}
User.findById(req.user.id, function(err, user) {
if (err) { return next(err); }
User.findById(req.user.id, function(err, user) {
if (err) { return next(err); }
user.password = req.body.password;
user.password = req.body.password;
user.save(function(err) {
if (err) { return next(err); }
user.save(function(err) {
if (err) { return next(err); }
req.flash('success', { msg: 'Password has been changed.' });
res.redirect('/account');
req.flash('success', { msg: 'Password has been changed.' });
res.redirect('/account');
});
});
});
};
/**
@@ -408,12 +453,12 @@ exports.postUpdatePassword = function(req, res, next) {
*/
exports.postDeleteAccount = function(req, res, next) {
User.remove({ _id: req.user.id }, function(err) {
if (err) { return next(err); }
req.logout();
req.flash('info', { msg: 'Your account has been deleted.' });
res.redirect('/');
});
User.remove({ _id: req.user.id }, function(err) {
if (err) { return next(err); }
req.logout();
req.flash('info', { msg: 'Your account has been deleted.' });
res.redirect('/');
});
};
/**
@@ -422,22 +467,22 @@ exports.postDeleteAccount = function(req, res, next) {
*/
exports.getOauthUnlink = function(req, res, next) {
var provider = req.params.provider;
User.findById(req.user.id, function(err, user) {
if (err) { return next(err); }
var provider = req.params.provider;
User.findById(req.user.id, function(err, user) {
if (err) { return next(err); }
user[provider] = undefined;
user.tokens =
_.reject(user.tokens, function(token) {
return token.kind === provider;
});
user[provider] = undefined;
user.tokens =
_.reject(user.tokens, function(token) {
return token.kind === provider;
});
user.save(function(err) {
if (err) { return next(err); }
req.flash('info', { msg: provider + ' account has been unlinked.' });
res.redirect('/account');
user.save(function(err) {
if (err) { return next(err); }
req.flash('info', { msg: provider + ' account has been unlinked.' });
res.redirect('/account');
});
});
});
};
/**
@@ -446,25 +491,25 @@ exports.getOauthUnlink = function(req, res, next) {
*/
exports.getReset = function(req, res) {
if (req.isAuthenticated()) {
return res.redirect('/');
}
User
.findOne({ resetPasswordToken: req.params.token })
.where('resetPasswordExpires').gt(Date.now())
.exec(function(err, user) {
if (err) { return next(err); }
if (!user) {
req.flash('errors', {
msg: 'Password reset token is invalid or has expired.'
if (req.isAuthenticated()) {
return res.redirect('/');
}
User
.findOne({ resetPasswordToken: req.params.token })
.where('resetPasswordExpires').gt(Date.now())
.exec(function(err, user) {
if (err) { return next(err); }
if (!user) {
req.flash('errors', {
msg: 'Password reset token is invalid or has expired.'
});
return res.redirect('/forgot');
}
res.render('account/reset', {
title: 'Password Reset',
token: req.params.token
});
});
return res.redirect('/forgot');
}
res.render('account/reset', {
title: 'Password Reset',
token: req.params.token
});
});
};
/**
@@ -473,72 +518,72 @@ exports.getReset = function(req, res) {
*/
exports.postReset = function(req, res, next) {
var errors = req.validationErrors();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('back');
}
async.waterfall([
function(done) {
User
.findOne({ resetPasswordToken: req.params.token })
.where('resetPasswordExpires').gt(Date.now())
.exec(function(err, user) {
if (err) { return next(err); }
if (!user) {
req.flash('errors', {
msg: 'Password reset token is invalid or has expired.'
});
return res.redirect('back');
}
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
if (err) { return done(err); }
req.logIn(user, function(err) {
done(err, user);
});
});
});
},
function(user, done) {
var transporter = nodemailer.createTransport({
service: 'Mandrill',
auth: {
user: secrets.mandrill.user,
pass: secrets.mandrill.password
}
});
var mailOptions = {
to: user.email,
from: 'Team@freecodecamp.com',
subject: 'Your Free Code Camp password has been changed',
text: [
'Hello,\n\n',
'This email is confirming that you requested to',
'reset your password for your Free Code Camp account.',
'This is your email:',
user.email,
'\n'
].join(' ')
};
transporter.sendMail(mailOptions, function(err) {
if (err) { return done(err); }
req.flash('success', {
msg: 'Success! Your password has been changed.'
});
done();
});
if (errors) {
req.flash('errors', errors);
return res.redirect('back');
}
], function(err) {
if (err) { return next(err); }
res.redirect('/');
});
async.waterfall([
function(done) {
User
.findOne({ resetPasswordToken: req.params.token })
.where('resetPasswordExpires').gt(Date.now())
.exec(function(err, user) {
if (err) { return next(err); }
if (!user) {
req.flash('errors', {
msg: 'Password reset token is invalid or has expired.'
});
return res.redirect('back');
}
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
if (err) { return done(err); }
req.logIn(user, function(err) {
done(err, user);
});
});
});
},
function(user, done) {
var transporter = nodemailer.createTransport({
service: 'Mandrill',
auth: {
user: secrets.mandrill.user,
pass: secrets.mandrill.password
}
});
var mailOptions = {
to: user.email,
from: 'Team@freecodecamp.com',
subject: 'Your Free Code Camp password has been changed',
text: [
'Hello,\n\n',
'This email is confirming that you requested to',
'reset your password for your Free Code Camp account.',
'This is your email:',
user.email,
'\n'
].join(' ')
};
transporter.sendMail(mailOptions, function(err) {
if (err) { return done(err); }
req.flash('success', {
msg: 'Success! Your password has been changed.'
});
done();
});
}
], function(err) {
if (err) { return next(err); }
res.redirect('/');
});
};
/**
@@ -547,12 +592,12 @@ exports.postReset = function(req, res, next) {
*/
exports.getForgot = function(req, res) {
if (req.isAuthenticated()) {
return res.redirect('/');
}
res.render('account/forgot', {
title: 'Forgot Password'
});
if (req.isAuthenticated()) {
return res.redirect('/');
}
res.render('account/forgot', {
title: 'Forgot Password'
});
};
/**
@@ -561,80 +606,80 @@ exports.getForgot = function(req, res) {
*/
exports.postForgot = function(req, res, next) {
var errors = req.validationErrors();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/forgot');
}
async.waterfall([
function(done) {
crypto.randomBytes(16, function(err, buf) {
if (err) { return done(err); }
var token = buf.toString('hex');
done(null, token);
});
},
function(token, done) {
User.findOne({
email: req.body.email.toLowerCase()
}, function(err, user) {
if (err) { return done(err); }
if (!user) {
req.flash('errors', {
msg: 'No account with that email address exists.'
});
return res.redirect('/forgot');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
if (err) { return done(err); }
done(null, token, user);
});
});
},
function(token, user, done) {
var transporter = nodemailer.createTransport({
service: 'Mandrill',
auth: {
user: secrets.mandrill.user,
pass: secrets.mandrill.password
}
});
var mailOptions = {
to: user.email,
from: 'Team@freecodecamp.com',
subject: 'Reset your Free Code Camp password',
text: [
'You are receiving this email because you (or someone else)\n',
'requested we reset your Free Code Camp account\'s password.\n\n',
'Please click on the following link, or paste this into your\n',
'browser to complete the process:\n\n',
'http://',
req.headers.host,
'/reset/',
token,
'\n\n',
'If you did not request this, please ignore this email and\n',
'your password will remain unchanged.\n'
].join('')
};
transporter.sendMail(mailOptions, function(err) {
if (err) { return done(err); }
req.flash('info', {
msg: 'An e-mail has been sent to ' +
user.email +
' with further instructions.'
});
done(null, 'done');
});
if (errors) {
req.flash('errors', errors);
return res.redirect('/forgot');
}
], function(err) {
if (err) { return next(err); }
res.redirect('/forgot');
});
async.waterfall([
function(done) {
crypto.randomBytes(16, function(err, buf) {
if (err) { return done(err); }
var token = buf.toString('hex');
done(null, token);
});
},
function(token, done) {
User.findOne({
email: req.body.email.toLowerCase()
}, function(err, user) {
if (err) { return done(err); }
if (!user) {
req.flash('errors', {
msg: 'No account with that email address exists.'
});
return res.redirect('/forgot');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
if (err) { return done(err); }
done(null, token, user);
});
});
},
function(token, user, done) {
var transporter = nodemailer.createTransport({
service: 'Mandrill',
auth: {
user: secrets.mandrill.user,
pass: secrets.mandrill.password
}
});
var mailOptions = {
to: user.email,
from: 'Team@freecodecamp.com',
subject: 'Reset your Free Code Camp password',
text: [
'You are receiving this email because you (or someone else)\n',
'requested we reset your Free Code Camp account\'s password.\n\n',
'Please click on the following link, or paste this into your\n',
'browser to complete the process:\n\n',
'http://',
req.headers.host,
'/reset/',
token,
'\n\n',
'If you did not request this, please ignore this email and\n',
'your password will remain unchanged.\n'
].join('')
};
transporter.sendMail(mailOptions, function(err) {
if (err) { return done(err); }
req.flash('info', {
msg: 'An e-mail has been sent to ' +
user.email +
' with further instructions.'
});
done(null, 'done');
});
}
], function(err) {
if (err) { return next(err); }
res.redirect('/forgot');
});
};