diff --git a/.jshintignore b/.jshintignore new file mode 100644 index 000000000..41c54fc67 --- /dev/null +++ b/.jshintignore @@ -0,0 +1 @@ +**/ace/**.js diff --git a/.weignore b/.weignore new file mode 100644 index 000000000..41c54fc67 --- /dev/null +++ b/.weignore @@ -0,0 +1 @@ +**/ace/**.js diff --git a/app.js b/app.js index 5c3466c53..fc5880527 100755 --- a/app.js +++ b/app.js @@ -55,9 +55,9 @@ app.use(express.methodOverride()); // Order is very important here (i.e mess with at your own risk) app.use(express.cookieParser()); app.use(express.session({ - secret: sessionSecret, - store: sessionStore -})); + secret: sessionSecret, + store: sessionStore + })); app.use(passport.initialize()); app.use(modifySessions.init(sessionStore)); app.use(app.router); @@ -68,7 +68,6 @@ app.engine('html', require('./libs/muExpress').renderFile(app)); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); - // Setup minification // Order is important here as Ace will fail with an invalid content encoding issue if (process.env.NODE_ENV === 'production') { diff --git a/controllers/_template.js b/controllers/_template.js index 89f32525a..acaec3345 100644 --- a/controllers/_template.js +++ b/controllers/_template.js @@ -28,7 +28,7 @@ exports.example = function (aReq, aRes, aNext) { var tasks = []; //--- - function preRender() { }; + function preRender() { } function render() { aRes.render('pages/_templatePage', options); } function asyncComplete() { preRender(); render(); } @@ -57,7 +57,7 @@ exports.example = function (aReq, aRes, aNext) { function preRender() { // Pagination options.paginationRendered = pagination.renderDefault(aReq); - }; + } function render() { aRes.render('pages/_templatePage', options); } function asyncComplete() { preRender(); render(); } @@ -76,8 +76,9 @@ exports.example = function (aReq, aRes, aNext) { scriptListQuery.find({ isLib: false }); // Scripts: Query: Search - if (aReq.query.q) + if (aReq.query.q) { modelQuery.parseScriptSearchQuery(scriptListQuery, aReq.query.q); + } // Scripts: Query: Sort modelQuery.parseModelListSort(scriptListQuery, aReq.query.orderBy, aReq.query.orderDir, function () { @@ -108,4 +109,3 @@ exports.example = function (aReq, aRes, aNext) { //--- async.parallel(tasks, asyncComplete); }; - diff --git a/controllers/admin.js b/controllers/admin.js index 130af46aa..bc33ac711 100644 --- a/controllers/admin.js +++ b/controllers/admin.js @@ -57,7 +57,8 @@ exports.userAdmin = function (aReq, aRes, aNext) { if (!userIsAdmin(aReq)) { return aNext(); } // You can only see users with a role less than yours - User.find({ role: { $gt: thisUser.role } }, function (aErr, aUsers) { // TODO: STYLEGUIDE.md conformance needed here + // TODO: STYLEGUIDE.md conformance needed here + User.find({ role: { $gt: thisUser.role } }, function (aErr, aUsers) { var i = 0; options.users = []; @@ -95,14 +96,14 @@ exports.adminUserView = function (aReq, aRes, aNext) { // Nothing fancy, just the stringified user object User.findOne({ '_id': id, role: { $gt: thisUser.role } }, function (aErr, aUser) { - if (aErr || !aUser) { return aNext(); } + if (aErr || !aUser) { return aNext(); } - aRes.render('userAdmin', { - user: { - info: JSON.stringify(aUser.toObject(), null, ' ') - } - }); + aRes.render('userAdmin', { + user: { + info: JSON.stringify(aUser.toObject(), null, ' ') + } }); + }); }; var jsonModelMap = { @@ -130,18 +131,21 @@ exports.adminJsonView = function (aReq, aRes, aNext) { options.isMod = authedUser && authedUser.isMod; options.isAdmin = authedUser && authedUser.isAdmin; - if (!options.isAdmin) + if (!options.isAdmin) { return aRes.send(403, { status: 403, message: 'Not an admin.' }); + } var model = jsonModelMap[modelname]; - if (!model) + if (!model) { return aRes.send(400, { status: 400, message: 'Invalid model.' }); + } model.findOne({ _id: id }, function (aErr, aObj) { - if (aErr || !aObj) + if (aErr || !aObj) { return aRes.send(404, { status: 404, message: 'Id doesn\'t exist.' }); + } aRes.json(aObj); }); @@ -232,7 +236,7 @@ exports.adminPage = function (aReq, aRes, aNext) { //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } aRes.render('pages/adminPage', options); }); }; @@ -285,7 +289,7 @@ exports.adminApiKeysPage = function (aReq, aRes, aNext) { //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } aRes.render('pages/adminApiKeysPage', options); }); }; @@ -303,14 +307,15 @@ exports.adminNpmLsView = function (aReq, aRes, aNext) { options.isMod = authedUser && authedUser.isMod; options.isAdmin = authedUser && authedUser.isAdmin; - if (!options.isAdmin) + if (!options.isAdmin) { return aRes.send(403, { status: 403, message: 'Not an admin.' }); + } - exec('npm ls --json', function(aErr, aStdout, aStderr) { - if (aErr) return aRes.send(501, { status: 501, message: 'Not implemented.' }); + exec('npm ls --json', function (aErr, aStdout, aStderr) { + if (aErr) { return aRes.send(501, { status: 501, message: 'Not implemented.' }); } aRes.json(JSON.parse(aStdout)); }); -} +}; // Manage oAuth strategies without having to restart the server // When new keys are added, we load the new strategy @@ -322,7 +327,7 @@ exports.apiAdminUpdate = function (aReq, aRes, aNext) { postStrats = Object.keys(aReq.body).map(function (aPostStrat) { var values = aReq.body[aPostStrat]; - return { name: aPostStrat, id: values[0], key: values[1] } + return { name: aPostStrat, id: values[0], key: values[1] }; }); Strategy.find({}, function (aErr, aStrats) { diff --git a/controllers/auth.js b/controllers/auth.js index 1ff850c45..b338a032a 100644 --- a/controllers/auth.js +++ b/controllers/auth.js @@ -72,30 +72,32 @@ exports.auth = function (aReq, aRes, aNext) { User.findOne({ name: { $regex: new RegExp('^' + username + '$', 'i') } }, function (aErr, aUser) { - var strategies = null; - var strat = null; - - if (aUser) { - strategies = aUser.strategies; - strat = strategies.pop(); - - if (aReq.session.newstrategy) { // authenticate with a new strategy - delete aReq.session.newstrategy; - } else if (!strategy) { // use an existing strategy - strategy = strat; - } else if (strategies.indexOf(strategy) === -1) { - // add a new strategy but first authenticate with existing strategy - aReq.session.newstrategy = strategy; - strategy = strat; - } // else use the strategy that was given in the POST - } + var strategies = null; + var strat = null; + + if (aUser) { + strategies = aUser.strategies; + strat = strategies.pop(); + + if (aReq.session.newstrategy) { + // authenticate with a new strategy + delete aReq.session.newstrategy; + } else if (!strategy) { + // use an existing strategy + strategy = strat; + } else if (strategies.indexOf(strategy) === -1) { + // add a new strategy but first authenticate with existing strategy + aReq.session.newstrategy = strategy; + strategy = strat; + } // else use the strategy that was given in the POST + } - if (!strategy) { - return aRes.redirect('/register'); - } else { - return auth(); - } - }); + if (!strategy) { + return aRes.redirect('/register'); + } else { + return auth(); + } + }); }; exports.callback = function (aReq, aRes, aNext) { @@ -116,21 +118,20 @@ exports.callback = function (aReq, aRes, aNext) { if (openIdStrategies[strategy]) { strategyInstance._verify = function (aId, aDone) { verifyPassport(aId, strategy, username, aReq.session.user, aDone); - } + }; } else { strategyInstance._verify = function (aToken, aRefreshOrSecretToken, aProfile, aDone) { - aReq.session.profile = aProfile; - verifyPassport(aProfile.id, strategy, username, aReq.session.user, aDone); - } + aReq.session.profile = aProfile; + verifyPassport(aProfile.id, strategy, username, aReq.session.user, aDone); + }; } // This callback will happen after the verify routine var authenticate = passport.authenticate(strategy, function (aErr, aUser, aInfo) { if (aErr) { return aNext(aErr); } if (!aUser) { - return aRes.redirect(doneUrl + (doneUrl === '/' ? 'register' : '') - + '?authfail'); + return aRes.redirect(doneUrl + (doneUrl === '/' ? 'register' : '') + '?authfail'); } aReq.logIn(aUser, function (aErr) { @@ -161,4 +162,4 @@ exports.callback = function (aReq, aRes, aNext) { }); authenticate(aReq, aRes, aNext); -} +}; diff --git a/controllers/discussion.js b/controllers/discussion.js index 4a9fb3455..e15c7631a 100644 --- a/controllers/discussion.js +++ b/controllers/discussion.js @@ -83,7 +83,7 @@ exports.categoryListPage = function (aReq, aRes, aNext) { //--- async.parallel(tasks, function (aErr) { - if (aErr) aNext(); + if (aErr) { aNext(); } //--- PreRender // discussionList @@ -124,8 +124,9 @@ exports.list = function (aReq, aRes, aNext) { var categorySlug = aReq.route.params.category; var category = _.findWhere(categories, { slug: categorySlug }); - if (!category) + if (!category) { return aNext(); + } // var options = {}; @@ -171,7 +172,7 @@ exports.list = function (aReq, aRes, aNext) { //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } //--- PreRender // discussionList @@ -211,8 +212,9 @@ exports.show = function (aReq, aRes, aNext) { var topic = aReq.route.params.topic; var category = _.findWhere(categories, { slug: categorySlug }); - if (!category) + if (!category) { return aNext(); + } findDiscussion(category.slug, topic, function (aDiscussionData) { if (!aDiscussionData) { return aNext(); } @@ -257,7 +259,7 @@ exports.show = function (aReq, aRes, aNext) { //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } //--- PreRender // commentList @@ -280,14 +282,16 @@ exports.show = function (aReq, aRes, aNext) { exports.newTopic = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) + if (!authedUser) { return aRes.redirect('/login'); + } var categorySlug = aReq.route.params.category; var category = _.findWhere(categories, { slug: categorySlug }); - if (!category) + if (!category) { return aNext(); + } // var options = {}; @@ -394,16 +398,18 @@ exports.postTopic = postTopic; exports.createTopic = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) + if (!authedUser) { return aRes.redirect('/login'); + } var categorySlug = aReq.route.params.category; var topic = aReq.body['discussion-topic']; var content = aReq.body['comment-content']; var category = _.findWhere(categories, { slug: categorySlug }); - if (!category) + if (!category) { return aNext(); + } // var options = {}; @@ -423,8 +429,8 @@ exports.createTopic = function (aReq, aRes, aNext) { postTopic(authedUser, category.slug, topic, content, false, function (aDiscussion) { if (!aDiscussion) { return exports.newTopic(aReq, aRes, aNext); } - aRes.redirect(encodeURI(aDiscussion.path - + (aDiscussion.duplicateId ? '_' + aDiscussion.duplicateId : ''))); + aRes.redirect(encodeURI(aDiscussion.path + + (aDiscussion.duplicateId ? '_' + aDiscussion.duplicateId : ''))); }); }; @@ -442,8 +448,8 @@ exports.createComment = function (aReq, aRes, aNext) { if (!discussion) { return aNext(); } postComment(user, discussion, content, false, function (err, discussion) { - aRes.redirect(encodeURI(discussion.path - + (discussion.duplicateId ? '_' + discussion.duplicateId : ''))); + aRes.redirect(encodeURI(discussion.path + + (discussion.duplicateId ? '_' + discussion.duplicateId : ''))); }); }); }; diff --git a/controllers/document.js b/controllers/document.js index 60e5b71f1..596563c7f 100644 --- a/controllers/document.js +++ b/controllers/document.js @@ -25,7 +25,6 @@ exports.view = function (aReq, aRes, aNext) { options.isMod = authedUser && authedUser.isMod; options.isAdmin = authedUser && authedUser.isAdmin; - if (document) { documentPath = 'views/includes/documents'; @@ -90,10 +89,9 @@ exports.view = function (aReq, aRes, aNext) { aCallback(null); }); } - ], aCallback) + ], aCallback); }); - } - else { + } else { // Page metadata pageMetadata(options, ['About', 'About']); @@ -118,7 +116,7 @@ exports.view = function (aReq, aRes, aNext) { return statusCodePage(aReq, aRes, aNext, { statusCode: aErr.statusCode, statusMessage: aErr.statusMessage - }) + }); } aRes.render('pages/documentPage', options); diff --git a/controllers/group.js b/controllers/group.js index 29997ff1a..66506501b 100644 --- a/controllers/group.js +++ b/controllers/group.js @@ -60,7 +60,8 @@ exports.addScriptToGroups = function (aScript, aGroupNames, aCallback) { return aScript.save(aCallback); } - Group.find({ name: { $in: aGroupNames } }, function (aErr, aGroups) { // TODO: STYLEGUIDE.md conformance needed here + // TODO: STYLEGUIDE.md conformance needed here + Group.find({ name: { $in: aGroupNames } }, function (aErr, aGroups) { var existingGroups = null; var existingNames = null; var newGroup = null; @@ -82,8 +83,8 @@ exports.addScriptToGroups = function (aScript, aGroupNames, aCallback) { // Name of a group that doesn't exist newGroup = cleanGroupName(aGroupNames.filter(function (aName) { - return existingNames.indexOf(aName) === -1; - }).shift()); + return existingNames.indexOf(aName) === -1; + }).shift()); // Add script to exising groups tasks.push(function (aCallback) { @@ -118,13 +119,13 @@ exports.addScriptToGroups = function (aScript, aGroupNames, aCallback) { aGroups.forEach(function (aGroup) { Script.find({ _id: { $in: aGroup._scriptIds } }, // TODO: STYLEGUIDE.md conformance needed here function (aErr, aScripts) { - if (aErr || aScripts.length < 2) { return; } + if (aErr || aScripts.length < 2) { return; } - aGroup.size = aScripts.length; - aGroup.rating = getRating(aScripts); - aGroup.updated = new Date(); - aGroup.save(function () { }); - } + aGroup.size = aScripts.length; + aGroup.rating = getRating(aScripts); + aGroup.updated = new Date(); + aGroup.save(function () { }); + } ); }); }); @@ -154,7 +155,7 @@ exports.list = function (aReq, aRes) { if (options.groupList) { pageMetadata(options, 'Groups', null, _.pluck(options.groupList, 'name')); } - }; + } function render() { aRes.render('pages/groupListPage', options); } function asyncComplete() { preRender(); render(); } @@ -264,7 +265,7 @@ exports.view = function (aReq, aRes, aNext) { } else if (options.isUserScriptListPage) { options.scriptListIsEmptyMessage = 'This user hasn\'t added any scripts yet.'; } - }; + } function render() { aRes.render('pages/groupScriptListPage', options); } function asyncComplete() { preRender(); render(); } diff --git a/controllers/index.js b/controllers/index.js index 932434320..ad1260fd9 100644 --- a/controllers/index.js +++ b/controllers/index.js @@ -68,13 +68,13 @@ exports.home = function (aReq, aRes) { .limit(25); // Announcements - options.announcementsCategory = _.findWhere(discussionLib.categories, {slug: 'announcements'}); + options.announcementsCategory = _.findWhere(discussionLib.categories, { slug: 'announcements' }); options.announcementsCategory = modelParser.parseCategory(options.announcementsCategory); // announcementsDiscussionListQuery var announcementsDiscussionListQuery = Discussion.find(); announcementsDiscussionListQuery - .and({category: options.announcementsCategory.slug}) + .and({ category: options.announcementsCategory.slug }) .sort('-created') .limit(5); @@ -139,7 +139,7 @@ exports.home = function (aReq, aRes) { pageMetadata(options, ['Flagged Scripts', 'Moderation']); } } - }; + } function render() { aRes.render('pages/scriptListPage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); @@ -150,8 +150,9 @@ exports.register = function (aReq, aRes) { var authedUser = aReq.session.user; // If already logged in, goto the front page. - if (authedUser) + if (authedUser) { return aRes.redirect('/'); + } // var options = {}; @@ -209,9 +210,10 @@ exports.register = function (aReq, aRes) { // Prefer GitHub var githubStrategy = _.findWhere(options.strategies, { strat: 'github' }); - if (githubStrategy) + if (githubStrategy) { githubStrategy.selected = true; - }; + } + } function render() { aRes.render('pages/loginPage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); diff --git a/controllers/issue.js b/controllers/issue.js index 68386ccb4..d17d67cdf 100644 --- a/controllers/issue.js +++ b/controllers/issue.js @@ -126,7 +126,7 @@ exports.list = function (aReq, aRes, aNext) { options.discussionListIsEmptyMessage = 'No closed discussions.'; } } - }; + } function render() { aRes.render('pages/scriptIssueListPage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); @@ -146,7 +146,7 @@ exports.view = function (aReq, aRes, aNext) { Script.findOne({ installName: scriptStorage.caseInsensitive( - installNameSlug + (type === 'libs' ? '.js' : '.user.js')) + installNameSlug + (type === 'libs' ? '.js' : '.user.js')) }, function (aErr, aScriptData) { if (aErr || !aScriptData) { return aNext(); } @@ -222,7 +222,7 @@ exports.view = function (aReq, aRes, aNext) { // Pagination options.paginationRendered = pagination.renderDefault(aReq); - }; + } function render() { aRes.render('pages/scriptIssuePage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); @@ -234,7 +234,7 @@ exports.view = function (aReq, aRes, aNext) { exports.open = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) return aRes.redirect('/login'); + if (!authedUser) { return aRes.redirect('/login'); } var topic = aReq.body['discussion-topic']; var content = aReq.body['comment-content']; @@ -244,12 +244,12 @@ exports.open = function (aReq, aRes, aNext) { Script.findOne({ installName: scriptStorage.caseInsensitive( - installNameSlug + (type === 'libs' ? '.js' : '.user.js')) + installNameSlug + (type === 'libs' ? '.js' : '.user.js')) }, function (aErr, aScriptData) { function preRender() { // Page metadata pageMetadata(options, ['New Issue', script.name]); - }; + } function render() { aRes.render('pages/scriptNewIssuePage', options); } function asyncComplete() { preRender(); render(); } @@ -283,11 +283,12 @@ exports.open = function (aReq, aRes, aNext) { // Issue Submission discussionLib.postTopic(authedUser, category.slug, topic, content, true, function (aDiscussion) { - if (!aDiscussion) - return aRes.redirect('/' + encodeURI(category) + '/open'); - - aRes.redirect(encodeURI(aDiscussion.path + (aDiscussion.duplicateId ? '_' + aDiscussion.duplicateId : ''))); + if (!aDiscussion) { + return aRes.redirect('/' + encodeURI(category) + '/open'); } + + aRes.redirect(encodeURI(aDiscussion.path + (aDiscussion.duplicateId ? '_' + aDiscussion.duplicateId : ''))); + } ); } else { // New Issue Page @@ -311,9 +312,10 @@ exports.comment = function (aReq, aRes, aNext) { if (!user) { return aRes.redirect('/login'); } - Script.findOne({ installName: scriptStorage.caseInsensitive(installName - + (type === 'libs' ? '.js' : '.user.js')) }, function (aErr, aScript) { - var content = aReq.body['comment-content']; + Script.findOne({ + installName: scriptStorage.caseInsensitive(installName + (type === 'libs' ? '.js' : '.user.js')) + }, function (aErr, aScript) { + var content = aReq.body['comment-content']; if (aErr || !aScript) { return aNext(); } @@ -322,9 +324,9 @@ exports.comment = function (aReq, aRes, aNext) { discussionLib.postComment(user, aIssue, content, false, function (aErr, aDiscussion) { - aRes.redirect(encodeURI(aDiscussion.path - + (aDiscussion.duplicateId ? '_' + aDiscussion.duplicateId : ''))); - }); + aRes.redirect(encodeURI(aDiscussion.path + + (aDiscussion.duplicateId ? '_' + aDiscussion.duplicateId : ''))); + }); }); }); }; @@ -341,8 +343,9 @@ exports.changeStatus = function (aReq, aRes, aNext) { if (!user) { return aRes.redirect('/login'); } - Script.findOne({ installName: scriptStorage.caseInsensitive(installName - + (type === 'libs' ? '.js' : '.user.js')) }, function (aErr, aScript) { + Script.findOne({ + installName: scriptStorage.caseInsensitive(installName + (type === 'libs' ? '.js' : '.user.js')) + }, function (aErr, aScript) { if (aErr || !aScript) { return aNext(); } @@ -351,20 +354,19 @@ exports.changeStatus = function (aReq, aRes, aNext) { // Both the script author and the issue creator can close the issue // Only the script author can reopen a closed issue - if (action === 'close' && aIssue.open - && (user.name === aIssue.author || user.name === aScript.author)) { + if (action === 'close' && aIssue.open && + (user.name === aIssue.author || user.name === aScript.author)) { aIssue.open = false; changed = true; - } else if (action === 'reopen' && !aIssue.open - && user.name === aScript.author) { + } else if (action === 'reopen' && !aIssue.open && user.name === aScript.author) { aIssue.open = true; changed = true; } if (changed) { aIssue.save(function (aErr, aDiscussion) { - aRes.redirect(encodeURI(aDiscussion.path - + (aDiscussion.duplicateId ? '_' + aDiscussion.duplicateId : ''))); + aRes.redirect(encodeURI(aDiscussion.path + + (aDiscussion.duplicateId ? '_' + aDiscussion.duplicateId : ''))); }); } else { aNext(); diff --git a/controllers/moderation.js b/controllers/moderation.js index 7a8985770..3fd50b7bd 100644 --- a/controllers/moderation.js +++ b/controllers/moderation.js @@ -88,7 +88,7 @@ exports.removedItemListPage = function (aReq, aRes, aNext) { //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } //--- PreRender // removedItemList diff --git a/controllers/remove.js b/controllers/remove.js index 366ca152a..0810ff092 100644 --- a/controllers/remove.js +++ b/controllers/remove.js @@ -25,15 +25,15 @@ exports.rm = function (aReq, aRes, aNext) { case 'users': User.findOne({ name: { $regex: new RegExp('^' + path + '$', "i") } }, function (aErr, aUser) { - removeLib.remove(User, aUser, thisUser, '', function (aRemoved) { - if (!aRemoved) { return aNext(); } + removeLib.remove(User, aUser, thisUser, '', function (aRemoved) { + if (!aRemoved) { return aNext(); } - // Destory all the sessions belonging to the removed user - destroySessions(aReq, aUser, function () { - aRes.redirect('/'); - }); + // Destory all the sessions belonging to the removed user + destroySessions(aReq, aUser, function () { + aRes.redirect('/'); }); }); + }); break; default: aNext(); diff --git a/controllers/script.js b/controllers/script.js index 05eeb91fb..a94955d76 100644 --- a/controllers/script.js +++ b/controllers/script.js @@ -13,7 +13,7 @@ var Script = require('../models/script').Script; var Vote = require('../models/vote').Vote; var scriptStorage = require('./scriptStorage'); -var addScriptToGroups = require('./group').addScriptToGroups +var addScriptToGroups = require('./group').addScriptToGroups; var flagLib = require('../libs/flag'); var removeLib = require('../libs/remove'); var modelQuery = require('../libs/modelQuery'); @@ -50,8 +50,10 @@ var getScriptPageTasks = function (aOptions) { //--- Tasks // Show the number of open issues - var scriptOpenIssueCountQuery = Discussion.find({ category: scriptStorage - .caseInsensitive(script.issuesCategorySlug), open: {$ne: false} }); + var scriptOpenIssueCountQuery = Discussion.find({ + category: scriptStorage + .caseInsensitive(script.issuesCategorySlug), open: { $ne: false } + }); tasks.push(countTask(scriptOpenIssueCountQuery, aOptions, 'issueCount')); // Show the groups the script belongs to @@ -62,7 +64,7 @@ var getScriptPageTasks = function (aOptions) { Group.find({ _scriptIds: script._id }, function (aErr, aScriptGroupList) { - if (aErr) return aCallback(aErr); + if (aErr) { return aCallback(aErr); } aScriptGroupList = _.map(aScriptGroupList, modelParser.parseGroup); @@ -79,10 +81,10 @@ var getScriptPageTasks = function (aOptions) { htmlStub = ''; if (htmlStub === sanitizeHtml(htmlStub, htmlWhitelistLink)) { aOptions.script.homepages = [{ - url: script.meta.homepageURL, - text: decodeURI(script.meta.homepageURL), - hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org\//i.test(script.meta.homepageURL) - }]; + url: script.meta.homepageURL, + text: decodeURI(script.meta.homepageURL), + hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org\//i.test(script.meta.homepageURL) + }]; } } else { aOptions.script.homepages = []; @@ -146,7 +148,7 @@ var getScriptPageTasks = function (aOptions) { Script.find({ installName: { $in: script.uses } // TODO: STYLEGUIDE.md conformance needed here }, function (aErr, aScriptLibraryList) { - if (aErr) return aCallback(aErr); + if (aErr) { return aCallback(aErr); } script.libs = aScriptLibraryList; script.libs = _.map(script.libs, modelParser.parseScript); @@ -160,7 +162,7 @@ var getScriptPageTasks = function (aOptions) { Script.find({ uses: script.installName }, function (aErr, aLibraryScriptList) { - if (aErr) return aCallback(aErr); + if (aErr) { return aCallback(aErr); } script.isUsed = aLibraryScriptList.length > 0; script.usedBy = aLibraryScriptList; @@ -218,17 +220,17 @@ var getScriptPageTasks = function (aOptions) { flagLib.flaggable(Script, script, authedUser, function (aCanFlag, aAuthor, aFlag) { - if (aFlag) { - flagUrl += '/unflag'; - aOptions.flagged = true; - aOptions.canFlag = true; - } else { - aOptions.canFlag = aCanFlag; - } - aOptions.flagUrl = flagUrl; + if (aFlag) { + flagUrl += '/unflag'; + aOptions.flagged = true; + aOptions.canFlag = true; + } else { + aOptions.canFlag = aCanFlag; + } + aOptions.flagUrl = flagUrl; - aCallback(); - }); + aCallback(); + }); }); // Set up the removal UI @@ -241,18 +243,18 @@ var getScriptPageTasks = function (aOptions) { removeLib.removeable(Script, script, authedUser, function (aCanRemove, author) { - aOptions.canRemove = aCanRemove; - aOptions.flags = script.flags || 0; - aOptions.removeUrl = '/remove' + (script.isLib ? '/libs/' : '/scripts/') + script.installNameSlug; + aOptions.canRemove = aCanRemove; + aOptions.flags = script.flags || 0; + aOptions.removeUrl = '/remove' + (script.isLib ? '/libs/' : '/scripts/') + script.installNameSlug; - if (!aCanRemove) { return aCallback(); } + if (!aCanRemove) { return aCallback(); } - flagLib.getThreshold(Script, script, author, + flagLib.getThreshold(Script, script, author, function (aThreshold) { - aOptions.threshold = aThreshold; - aCallback(); - }); + aOptions.threshold = aThreshold; + aCallback(); }); + }); }); return tasks; @@ -299,7 +301,7 @@ exports.view = function (aReq, aRes, aNext) { pageMetadata(options, ['About', script.name, (script.isLib ? 'Libraries' : 'Scripts')], script.meta.description, _.pluck(script.groups, 'name')); } - }; + } function render() { aRes.render('pages/scriptPage', options); } function asyncComplete() { preRender(); render(); } @@ -365,7 +367,7 @@ exports.edit = function (aReq, aRes, aNext) { }); options.groupNameListJSON = JSON.stringify(groupNameList); - }; + } function render() { aRes.render('pages/scriptEditMetadataPage', options); } function asyncComplete() { preRender(); render(); } @@ -431,8 +433,7 @@ exports.edit = function (aReq, aRes, aNext) { // Script voting exports.vote = function (aReq, aRes, aNext) { var isLib = aReq.route.params.isLib; - var installName = scriptStorage.getInstallName(aReq) - + (isLib ? '.js' : '.user.js'); + var installName = scriptStorage.getInstallName(aReq) + (isLib ? '.js' : '.user.js'); var vote = aReq.route.params.vote; var user = aReq.session.user; var url = aReq._parsedUrl.pathname.split('/'); @@ -456,59 +457,59 @@ exports.vote = function (aReq, aRes, aNext) { Script.findOne({ installName: scriptStorage.caseInsensitive(installName) }, function (aErr, aScript) { - if (aErr || !aScript) { return aRes.redirect(url); } + if (aErr || !aScript) { return aRes.redirect(url); } - Vote.findOne({ _scriptId: aScript._id, _userId: user._id }, + Vote.findOne({ _scriptId: aScript._id, _userId: user._id }, function (aErr, aVoteModel) { - var oldVote = null; - var votes = aScript.votes || 0; - var flags = 0; + var oldVote = null; + var votes = aScript.votes || 0; + var flags = 0; - function saveScript() { - if (!flags) { - return aScript.save(function (aErr, aScript) { aRes.redirect(url); }); - } + function saveScript() { + if (!flags) { + return aScript.save(function (aErr, aScript) { aRes.redirect(url); }); + } - flagLib.getAuthor(aScript, function (aAuthor) { - flagLib.saveContent(Script, aScript, aAuthor, flags, + flagLib.getAuthor(aScript, function (aAuthor) { + flagLib.saveContent(Script, aScript, aAuthor, flags, function (aFlagged) { - aRes.redirect(url); - }); - }); - } - - if (!aScript.rating) { aScript.rating = 0; } - if (!aScript.votes) { aScript.votes = 0; } - - if (user._id == aScript._authorId || (!aVoteModel && unvote)) { - return aRes.redirect(url); - } else if (!aVoteModel) { - aVoteModel = new Vote({ - vote: vote, - _scriptId: aScript._id, - _userId: user._id - }); - aScript.rating += vote ? 1 : -1; - aScript.votes = votes + 1; - if (vote) { flags = -1; } - } else if (unvote) { - oldVote = aVoteModel.vote; - return aVoteModel.remove(function () { - aScript.rating += oldVote ? -1 : 1; - aScript.votes = votes <= 0 ? 0 : votes - 1; - if (oldVote) { flags = 1; } - saveScript(); - }); - } else if (aVoteModel.vote !== vote) { - aVoteModel.vote = vote; - aScript.rating += vote ? 2 : -2; - flags = vote ? -1 : 1; - } - - aVoteModel.save(saveScript); - } - ); + aRes.redirect(url); + }); + }); + } + + if (!aScript.rating) { aScript.rating = 0; } + if (!aScript.votes) { aScript.votes = 0; } + + if (user._id == aScript._authorId || (!aVoteModel && unvote)) { + return aRes.redirect(url); + } else if (!aVoteModel) { + aVoteModel = new Vote({ + vote: vote, + _scriptId: aScript._id, + _userId: user._id + }); + aScript.rating += vote ? 1 : -1; + aScript.votes = votes + 1; + if (vote) { flags = -1; } + } else if (unvote) { + oldVote = aVoteModel.vote; + return aVoteModel.remove(function () { + aScript.rating += oldVote ? -1 : 1; + aScript.votes = votes <= 0 ? 0 : votes - 1; + if (oldVote) { flags = 1; } + saveScript(); + }); + } else if (aVoteModel.vote !== vote) { + aVoteModel.vote = vote; + aScript.rating += vote ? 2 : -2; + flags = vote ? -1 : 1; + } + + aVoteModel.save(saveScript); } + ); + } ); }; @@ -518,15 +519,18 @@ exports.flag = function (aReq, aRes, aNext) { var installName = scriptStorage.getInstallName(aReq); var unflag = aReq.route.params.unflag; - Script.findOne({ installName: scriptStorage - .caseInsensitive(installName + (isLib ? '.js' : '.user.js')) }, + Script.findOne({ + installName: scriptStorage + .caseInsensitive(installName + (isLib ? '.js' : '.user.js')) + }, function (aErr, aScript) { - var fn = flagLib[unflag && unflag === 'unflag' ? 'unflag' : 'flag']; - if (aErr || !aScript) { return aNext(); } + var fn = flagLib[unflag && unflag === 'unflag' ? 'unflag' : 'flag']; + if (aErr || !aScript) { return aNext(); } - fn(Script, aScript, aReq.session.user, function (aFlagged) { // TODO: Non-descript function name - aRes.redirect((isLib ? '/libs/' : '/scripts/') + encodeURI(installName)); - }); - } + fn(Script, aScript, aReq.session.user, function (aFlagged) { + // TODO: Non-descript function name + aRes.redirect((isLib ? '/libs/' : '/scripts/') + encodeURI(installName)); + }); + } ); }; diff --git a/controllers/scriptStorage.js b/controllers/scriptStorage.js index 60a02d40c..53064d5bc 100644 --- a/controllers/scriptStorage.js +++ b/controllers/scriptStorage.js @@ -27,14 +27,13 @@ if (process.env.NODE_ENV === 'production') { }); } -function getInstallName (aReq) { +function getInstallName(aReq) { return aReq.route.params.username + '/' + aReq.route.params.scriptname; } exports.getInstallName = getInstallName; -function caseInsensitive (aInstallName) { - return new RegExp('^' + aInstallName.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") - + '$', 'i'); +function caseInsensitive(aInstallName) { + return new RegExp('^' + aInstallName.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") + '$', 'i'); } exports.caseInsensitive = caseInsensitive; @@ -45,10 +44,10 @@ exports.getSource = function (aReq, aCallback) { Script.findOne({ installName: caseInsensitive(installName) }, function (aErr, aScript) { - if (!aScript) { return aCallback(null); } + if (!aScript) { return aCallback(null); } - // Get the script - aCallback(aScript, s3.getObject({ Bucket: bucketName, Key: installName }) + // Get the script + aCallback(aScript, s3.getObject({ Bucket: bucketName, Key: installName }) .createReadStream()); }); }; @@ -86,42 +85,41 @@ exports.sendMeta = function (aReq, aRes, aNext) { Script.findOne({ installName: caseInsensitive(installName) }, function (aErr, aScript) { - var meta = null; - var data = null; - var prefix = null; - var key = null; - var whitespace = '\u0020\u0020\u0020\u0020'; - - if (!aScript) { return aNext(); } - - aRes.set('Content-Type', 'text/javascript; charset=UTF-8'); - meta = aScript.meta; // NOTE: Watchpoint - - aRes.write('// ==UserScript==\n'); - Object.keys(meta).reverse().forEach(function (aName) { - if (meta[aName] instanceof Array) { - meta[aName].forEach(function (aValue) { - aRes.write('// @' + aName + (aValue ? whitespace + aValue : '') + '\n'); - }); - } else if (meta[aName] instanceof Object) { - prefix = aName; - for (key in meta[aName]) { - data = meta[prefix][key]; - if (data instanceof Array) { - data.forEach(function (aValue) { - aRes.write('// @' + prefix + ':' + key + (aValue ? whitespace + aValue : '') + '\n'); - }); - } - else { - aRes.write('// @' + prefix + ':' + key + (data ? whitespace + data : '') + '\n'); - } + var meta = null; + var data = null; + var prefix = null; + var key = null; + var whitespace = '\u0020\u0020\u0020\u0020'; + + if (!aScript) { return aNext(); } + + aRes.set('Content-Type', 'text/javascript; charset=UTF-8'); + meta = aScript.meta; // NOTE: Watchpoint + + aRes.write('// ==UserScript==\n'); + Object.keys(meta).reverse().forEach(function (aName) { + if (meta[aName] instanceof Array) { + meta[aName].forEach(function (aValue) { + aRes.write('// @' + aName + (aValue ? whitespace + aValue : '') + '\n'); + }); + } else if (meta[aName] instanceof Object) { + prefix = aName; + for (key in meta[aName]) { + data = meta[prefix][key]; + if (data instanceof Array) { + data.forEach(function (aValue) { + aRes.write('// @' + prefix + ':' + key + (aValue ? whitespace + aValue : '') + '\n'); + }); + } else { + aRes.write('// @' + prefix + ':' + key + (data ? whitespace + data : '') + '\n'); } - } else { - data = meta[aName]; - aRes.write('// @' + aName + (data ? whitespace + data : '') + '\n'); } - }); - aRes.end('// ==/UserScript==\n'); + } else { + data = meta[aName]; + aRes.write('// @' + aName + (data ? whitespace + data : '') + '\n'); + } + }); + aRes.end('// ==/UserScript==\n'); }); }; @@ -206,8 +204,8 @@ function parseMeta(aString, aNormalize) { } if (!header[key] || aNormalize && unique[key]) { header[key] = value || ''; - } else if (!aNormalize || header[key] !== (value || '') - && !(header[key] instanceof Array && header[key].indexOf(value) > -1)) { + } else if (!aNormalize || header[key] !== (value || '') && + !(header[key] instanceof Array && header[key].indexOf(value) > -1)) { if (!(header[key] instanceof Array)) { header[key] = [header[key]]; } @@ -261,13 +259,11 @@ exports.storeScript = function (aUser, aMeta, aBuf, aCallback, aUpdate) { // Can't install a script without a @name (maybe replace with random value) if (!scriptName) { return aCallback(null); } - if (!isLibrary && aMeta.oujs && aMeta.oujs.author - && aMeta.oujs.author != aUser.name && aMeta.oujs.collaborator) { + if (!isLibrary && aMeta.oujs && aMeta.oujs.author && + aMeta.oujs.author != aUser.name && aMeta.oujs.collaborator) { collaborators = aMeta.oujs.collaborator; - if ((typeof collaborators === 'string' - && collaborators === aUser.name) - || (collaborators instanceof Array - && collaborators.indexOf(aUser.name) > -1)) { + if ((typeof collaborators === 'string' && collaborators === aUser.name) || + (collaborators instanceof Array && collaborators.indexOf(aUser.name) > -1)) { installName = aMeta.oujs.author + '/'; } else { collaborators = null; @@ -298,80 +294,80 @@ exports.storeScript = function (aUser, aMeta, aBuf, aCallback, aUpdate) { // Prevent a removed script from being reuploaded findDeadorAlive(Script, { installName: caseInsensitive(installName) }, true, function (aAlive, aScript, aRemoved) { - if (aRemoved || (!aScript && (aUpdate || collaborators))) { - return aCallback(null); - } else if (!aScript) { - // New script - aScript = new Script({ - name: isLibrary ? aMeta : aMeta.name, - author: aUser.name, - installs: 0, - rating: 0, - about: '', - updated: new Date(), - votes: 0, - flags: 0, - installName: installName, - fork: null, - meta: isLibrary ? { name: aMeta } : aMeta, - isLib: isLibrary, - uses: isLibrary ? null : libraries, - _authorId: aUser._id - }); - } else { - // Script already exists. - if (!aScript.isLib) { - if (collaborators && (aScript.meta.oujs && aScript.meta.oujs.author != aMeta.oujs.author - || (aScript.meta.oujs && JSON.stringify(aScript.meta.oujs.collaborator) != + if (aRemoved || (!aScript && (aUpdate || collaborators))) { + return aCallback(null); + } else if (!aScript) { + // New script + aScript = new Script({ + name: isLibrary ? aMeta : aMeta.name, + author: aUser.name, + installs: 0, + rating: 0, + about: '', + updated: new Date(), + votes: 0, + flags: 0, + installName: installName, + fork: null, + meta: isLibrary ? { name: aMeta } : aMeta, + isLib: isLibrary, + uses: isLibrary ? null : libraries, + _authorId: aUser._id + }); + } else { + // Script already exists. + if (!aScript.isLib) { + if (collaborators && (aScript.meta.oujs && aScript.meta.oujs.author != aMeta.oujs.author || + (aScript.meta.oujs && JSON.stringify(aScript.meta.oujs.collaborator) != JSON.stringify(aMeta.oujs.collaborator)))) { - return aCallback(null); - } - aScript.meta = aMeta; - aScript.uses = libraries; + return aCallback(null); } - aScript.updated = new Date(); - aScript.installsSinceUpdate = 0; + aScript.meta = aMeta; + aScript.uses = libraries; } + aScript.updated = new Date(); + aScript.installsSinceUpdate = 0; + } - aScript.save(function (aErr, aScript) { - s3.putObject({ Bucket: bucketName, Key: installName, Body: aBuf }, + aScript.save(function (aErr, aScript) { + s3.putObject({ Bucket: bucketName, Key: installName, Body: aBuf }, function (aErr, aData) { - // Don't save a script if storing failed - if (aErr) { - console.error(aUser.name, '-', installName); - console.error(JSON.stringify(aErr)); - console.error(JSON.stringify(aScript.toObject())); - return aCallback(null); - } + // Don't save a script if storing failed + if (aErr) { + console.error(aUser.name, '-', installName); + console.error(JSON.stringify(aErr)); + console.error(JSON.stringify(aScript.toObject())); + return aCallback(null); + } - if (aUser.role === userRoles.length - 1) { - var userDoc = aUser; - if (!userDoc.save) { - // We're probably using req.session.user which may have gotten serialized. - userDoc = new User(userDoc); - } - --userDoc.role; - userDoc.save(function (aErr, aUser) { aCallback(aScript); }); - } else { - aCallback(aScript); - } - }); + if (aUser.role === userRoles.length - 1) { + var userDoc = aUser; + if (!userDoc.save) { + // We're probably using req.session.user which may have gotten serialized. + userDoc = new User(userDoc); + } + --userDoc.role; + userDoc.save(function (aErr, aUser) { aCallback(aScript); }); + } else { + aCallback(aScript); + } }); }); + }); }; exports.deleteScript = function (aInstallName, aCallback) { Script.findOne({ installName: caseInsensitive(aInstallName) }, function (aErr, aScript) { - var s3 = new AWS.S3(); - s3.deleteObject({ Bucket : bucketName, Key : aScript.installName}, + var s3 = new AWS.S3(); + s3.deleteObject({ Bucket : bucketName, Key : aScript.installName }, function (aErr) { - if (!aErr) { - aScript.remove(aCallback); - } else { - aCallback(null); - } - }); + if (!aErr) { + aScript.remove(aCallback); + } else { + aCallback(null); + } + }); }); }; diff --git a/controllers/strategies.json b/controllers/strategies.json index 4e3c21353..c05e8a44e 100644 --- a/controllers/strategies.json +++ b/controllers/strategies.json @@ -1,19 +1,19 @@ { - "github" : { "name" : "GitHub", "oauth" : true }, - "facebook" : { "name" : "Facebook", "oauth" : true }, - "google" : { "name" : "Google", "oauth" : false }, - "persona" : { "name" : "Mozilla Persona", "oauth" : false }, - "yahoo" : { "name" : "Yahoo!", "oauth" : false }, - "aol" : { "name" : "AOL", "oauth" : false }, - "twitter" : { "name" : "Twitter", "oauth" : true }, - "flickr" : { "name" : "Flickr", "oauth" : true }, - "linkedin" : { "name" : "LinkedIn", "oauth" : true }, - "reddit" : { "name" : "Reddit", "oauth" : true }, - "imgur" : { "name" : "Imgur", "oauth" : true }, - "amazon" : { "name" : "Amazon", "oauth" : true }, - "windowslive" : { "name" : "Windows Live", "oauth" : true }, - "tumblr" : { "name" : "Tumblr", "oauth" : true }, - "foursquare" : { "name" : "Foursquare", "oauth" : true }, - "instagram" : { "name" : "Instagram", "oauth" : true }, - "steam" : { "name" : "Steam", "oauth" : false } + "github": { "name": "GitHub", "oauth": true }, + "facebook": { "name": "Facebook", "oauth": true }, + "google": { "name": "Google", "oauth": false }, + "persona": { "name": "Mozilla Persona", "oauth": false }, + "yahoo": { "name": "Yahoo!", "oauth": false }, + "aol": { "name": "AOL", "oauth": false }, + "twitter": { "name": "Twitter", "oauth": true }, + "flickr": { "name": "Flickr", "oauth": true }, + "linkedin": { "name": "LinkedIn", "oauth": true }, + "reddit": { "name": "Reddit", "oauth": true }, + "imgur": { "name": "Imgur", "oauth": true }, + "amazon": { "name": "Amazon", "oauth": true }, + "windowslive": { "name": "Windows Live", "oauth": true }, + "tumblr": { "name": "Tumblr", "oauth": true }, + "foursquare": { "name": "Foursquare", "oauth": true }, + "instagram": { "name": "Instagram", "oauth": true }, + "steam": { "name": "Steam", "oauth": false } } diff --git a/controllers/user.js b/controllers/user.js index ab1d06b32..e31932fb1 100644 --- a/controllers/user.js +++ b/controllers/user.js @@ -33,9 +33,8 @@ var github = require('./../libs/githubClient'); var pageMetadata = require('../libs/templateHelpers').pageMetadata; var orderDir = require('../libs/templateHelpers').orderDir; -function caseInsensitive (aStr) { - return new RegExp('^' + (aStr || '').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") - + '$', 'i'); +function caseInsensitive(aStr) { + return new RegExp('^' + (aStr || '').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") + '$', 'i'); } var setupUserModerationUITask = function (aOptions) { @@ -210,9 +209,9 @@ exports.userListPage = function (aReq, aRes, aNext) { if (options.isFlagged) { pageMetadata(options, ['Flagged Users', 'Moderation']); } - }; + } function render() { aRes.render('pages/userListPage', options); } - function asyncComplete(err) { if (err) { return aNext(); } else { preRender(); render(); } }; + function asyncComplete(err) { if (err) { return aNext(); } else { preRender(); render(); } } async.parallel(tasks, asyncComplete); }; @@ -269,7 +268,7 @@ exports.view = function (aReq, aRes, aNext) { tasks = tasks.concat(getUserSidePanelTasks(options)); //--- - function preRender() { }; + function preRender() { } function render() { aRes.render('pages/userPage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); @@ -353,7 +352,7 @@ exports.userCommentListPage = function (aReq, aRes, aNext) { // Pagination options.paginationRendered = pagination.renderDefault(aReq); - }; + } function render() { aRes.render('pages/userCommentListPage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); @@ -445,7 +444,7 @@ exports.userScriptListPage = function (aReq, aRes, aNext) { } else if (options.isUserScriptListPage) { options.scriptListIsEmptyMessage = 'This user hasn\'t added any scripts yet.'; } - }; + } function render() { aRes.render('pages/userScriptListPage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); @@ -507,7 +506,7 @@ exports.userEditProfilePage = function (aReq, aRes, aNext) { tasks = tasks.concat(getUserSidePanelTasks(options)); //--- - function preRender() { }; + function preRender() { } function render() { aRes.render('pages/userEditProfilePage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); @@ -621,7 +620,7 @@ exports.userEditPreferencesPage = function (aReq, aRes, aNext) { // UserSidePanel tasks tasks = tasks.concat(getUserSidePanelTasks(options)); - function preRender() { }; + function preRender() { } function render() { aRes.render('pages/userEditPreferencesPage', options); } function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); @@ -699,17 +698,17 @@ exports.edit = function (aReq, aRes, aNext) { scriptsList.listScripts({ _authorId: user._id, isLib: null, flagged: null }, // TODO: Global detected... may need renaming { size: -1 }, '/user/edit', function (aScriptsList) { - aScriptsList.edit = true; - options.scriptsList = aScriptsList; - aRes.render('userEdit', options); - }); + aScriptsList.edit = true; + options.scriptsList = aScriptsList; + aRes.render('userEdit', options); + }); }); }; exports.newScriptPage = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) return aRes.redirect('/login'); + if (!authedUser) { return aRes.redirect('/login'); } // var options = {}; @@ -731,7 +730,7 @@ exports.newScriptPage = function (aReq, aRes, aNext) { //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } aRes.render('pages/newScriptPage', options); }); @@ -740,7 +739,7 @@ exports.newScriptPage = function (aReq, aRes, aNext) { exports.newLibraryPage = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) return aRes.redirect('/login'); + if (!authedUser) { return aRes.redirect('/login'); } // var options = {}; @@ -762,7 +761,7 @@ exports.newLibraryPage = function (aReq, aRes, aNext) { //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } aRes.render('pages/newScriptPage', options); }); @@ -771,7 +770,7 @@ exports.newLibraryPage = function (aReq, aRes, aNext) { exports.userGitHubRepoListPage = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) return aRes.redirect('/login'); + if (!authedUser) { return aRes.redirect('/login'); } // var options = {}; @@ -860,7 +859,7 @@ exports.userGitHubRepoListPage = function (aReq, aRes, aNext) { exports.userGitHubImportScriptPage = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) return aRes.redirect('/login'); + if (!authedUser) { return aRes.redirect('/login'); } // var options = {}; @@ -897,8 +896,9 @@ exports.userGitHubImportScriptPage = function (aReq, aRes, aNext) { javascriptBlob = parseJavascriptBlob(javascriptBlob); - if (!javascriptBlob.canUpload) + if (!javascriptBlob.canUpload) { return aCallback(javascriptBlob.errors); + } options.javascriptBlob = javascriptBlob; aCallback(null); @@ -914,8 +914,9 @@ exports.userGitHubImportScriptPage = function (aReq, aRes, aNext) { }, function (aBlobUtf8, aCallback) { // Double check file size. - if (aBlobUtf8.length > settings.maximum_upload_script_size) + if (aBlobUtf8.length > settings.maximum_upload_script_size) { return aCallback(util.format('File size is larger than maximum (%s bytes).', settings.maximum_upload_script_size)); + } var onScriptStored = function (aScript) { if (aScript) { @@ -962,7 +963,7 @@ exports.userGitHubImportScriptPage = function (aReq, aRes, aNext) { exports.userGitHubRepoPage = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) return aRes.redirect('/login'); + if (!authedUser) { return aRes.redirect('/login'); } // var options = {}; @@ -1009,7 +1010,7 @@ exports.userGitHubRepoPage = function (aReq, aRes, aNext) { options.repo = aRepo; options.repoAsEncoded = { default_branch: encodeURI(options.repo.default_branch) - } + }; github.gitdata.getJavascriptBlobs({ user: encodeURIComponent(aRepo.owner.login), @@ -1033,12 +1034,12 @@ exports.userGitHubRepoPage = function (aReq, aRes, aNext) { aCallback(null); }, - ], aCallback) + ], aCallback); }); //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } aRes.render('pages/userGitHubRepoPage', options); }); @@ -1077,8 +1078,9 @@ var parseJavascriptBlob = function (aJavascriptBlob) { }); } - if (aJavascriptBlob.errors.length) + if (aJavascriptBlob.errors.length) { aJavascriptBlob.canUpload = !aJavascriptBlob.errors.length; + } return aJavascriptBlob; }; @@ -1087,7 +1089,7 @@ var parseJavascriptBlob = function (aJavascriptBlob) { exports.userManageGitHubPage = function (aReq, aRes, aNext) { var authedUser = aReq.session.user; - if (!authedUser) return aRes.redirect('/login'); + if (!authedUser) { return aRes.redirect('/login'); } // var options = {}; @@ -1168,7 +1170,8 @@ exports.userManageGitHubPage = function (aReq, aRes, aNext) { loadable[aReponame][scriptname] = aRepo[scriptname]; } } - } else if (typeof aRepo === 'object') { // load individual scripts + } else if (typeof aRepo === 'object') { + // load individual scripts for (scriptname in aRepo) { if (aRepos[aReponame][scriptname]) { if (!loadable[aReponame]) { loadable[aReponame] = nil(); } @@ -1195,13 +1198,12 @@ exports.userManageGitHubPage = function (aReq, aRes, aNext) { ], aCallback); }); - //--- async.parallel(tasks, function (aErr) { if (aErr) { return statusCodePage(aReq, aRes, aNext, { statusMessage: aErr - }) + }); } console.log('render'); @@ -1243,20 +1245,20 @@ exports.uploadScript = function (aReq, aRes, aNext) { if (isLib) { scriptStorage.storeScript(aUser, scriptName, Buffer.concat(bufs), function (aScript) { - if (!aScript) { return aRes.redirect(failUrl); } + if (!aScript) { return aRes.redirect(failUrl); } - aRes.redirect('/libs/' + encodeURI(aScript.installName + aRes.redirect('/libs/' + encodeURI(aScript.installName .replace(jsRegex, ''))); - }); + }); } else { scriptStorage.getMeta(bufs, function (aMeta) { scriptStorage.storeScript(aUser, aMeta, Buffer.concat(bufs), function (aScript) { - if (!aScript) { return aRes.redirect(failUrl); } + if (!aScript) { return aRes.redirect(failUrl); } - aRes.redirect('/scripts/' + encodeURI(aScript.installName + aRes.redirect('/scripts/' + encodeURI(aScript.installName .replace(userjsRegex, ''))); - }); + }); }); } }); @@ -1279,11 +1281,11 @@ exports.update = function (aReq, aRes, aNext) { User.findOneAndUpdate({ _id: user._id }, { about: aReq.body.about }, function (aErr, aUser) { - if (aErr) { aRes.redirect('/'); } + if (aErr) { aRes.redirect('/'); } - aReq.session.user.about = aUser.about; // TODO: Ambiguous - aRes.redirect('/users/' + aUser.name); - }); + aReq.session.user.about = aUser.about; // TODO: Ambiguous + aRes.redirect('/users/' + aUser.name); + }); } else { // Remove scripts (currently no UI) installRegex = new RegExp('^\/install\/(' + username + '\/.+)$'); @@ -1312,9 +1314,9 @@ exports.submitSource = function (aReq, aRes, aNext) { User.findOne({ _id: user._id }, function (aErr, aUser) { scriptStorage.storeScript(aUser, aMeta, aSource, function (aScript) { - var redirectUrl = encodeURI(aScript ? (aScript.isLib ? '/libs/' - + aScript.installName.replace(jsRegex, '') : '/scripts/' - + aScript.installName.replace(userjsRegex, '')) : aReq.body.url); + var redirectUrl = encodeURI(aScript ? + (aScript.isLib ? '/libs/' + aScript.installName.replace(jsRegex, '') : + '/scripts/' + aScript.installName.replace(userjsRegex, '')) : aReq.body.url); if (!aScript || !aReq.body.original) { return aRes.redirect(redirectUrl); @@ -1322,20 +1324,20 @@ exports.submitSource = function (aReq, aRes, aNext) { Script.findOne({ installName: aReq.body.original }, function (aErr, aOrigScript) { - var fork = null; - if (aErr || !aOrigScript) { return aRes.redirect(redirectUrl); } + var fork = null; + if (aErr || !aOrigScript) { return aRes.redirect(redirectUrl); } - fork = aOrigScript.fork || []; - fork.unshift({ - author: aOrigScript.author, url: aOrigScript + fork = aOrigScript.fork || []; + fork.unshift({ + author: aOrigScript.author, url: aOrigScript .installName.replace(aOrigScript.isLib ? jsRegex : userjsRegex, '') - }); - aScript.fork = fork; + }); + aScript.fork = fork; - aScript.save(function (aErr, aScript) { - aRes.redirect(redirectUrl); - }); + aScript.save(function (aErr, aScript) { + aRes.redirect(redirectUrl); }); + }); }); }); } @@ -1395,8 +1397,8 @@ function getExistingScript(aReq, aOptions, aAuthedUser, aCallback) { aOptions.source = Buffer.concat(bufs).toString('utf8'); aOptions.original = aScript.installName; aOptions.url = aReq.url; - aOptions.owner = aAuthedUser && (aScript._authorId == aAuthedUser._id - || collaborators.indexOf(aAuthedUser.name) > -1); + aOptions.owner = aAuthedUser && (aScript._authorId == aAuthedUser._id || + collaborators.indexOf(aAuthedUser.name) > -1); aOptions.username = aAuthedUser ? aAuthedUser.name : null; aOptions.isLib = aScript.isLib; aOptions.scriptName = aScript.name; @@ -1466,13 +1468,15 @@ exports.editScript = function (aReq, aRes, aNext) { //--- Tasks // Show the number of open issues - var scriptOpenIssueCountQuery = Discussion.find({ category: scriptStorage - .caseInsensitive(script.issuesCategorySlug), open: {$ne: false} }); + var scriptOpenIssueCountQuery = Discussion.find({ + category: scriptStorage + .caseInsensitive(script.issuesCategorySlug), open: { $ne: false } + }); tasks.push(countTask(scriptOpenIssueCountQuery, options, 'issueCount')); //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } aRes.render('pages/scriptViewSourcePage', options); }); @@ -1480,7 +1484,7 @@ exports.editScript = function (aReq, aRes, aNext) { } else { //--- async.parallel(tasks, function (aErr) { - if (aErr) return aNext(); + if (aErr) { return aNext(); } aRes.render('pages/scriptViewSourcePage', options); }); @@ -1496,7 +1500,8 @@ exports.flag = function (aReq, aRes, aNext) { var fn = flagLib[unflag && unflag === 'unflag' ? 'unflag' : 'flag']; if (aErr || !aUser) { return aNext(); } - fn(User, aUser, aReq.session.user, function (aFlagged) { // TODO: Non-descript function name + fn(User, aUser, aReq.session.user, function (aFlagged) { + // TODO: Non-descript function name aRes.redirect('/users/' + username); }); }); diff --git a/libs/flag.js b/libs/flag.js index 78dd97fa4..797ea9b62 100644 --- a/libs/flag.js +++ b/libs/flag.js @@ -13,7 +13,6 @@ function flaggable(aModel, aContent, aUser, aCallback) { // Not logged in. if (!aUser) { return aCallback(false); } - // You can't flag yourself // Only someone less than an admin can be flagged // It is not the responsibility of the community @@ -98,17 +97,17 @@ function saveContent(aModel, aContent, aAuthor, aFlags, aCallback) { exports.saveContent = saveContent; function flag(aModel, aContent, aUser, aAuthor, aCallback) { - var flag = new Flag({ + var flagModel = new Flag({ 'model': aModel.modelName, '_contentId': aContent._id, '_userId': aUser._id }); - flag.save(function (aErr, aFlag) { + flagModel.save(function (aErr, aFlag) { if (!aContent.flags) { aContent.flags = 0; } if (!aContent.flagged) { aContent.flagged = false; } - saveContent(aModel, aContent, aAuthor, aUser.role < 4 ? 2 : 1, aCallback) + saveContent(aModel, aContent, aAuthor, aUser.role < 4 ? 2 : 1, aCallback); }); } diff --git a/libs/githubClient.js b/libs/githubClient.js index 87e75a7a4..26f4719f7 100644 --- a/libs/githubClient.js +++ b/libs/githubClient.js @@ -15,8 +15,9 @@ module.exports = github; // Authenticate Client var Strategy = require('../models/strategy').Strategy; Strategy.findOne({ name: 'github' }, function (aErr, aStrat) { - if (aErr) + if (aErr) { console.error(aErr); + } if (aStrat) { github.authenticate({ @@ -63,8 +64,9 @@ var githubUserContentGetBlobAsUtf8 = function (aMsg, aCallback) { request.get(url, aCallback); }, function (aResponse, aBody, aCallback) { - if (aResponse.statusCode != 200) + if (aResponse.statusCode != 200) { return aCallback(util.format('Status Code %s', aResponse.statusCode)); + } aCallback(null, aBody); }, diff --git a/libs/helpers.js b/libs/helpers.js index 9b177bbde..9544dd398 100644 --- a/libs/helpers.js +++ b/libs/helpers.js @@ -34,9 +34,7 @@ exports.formatDate = function (aDate) { } if (difference > week) { - ret = aDate.getDate() + ' ' - + months[aDate.getMonth()] + ' ' - + aDate.getFullYear(); + ret = aDate.getDate() + ' ' + months[aDate.getMonth()] + ' ' + aDate.getFullYear(); } else if (difference > day) { days = Math.round(difference / day); if (days <= 1) { @@ -53,13 +51,13 @@ exports.formatDate = function (aDate) { } return ret; -} +}; // Create an object with no properties exports.nil = function (aObj) { var nilObj = Object.create(null); - if (!aObj) return nilObj; + if (!aObj) { return nilObj; } exports.forIn(aObj, function (aVal, aKey) { nilObj[aKey] = aVal; diff --git a/libs/markdown.js b/libs/markdown.js index 0ae78eaa9..dfef14147 100644 --- a/libs/markdown.js +++ b/libs/markdown.js @@ -79,7 +79,7 @@ renderer.heading = function (aText, aLevel) { var name = escapedText; var html = ''; - html += '' + html += ''; html += sanitize(aText); html += ''; html += ''; diff --git a/libs/modelParser.js b/libs/modelParser.js index 7d739f44a..094969252 100644 --- a/libs/modelParser.js +++ b/libs/modelParser.js @@ -24,7 +24,7 @@ var momentLangFromNow = function (aDate) { return '[' + aDate.fromNow() + ']'; }; var momentLangTinyDate = function (aDate) { - if(aDate.year() === moment().year()) { + if (aDate.year() === moment().year()) { return '[' + aDate.format("D MMM") + ']'; } else { return '[' + aDate.format("MMM 'YY") + ']'; @@ -102,7 +102,7 @@ var getScriptInstallPageUrl = function (aScript) { // var parseScript = function (aScriptData) { - if (!aScriptData) return; + if (!aScriptData) { return; } var script = aScriptData.toObject ? aScriptData.toObject() : aScriptData; // Temporaries @@ -134,19 +134,19 @@ var parseScript = function (aScriptData) { htmlStub = ''; if (htmlStub === sanitizeHtml(htmlStub, htmlWhitelistLink)) { script.support = [{ - url: script.meta.supportURL, - text: decodeURI(script.meta.supportURL), - hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org/i.test(script.meta.supportURL) - }]; + url: script.meta.supportURL, + text: decodeURI(script.meta.supportURL), + hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org/i.test(script.meta.supportURL) + }]; } } else if (_.isArray(script.meta.supportURL) && !_.isEmpty(script.meta.supportURL)) { htmlStub = ''; if (htmlStub === sanitizeHtml(htmlStub, htmlWhitelistLink)) { script.support = [{ - url: script.meta.supportURL[script.meta.supportURL.length - 1], - text: decodeURI(script.meta.supportURL[script.meta.supportURL.length - 1]), - hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org/i.test(script.meta.supportURL[script.meta.supportURL.length - 1]) - }]; + url: script.meta.supportURL[script.meta.supportURL.length - 1], + text: decodeURI(script.meta.supportURL[script.meta.supportURL.length - 1]), + hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org/i.test(script.meta.supportURL[script.meta.supportURL.length - 1]) + }]; } } } @@ -208,7 +208,7 @@ parseModelFnMap.Script = parseScript; exports.parseScript = parseScript; exports.renderScript = function (aScript) { - if (!aScript) return; + if (!aScript) { return; } aScript.aboutRendered = renderMd(aScript.about); }; @@ -218,7 +218,7 @@ exports.renderScript = function (aScript) { // var parseUser = function (aUserData) { - if (!aUserData) return; + if (!aUserData) { return; } // var user = aUserData.toObject ? aUserData.toObject() : aUserData; // Intermediates @@ -265,7 +265,7 @@ exports.parseUser = parseUser; // var parseGroup = function (aGroupData) { - if (!aGroupData) return; + if (!aGroupData) { return; } // var group = aGroupData.toObject ? aGroupData.toObject() : aGroupData; // Intermediates @@ -307,7 +307,7 @@ exports.parseGroup = parseGroup; // var parseDiscussion = function (aDiscussionData) { - if (!aDiscussionData) return; + if (!aDiscussionData) { return; } var discussion = aDiscussionData.toObject ? aDiscussionData.toObject() : aDiscussionData; // var discussion = aDiscussionData; // Can't override discussionData.category @@ -320,10 +320,12 @@ var parseDiscussion = function (aDiscussionData) { // RecentCommentors var recentCommentors = []; - if (discussion.author) + if (discussion.author) { recentCommentors.push(discussion.author); - if (discussion.lastCommentor != discussion.author) + } + if (discussion.lastCommentor != discussion.author) { recentCommentors.push(discussion.lastCommentor); + } recentCommentors = _.map(recentCommentors, function (aUsername) { return { name: aUsername @@ -342,7 +344,7 @@ parseModelFnMap.Discussion = parseDiscussion; exports.parseDiscussion = parseDiscussion; var parseIssue = function (aDiscussionData) { - if (!aDiscussionData) return; + if (!aDiscussionData) { return; } var discussion = aDiscussionData.toObject ? aDiscussionData.toObject() : aDiscussionData; discussion.issue = true; @@ -350,7 +352,6 @@ var parseIssue = function (aDiscussionData) { discussion.issueCloseUrl = discussion.path + '/close'; discussion.issueOpenUrl = discussion.path + '/reopen'; - return discussion; }; parseModelFnMap.Issue = parseIssue; @@ -362,7 +363,7 @@ exports.parseIssue = parseIssue; // var parseComment = function (aCommentData) { - if (!aCommentData) return; + if (!aCommentData) { return; } var comment = aCommentData.toObject ? aCommentData.toObject() : aCommentData; // Dates @@ -374,7 +375,7 @@ parseModelFnMap.Comment = parseComment; exports.parseComment = parseComment; exports.renderComment = function (aComment) { - if (!aComment) return; + if (!aComment) { return; } aComment.contentRendered = renderMd(aComment.content); }; @@ -384,11 +385,13 @@ exports.renderComment = function (aComment) { var canUserPostTopicToCategory = function (aUser, aCategory) { // Check if user is logged in. - if (_.isUndefined(aUser) || _.isNull(aUser)) + if (_.isUndefined(aUser) || _.isNull(aUser)) { return false; // Not logged in. + } // Check if this category requires a minimum role to post topics. - console.log(aCategory.roleReqToPostTopic, _.isNumber(aCategory.roleReqToPostTopic), aUser.role, aUser.role <= aCategory.roleReqToPostTopic) + console.log(aCategory.roleReqToPostTopic, _.isNumber(aCategory.roleReqToPostTopic), aUser.role, + aUser.role <= aCategory.roleReqToPostTopic); if (_.isNumber(aCategory.roleReqToPostTopic)) { return aUser.role <= aCategory.roleReqToPostTopic; } else { @@ -399,7 +402,7 @@ var canUserPostTopicToCategory = function (aUser, aCategory) { // var parseCategory = function (aCategoryData) { - if (!aCategoryData) return; + if (!aCategoryData) { return; } var category = aCategoryData.toObject ? aCategoryData.toObject() : aCategoryData; // Urls @@ -421,8 +424,9 @@ exports.parseCategory = parseCategory; */ var getRemovedItemDescription = function (aRemove) { - if (!aRemove.content) + if (!aRemove.content) { return 'No content'; + } switch (aRemove.model) { case 'User': @@ -440,7 +444,7 @@ var getRemovedItemDescription = function (aRemove) { // var parseRemovedItem = function (aRemovedItemData) { - if (!aRemovedItemData) return; + if (!aRemovedItemData) { return; } var removedItem = aRemovedItemData; // Dates @@ -451,8 +455,9 @@ var parseRemovedItem = function (aRemovedItemData) { // Content var parseModelFn = parseModelFnMap[removedItem.model]; - if (parseModelFn && removedItem.content) + if (parseModelFn && removedItem.content) { removedItem.content = parseModelFn(removedItem.content); + } // Item removedItem.itemDescription = getRemovedItemDescription(removedItem); diff --git a/libs/modelQuery.js b/libs/modelQuery.js index 88e9d2bb4..5a11a7f26 100644 --- a/libs/modelQuery.js +++ b/libs/modelQuery.js @@ -21,8 +21,9 @@ exports.findOrDefaultIfNull = findOrDefaultIfNull; var orderDirs = ['asc', 'desc']; var parseModelListSort = function (aModelListQuery, aOrderBy, aOrderDir, aDefaultSortFn) { if (aOrderBy) { - if (_.isUndefined(aOrderDir) || !_.contains(orderDirs, aOrderDir)) + if (_.isUndefined(aOrderDir) || !_.contains(orderDirs, aOrderDir)) { aOrderDir = 'asc'; + } if (_.has(aModelListQuery.model.schema.paths, aOrderBy)) { var sortBy = {}; @@ -35,7 +36,8 @@ var parseModelListSort = function (aModelListQuery, aOrderBy, aOrderDir, aDefaul }; exports.parseModelListSort = parseModelListSort; -var parseSearchConditions = function (aQ, aPrefixSearchFields, aFullSearchFields) { // NOTE: This code is duplicated elsewhere but this is primary +var parseSearchConditions = function (aQ, aPrefixSearchFields, aFullSearchFields) { + // NOTE: This code is duplicated elsewhere but this is primary var conditions = []; var query = null; var prefixStr = ''; @@ -136,7 +138,7 @@ var applyModelListQueryFlaggedFilter = function (aModelListQuery, aOptions, aFla if (aFlaggedQuery == 'true') { aOptions.isFlagged = true; aModelListQuery.and({ flags: { $gt: 0 } }); - } else if (aFlaggedQuery == false) { + } else if (aFlaggedQuery === false) { // aModelListQuery.and({$or: [ // {flags: {$exists: false}}, // {flags: {$lte: 0} }, @@ -157,16 +159,18 @@ var applyModelListQueryDefaults = function (aModelListQuery, aOptions, aReq, aDe if (aReq.query.q) { aOptions.searchBarValue = aReq.query.q; - if (aDefaultOptions.parseSearchQueryFn) + if (aDefaultOptions.parseSearchQueryFn) { aDefaultOptions.parseSearchQueryFn(aModelListQuery, aReq.query.q); + } } aOptions.searchBarFormAction = aDefaultOptions.searchBarFormAction || ''; aOptions.searchBarPlaceholder = aDefaultOptions.searchBarPlaceholder || 'Search'; aOptions.searchBarFormHiddenVariables = aDefaultOptions.searchBarFormHiddenVariables || []; // flagged - if (aDefaultOptions.filterFlaggedItems) + if (aDefaultOptions.filterFlaggedItems) { applyModelListQueryFlaggedFilter(aModelListQuery, aOptions, aReq.query.flagged); + } // Sort parseModelListSort(aModelListQuery, aReq.query.orderBy, aReq.query.orderDir, function () { diff --git a/libs/muExpress.js b/libs/muExpress.js index 49a2f0dfc..57caf8f27 100644 --- a/libs/muExpress.js +++ b/libs/muExpress.js @@ -17,7 +17,8 @@ function renderFile(aRes, aPath, aOptions) { exports.renderFile = function (aApp) { var render = aApp.response.__proto__.render; - aApp.response.__proto__.render = function (aView, aOptions, aFn) { // TODO: Non-descript function parm + // TODO: Non-descript function parm + aApp.response.__proto__.render = function (aView, aOptions, aFn) { var self = this; if (!aFn && aApp.get('view engine') === 'html') { diff --git a/libs/passportLoader.js b/libs/passportLoader.js index fd036fcc2..6e795bf72 100644 --- a/libs/passportLoader.js +++ b/libs/passportLoader.js @@ -5,10 +5,12 @@ var passport = require('passport'); var nil = require('../libs/helpers').nil; var AUTH_CALLBACK_BASE_URL = 'http://localhost:' + (process.env.PORT || 8080); -if (process.env.NODE_ENV === 'production') +if (process.env.NODE_ENV === 'production') { AUTH_CALLBACK_BASE_URL = 'https://openuserjs.org'; -if (process.env.AUTH_CALLBACK_BASE_URL) +} +if (process.env.AUTH_CALLBACK_BASE_URL) { AUTH_CALLBACK_BASE_URL = process.env.AUTH_CALLBACK_BASE_URL; +} exports.strategyInstances = nil(); @@ -28,7 +30,8 @@ exports.loadPassport = function (aStrategy) { profile: false, stateless: true }, - function () { } // we replace this callback later (_verify) + function () + { } // we replace this callback later (_verify) ); } else { instance = new PassportStrategy( @@ -40,7 +43,8 @@ exports.loadPassport = function (aStrategy) { state: 'a bullshit string reddit requires', callbackURL: AUTH_CALLBACK_BASE_URL + '/auth/' + aStrategy.name + '/callback/' }, - function () { } // we replace this callback later (_verify) + function () + { } // we replace this callback later (_verify) ); } diff --git a/libs/passportVerify.js b/libs/passportVerify.js index 875a472e6..b08858c6f 100644 --- a/libs/passportVerify.js +++ b/libs/passportVerify.js @@ -23,50 +23,49 @@ exports.verify = function (aId, aStrategy, aUsername, aLoggedIn, aDone) { findDeadorAlive(User, { 'auths': digest }, true, function (aAlive, aUser, aRemoved) { - var pos = aUser ? aUser.auths.indexOf(digest) : -1; - if (aRemoved) { aDone(null, false, 'user was removed'); } + var pos = aUser ? aUser.auths.indexOf(digest) : -1; + if (aRemoved) { aDone(null, false, 'user was removed'); } - if (!aUser) { - User.findOne({ 'name': aUsername }, function (aErr, aUser) { - if (aUser && aLoggedIn) { - // Add the new strategy to same account - // This allows linking multiple external accounts to one of ours - aUser.auths.push(digest); - aUser.strategies.push(aStrategy); - aUser.save(function (aErr, aUser) { - return aDone(aErr, aUser); - }); - } else if (aUser) { - // user was found matching name but not can't be authenticated - return aDone(null, false, 'username is taken'); - } else { - // Create a new user - aUser = new User({ - 'name': aUsername, - 'auths': [digest], - 'strategies': [aStrategy], - 'role': userRoles.length - 1, - 'about': '', - 'ghUsername': null - }); - aUser.save(function (aErr, aUser) { - return aDone(aErr, aUser); - }); - } - }); - } else if (pos > -1 && pos < aUser.auths.length - 1) { - // Set the default strategy - aUser.strategies.splice(pos, 1); - aUser.auths.splice(pos, 1); - aUser.strategies.push(aStrategy); - aUser.auths.push(digest); - aUser.save(function (aErr, aUser) { - return aDone(aErr, aUser); - }); - } else { - // The user was authenticated - return aDone(null, aUser); - } + if (!aUser) { + User.findOne({ 'name': aUsername }, function (aErr, aUser) { + if (aUser && aLoggedIn) { + // Add the new strategy to same account + // This allows linking multiple external accounts to one of ours + aUser.auths.push(digest); + aUser.strategies.push(aStrategy); + aUser.save(function (aErr, aUser) { + return aDone(aErr, aUser); + }); + } else if (aUser) { + // user was found matching name but not can't be authenticated + return aDone(null, false, 'username is taken'); + } else { + // Create a new user + aUser = new User({ + 'name': aUsername, + 'auths': [digest], + 'strategies': [aStrategy], + 'role': userRoles.length - 1, + 'about': '', + 'ghUsername': null + }); + aUser.save(function (aErr, aUser) { + return aDone(aErr, aUser); + }); + } + }); + } else if (pos > -1 && pos < aUser.auths.length - 1) { + // Set the default strategy + aUser.strategies.splice(pos, 1); + aUser.auths.splice(pos, 1); + aUser.strategies.push(aStrategy); + aUser.auths.push(digest); + aUser.save(function (aErr, aUser) { + return aDone(aErr, aUser); + }); + } else { + // The user was authenticated + return aDone(null, aUser); } - ); -} + }); +}; diff --git a/libs/remove.js b/libs/remove.js index 829611cc9..3887ff52c 100644 --- a/libs/remove.js +++ b/libs/remove.js @@ -44,7 +44,7 @@ function removeable(aModel, aContent, aUser, aCallback) { exports.removeable = removeable; function remove(aModel, aContent, aUser, aReason, aCallback) { - var remove = new Remove({ + var removeModel = new Remove({ 'model': aModel.modelName, 'content': aContent.toObject(), 'removed': new Date(), @@ -54,7 +54,7 @@ function remove(aModel, aContent, aUser, aReason, aCallback) { '_removerId': aUser._id }); - remove.save(function (aErr, aRemove) { + removeModel.save(function (aErr, aRemove) { aContent.remove(function (aErr) { aCallback(aRemove); }); }); } diff --git a/libs/repoManager.js b/libs/repoManager.js index 09d535e8b..4afe5f8ac 100644 --- a/libs/repoManager.js +++ b/libs/repoManager.js @@ -29,17 +29,18 @@ function fetchRaw(aHost, aPath, aCallback) { headers: { 'User-Agent': 'Node.js' } }; - var req = https.request(options, - function (aRes) { - var bufs = []; - if (aRes.statusCode != 200) { console.log(aRes.statusCode); return aCallback([new Buffer('')]); } - else { - aRes.on('data', function (aD) { bufs.push(aD); }); // TODO: Non-descript function parm - aRes.on('end', function () { - aCallback(bufs); - }); - } - }); + var req = https.request(options, function (aRes) { + var bufs = []; + if (aRes.statusCode != 200) { + console.log(aRes.statusCode); return aCallback([new Buffer('')]); + } else { + aRes.on('data', function (aD) + { bufs.push(aD); }); // TODO: Non-descript function parm + aRes.on('end', function () { + aCallback(bufs); + }); + } + }); req.end(); } @@ -101,8 +102,7 @@ RepoManager.prototype.loadScripts = function (aCallback, aUpdate) { // TODO: remove usage of makeRepoArray since it causes redundant looping arrayOfRepos.forEach(function (aRepo) { async.each(aRepo.scripts, function (aScript, aCallback) { - var url = '/' + encodeURI(aRepo.user) + '/' + encodeURI(aRepo.repo) - + '/master' + aScript.path; + var url = '/' + encodeURI(aRepo.user) + '/' + encodeURI(aRepo.repo) + '/master' + aScript.path; fetchRaw('raw.githubusercontent.com', url, function (aBufs) { scriptStorage.getMeta(aBufs, function (aMeta) { if (aMeta) { @@ -113,7 +113,7 @@ RepoManager.prototype.loadScripts = function (aCallback, aUpdate) { }); }, aCallback); }); -} +}; // Create the Mustache object to display repos with their user scrips RepoManager.prototype.makeRepoArray = function () { @@ -138,7 +138,7 @@ RepoManager.prototype.makeRepoArray = function () { } return retOptions; -} +}; // Manages a single repo function Repo(aManager, aUsername, aReponame) { @@ -163,8 +163,7 @@ Repo.prototype.parseTree = function (aTree, aPath, aDone) { aTree.forEach(function (object) { if (object.type === 'tree') { trees.push({ - sha: object.sha, path: aPath + '/' - + encodeURI(object.path) + sha: object.sha, path: aPath + '/' + encodeURI(object.path) }); } else if (object.path.substr(-8) === '.user.js') { if (!repos[that.repo]) { repos[that.repo] = nil(); } @@ -182,11 +181,10 @@ Repo.prototype.parseTree = function (aTree, aPath, aDone) { // Gets information about a directory Repo.prototype.getTree = function (aSha, aPath, aCallback) { var that = this; - fetchJSON('/repos/' + encodeURI(this.user) + '/' + encodeURI(this.repo) - + '/git/trees/' + aSha, + fetchJSON('/repos/' + encodeURI(this.user) + '/' + encodeURI(this.repo) + '/git/trees/' + aSha, function (aJson) { - that.parseTree(aJson.tree, aPath, aCallback); - } + that.parseTree(aJson.tree, aPath, aCallback); + } ); }; diff --git a/libs/tasks.js b/libs/tasks.js index ac0281210..5574b9d6c 100644 --- a/libs/tasks.js +++ b/libs/tasks.js @@ -3,10 +3,11 @@ var defaultOnErrFn = console.log; var onErr = function (aErr, aOnErrFn) { - if (aOnErrFn) + if (aOnErrFn) { aOnErrFn(aErr); - else + } else { defaultOnErrFn(aErr); + } }; exports.countTask = function (aModelListQuery, aDict, aKey, aOnErrFn) { @@ -30,7 +31,7 @@ exports.execQueryTask = function (aQuery, aDict, aKey, aOnErrFn) { onErr(aErr, aOnErrFn); aCallback(); } else { - aDict[aKey] = result + aDict[aKey] = result; aCallback(); } }); diff --git a/libs/templateHelpers.js b/libs/templateHelpers.js index 169a66965..a3e30da50 100644 --- a/libs/templateHelpers.js +++ b/libs/templateHelpers.js @@ -18,22 +18,26 @@ var paginateTemplate = function (aOpts) { var linkedPages = []; - for (var i = Math.max(1, currentPage - distVisible); i <= Math.min(currentPage + distVisible, lastPage); i++) + for (var i = Math.max(1, currentPage - distVisible); i <= Math.min(currentPage + distVisible, lastPage); i++) { linkedPages.push(i); + } - if (firstVisible && linkedPages.length > 0 && linkedPages[0] != 1) + if (firstVisible && linkedPages.length > 0 && linkedPages[0] != 1) { linkedPages.splice(0, 0, 1); // insert the value 1 at index 0 + } - if (lastVisible && linkedPages.length > 0 && linkedPages[linkedPages.length - 1] != lastPage) + if (lastVisible && linkedPages.length > 0 && linkedPages[linkedPages.length - 1] != lastPage) { linkedPages.push(lastPage); + } var html = ''; html += '