From 82ef53392e8fabd9ccb86a283a2d3e7b6418c43d Mon Sep 17 00:00:00 2001 From: Brian Oley Date: Fri, 16 Aug 2013 15:23:09 -0400 Subject: [PATCH] Added semicolons to server code for consistency and general formatting --- app/controllers/articles.js | 69 ++++++------- app/controllers/index.js | 11 +-- app/controllers/users.js | 76 +++++++-------- app/models/article.js | 12 +-- app/models/user.js | 77 +++++++-------- config/config.js | 8 +- config/express.js | 63 ++++++------ config/middlewares/authorization.js | 21 ++-- config/passport.js | 146 ++++++++++++++-------------- config/routes.js | 62 ++++++------ 10 files changed, 263 insertions(+), 282 deletions(-) diff --git a/app/controllers/articles.js b/app/controllers/articles.js index 8966682c0b..c45b81e37d 100644 --- a/app/controllers/articles.js +++ b/app/controllers/articles.js @@ -1,70 +1,71 @@ /** * Module dependencies. */ - -var mongoose = require('mongoose') - , async = require('async') - , Article = mongoose.model('Article') - , _ = require('underscore') +var mongoose = require('mongoose'), + async = require('async'), + Article = mongoose.model('Article'), + _ = require('underscore'); /** * Find article by id */ - exports.article = function(req, res, next, id){ - var User = mongoose.model('User') + var User = mongoose.model('User'); Article.load(id, function (err, article) { - if (err) return next(err) - if (!article) return next(new Error('Failed to load article ' + id)) - req.article = article - next() - }) -} + if (err) return next(err); + if (!article) return next(new Error('Failed to load article ' + id)); + req.article = article; + next(); + }); +}; /** * Create a article */ exports.create = function (req, res) { - var article = new Article(req.body) - article.user = req.user - article.save() - res.jsonp(article) -} + var article = new Article(req.body); + + article.user = req.user; + article.save(); + res.jsonp(article); +}; /** * Update a article */ exports.update = function(req, res){ - var article = req.article - article = _.extend(article, req.body) + var article = req.article; + + article = _.extend(article, req.body); article.save(function(err) { - res.jsonp(article) - }) -} + res.jsonp(article); + }); +}; /** * Delete an article */ exports.destroy = function(req, res){ - var article = req.article + var article = req.article; + article.remove(function(err){ if (err) { - res.render('error', {status: 500}); - } else { - res.jsonp(article); - } - }) -} + res.render('error', {status: 500}); + } else { + res.jsonp(article); + } + }); +}; /** * Show an article */ exports.show = function(req, res){ res.jsonp(req.article); -} +}; /** * List of Articles @@ -73,8 +74,8 @@ exports.all = function(req, res){ Article.find().sort('-created').populate('user').exec(function(err, articles) { if (err) { res.render('error', {status: 500}); - } else { - res.jsonp(articles); + } else { + res.jsonp(articles); } }); -} \ No newline at end of file +}; \ No newline at end of file diff --git a/app/controllers/index.js b/app/controllers/index.js index b350ac37e6..1848c00460 100644 --- a/app/controllers/index.js +++ b/app/controllers/index.js @@ -1,14 +1,13 @@ /** * Module dependencies. */ - -var mongoose = require('mongoose') - , async = require('async') - , _ = require('underscore') +var mongoose = require('mongoose'), + async = require('async'), + _ = require('underscore'); exports.render = function(req, res){ res.render('index', { user: req.user ? JSON.stringify(req.user) : "null" - }) -} + }); +}; diff --git a/app/controllers/users.js b/app/controllers/users.js index 11c21b0aa6..8e449d2b0e 100755 --- a/app/controllers/users.js +++ b/app/controllers/users.js @@ -2,104 +2,100 @@ /** * Module dependencies. */ - -var mongoose = require('mongoose') - , User = mongoose.model('User') +var mongoose = require('mongoose'), + User = mongoose.model('User'); //exports.signin = function (req, res) {} /** * Auth callback */ - exports.authCallback = function (req, res, next) { - res.redirect('/') -} + res.redirect('/'); +}; /** * Show login form */ - exports.signin = function (req, res) { res.render('users/signin', { title: 'Signin', message: req.flash('error') - }) -} + }); +}; /** * Show sign up form */ - exports.signup = function (req, res) { res.render('users/signup', { title: 'Sign up', user: new User() - }) -} + }); +}; /** * Logout */ - exports.signout = function (req, res) { - req.logout() - res.redirect('/') -} + req.logout(); + res.redirect('/'); +}; /** * Session */ - exports.session = function (req, res) { - res.redirect('/') -} + res.redirect('/'); +}; /** * Create user */ - exports.create = function (req, res) { - var user = new User(req.body) - user.provider = 'local' + var user = new User(req.body); + + user.provider = 'local'; user.save(function (err) { if (err) { - return res.render('users/signup', { errors: err.errors, user: user }) + return res.render('users/signup', { errors: err.errors, user: user }); } req.logIn(user, function(err) { - if (err) return next(err) - return res.redirect('/') - }) - }) -} + if (err) return next(err); + return res.redirect('/'); + }); + }); +}; /** * Show profile */ - exports.show = function (req, res) { - var user = req.profile + var user = req.profile; + res.render('users/show', { title: user.name, user: user - }) -} + }); +}; +/** + * Send User + */ exports.me = function (req, res) { res.jsonp(req.user || null); -} +}; /** * Find user by id */ - exports.user = function (req, res, next, id) { User .findOne({ _id : id }) .exec(function (err, user) { - if (err) return next(err) - if (!user) return next(new Error('Failed to load User ' + id)) - req.profile = user - next() - }) -} + if (err) return next(err); + if (!user) return next(new Error('Failed to load User ' + id)); + req.profile = user; + next(); + }); +}; diff --git a/app/models/article.js b/app/models/article.js index dd35e03099..1ae4c946d7 100644 --- a/app/models/article.js +++ b/app/models/article.js @@ -1,15 +1,15 @@ /** * Module dependencies. */ -var mongoose = require('mongoose') - , env = process.env.NODE_ENV || 'development' - , config = require('../../config/config')[env] - , Schema = mongoose.Schema; +var mongoose = require('mongoose'), + env = process.env.NODE_ENV || 'development', + config = require('../../config/config')[env], + Schema = mongoose.Schema; + /** * Article Schema */ - var ArticleSchema = new Schema({ created: {type : Date, default : Date.now}, title: {type: String, default: '', trim : true}, @@ -17,11 +17,9 @@ var ArticleSchema = new Schema({ user: {type : Schema.ObjectId, ref : 'User'} }); - /** * Statics */ - ArticleSchema.statics = { load: function (id, cb) { this.findOne({ _id : id }).populate('user').exec(cb); diff --git a/app/models/user.js b/app/models/user.js index adde190bbc..0ac46238ba 100755 --- a/app/models/user.js +++ b/app/models/user.js @@ -2,17 +2,16 @@ /** * Module dependencies. */ +var mongoose = require('mongoose'), + Schema = mongoose.Schema, + crypto = require('crypto'), + _ = require('underscore'), + authTypes = ['github', 'twitter', 'facebook', 'google']; -var mongoose = require('mongoose') - , Schema = mongoose.Schema - , crypto = require('crypto') - , _ = require('underscore') - , authTypes = ['github', 'twitter', 'facebook', 'google'] /** * User Schema */ - var UserSchema = new Schema({ name: String, email: String, @@ -24,54 +23,52 @@ var UserSchema = new Schema({ twitter: {}, github: {}, google: {} -}) +}); /** * Virtuals */ - UserSchema .virtual('password') .set(function(password) { - this._password = password - this.salt = this.makeSalt() - this.hashed_password = this.encryptPassword(password) + this._password = password; + this.salt = this.makeSalt(); + this.hashed_password = this.encryptPassword(password); }) - .get(function() { return this._password }) + .get(function() { return this._password; }); /** * Validations */ - var validatePresenceOf = function (value) { - return value && value.length -} + return value && value.length; +}; // the below 4 validations only apply if you are signing up traditionally UserSchema.path('name').validate(function (name) { // if you are authenticating by any of the oauth strategies, don't validate - if (authTypes.indexOf(this.provider) !== -1) return true - return name.length -}, 'Name cannot be blank') + if (authTypes.indexOf(this.provider) !== -1) return true; + return name.length; +}, 'Name cannot be blank'); UserSchema.path('email').validate(function (email) { // if you are authenticating by any of the oauth strategies, don't validate - if (authTypes.indexOf(this.provider) !== -1) return true - return email.length -}, 'Email cannot be blank') + if (authTypes.indexOf(this.provider) !== -1) return true; + return email.length; +}, 'Email cannot be blank'); UserSchema.path('username').validate(function (username) { // if you are authenticating by any of the oauth strategies, don't validate - if (authTypes.indexOf(this.provider) !== -1) return true - return username.length -}, 'Username cannot be blank') + if (authTypes.indexOf(this.provider) !== -1) return true; + return username.length; +}, 'Username cannot be blank'); UserSchema.path('hashed_password').validate(function (hashed_password) { // if you are authenticating by any of the oauth strategies, don't validate - if (authTypes.indexOf(this.provider) !== -1) return true - return hashed_password.length -}, 'Password cannot be blank') + if (authTypes.indexOf(this.provider) !== -1) return true; + return hashed_password.length; +}, 'Password cannot be blank'); /** @@ -79,14 +76,13 @@ UserSchema.path('hashed_password').validate(function (hashed_password) { */ UserSchema.pre('save', function(next) { - if (!this.isNew) return next() + if (!this.isNew) return next(); - if (!validatePresenceOf(this.password) - && authTypes.indexOf(this.provider) === -1) - next(new Error('Invalid password')) + if (!validatePresenceOf(this.password) && authTypes.indexOf(this.provider) === -1) + next(new Error('Invalid password')); else - next() -}) + next(); +}); /** * Methods @@ -101,9 +97,8 @@ UserSchema.methods = { * @return {Boolean} * @api public */ - authenticate: function(plainText) { - return this.encryptPassword(plainText) === this.hashed_password + return this.encryptPassword(plainText) === this.hashed_password; }, /** @@ -112,9 +107,8 @@ UserSchema.methods = { * @return {String} * @api public */ - makeSalt: function() { - return Math.round((new Date().valueOf() * Math.random())) + '' + return Math.round((new Date().valueOf() * Math.random())) + ''; }, /** @@ -124,11 +118,10 @@ UserSchema.methods = { * @return {String} * @api public */ - encryptPassword: function(password) { - if (!password) return '' - return crypto.createHmac('sha1', this.salt).update(password).digest('hex') + if (!password) return ''; + return crypto.createHmac('sha1', this.salt).update(password).digest('hex'); } -} +}; -mongoose.model('User', UserSchema) +mongoose.model('User', UserSchema); diff --git a/config/config.js b/config/config.js index 4105121bec..d7c262c16b 100644 --- a/config/config.js +++ b/config/config.js @@ -1,6 +1,6 @@ -var path = require('path') - , rootPath = path.normalize(__dirname + '/..') +var path = require('path'), + rootPath = path.normalize(__dirname + '/..'); module.exports = { development: { @@ -28,7 +28,7 @@ module.exports = { clientID: "APP_ID", clientSecret: "APP_SECRET", callbackURL: "http://localhost:3000/auth/google/callback" - }, + } }, test: { db: 'mongodb://localhost/mean-test', @@ -84,4 +84,4 @@ module.exports = { callbackURL: "http://localhost:3000/auth/google/callback" } } -} +}; diff --git a/config/express.js b/config/express.js index 3ff9e02ad0..13011488d5 100755 --- a/config/express.js +++ b/config/express.js @@ -1,44 +1,43 @@ /** * Module dependencies. */ - -var express = require('express') - , mongoStore = require('connect-mongo')(express) - , flash = require('connect-flash') - , helpers = require('view-helpers') +var express = require('express'), + mongoStore = require('connect-mongo')(express), + flash = require('connect-flash'), + helpers = require('view-helpers'); module.exports = function (app, config, passport) { - app.set('showStackError', true) + app.set('showStackError', true); // should be placed before express.static app.use(express.compress({ filter: function (req, res) { - return /json|text|javascript|css/.test(res.getHeader('Content-Type')); + return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, level: 9 - })) - app.use(express.favicon()) - app.use(express.static(config.root + '/public')) + })); + app.use(express.favicon()); + app.use(express.static(config.root + '/public')); // don't use logger for test env if (process.env.NODE_ENV !== 'test') { - app.use(express.logger('dev')) + app.use(express.logger('dev')); } // set views path, template engine and default layout - app.set('views', config.root + '/app/views') - app.set('view engine', 'jade') - + app.set('views', config.root + '/app/views'); + app.set('view engine', 'jade'); + // enable jsonp - app.enable("jsonp callback") + app.enable("jsonp callback"); app.configure(function () { // cookieParser should be above session - app.use(express.cookieParser()) + app.use(express.cookieParser()); // bodyParser should be above methodOverride - app.use(express.bodyParser()) - app.use(express.methodOverride()) + app.use(express.bodyParser()); + app.use(express.methodOverride()); // express/mongo session storage app.use(express.session({ @@ -47,20 +46,20 @@ module.exports = function (app, config, passport) { url: config.db, collection : 'sessions' }) - })) + })); // connect flash for flash messages - app.use(flash()) + app.use(flash()); // dynamic helpers - app.use(helpers(config.app.name)) + app.use(helpers(config.app.name)); // use passport session - app.use(passport.initialize()) - app.use(passport.session()) + app.use(passport.initialize()); + app.use(passport.session()); // routes should be at the last - app.use(app.router) + app.use(app.router); // assume "not found" in the error msgs // is a 404. this is somewhat silly, but @@ -68,19 +67,19 @@ module.exports = function (app, config, passport) { // properties, use instanceof etc. app.use(function(err, req, res, next){ // treat as 404 - if (~err.message.indexOf('not found')) return next() + if (~err.message.indexOf('not found')) return next(); // log it - console.error(err.stack) + console.error(err.stack); // error page - res.status(500).render('500', { error: err.stack }) - }) + res.status(500).render('500', { error: err.stack }); + }); // assume 404 since no middleware responded app.use(function(req, res, next){ - res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }) - }) + res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }); + }); - }) -} + }); +}; diff --git a/config/middlewares/authorization.js b/config/middlewares/authorization.js index b78360bc41..df13c7f1d5 100755 --- a/config/middlewares/authorization.js +++ b/config/middlewares/authorization.js @@ -2,38 +2,33 @@ /* * Generic require login routing middleware */ - exports.requiresLogin = function (req, res, next) { if (!req.isAuthenticated()) { - return res.redirect('/login') + return res.redirect('/login'); } - next() + next(); }; - /* * User authorizations routing middleware */ - exports.user = { hasAuthorization : function (req, res, next) { if (req.profile.id != req.user.id) { - return res.redirect('/users/'+req.profile.id) + return res.redirect('/users/'+req.profile.id); } - next() + next(); } -} - +}; /* * Article authorizations routing middleware */ - exports.article = { hasAuthorization : function (req, res, next) { if (req.article.user.id != req.user.id) { - return res.redirect('/articles/'+req.article.id) + return res.redirect('/articles/'+req.article.id); } - next() + next(); } -} +}; diff --git a/config/passport.js b/config/passport.js index 4169a175fe..f24fdd8ae1 100755 --- a/config/passport.js +++ b/config/passport.js @@ -1,11 +1,11 @@ -var mongoose = require('mongoose') - , LocalStrategy = require('passport-local').Strategy - , TwitterStrategy = require('passport-twitter').Strategy - , FacebookStrategy = require('passport-facebook').Strategy - , GitHubStrategy = require('passport-github').Strategy - , GoogleStrategy = require('passport-google-oauth').Strategy - , User = mongoose.model('User') +var mongoose = require('mongoose'), + LocalStrategy = require('passport-local').Strategy, + TwitterStrategy = require('passport-twitter').Strategy, + FacebookStrategy = require('passport-facebook').Strategy, + GitHubStrategy = require('passport-github').Strategy, + GoogleStrategy = require('passport-google-oauth').Strategy, + User = mongoose.model('User'); module.exports = function (passport, config) { @@ -13,14 +13,14 @@ module.exports = function (passport, config) { // serialize sessions passport.serializeUser(function(user, done) { - done(null, user.id) - }) + done(null, user.id); + }); passport.deserializeUser(function(id, done) { User.findOne({ _id: id }, function (err, user) { - done(err, user) - }) - }) + done(err, user); + }); + }); // use local strategy passport.use(new LocalStrategy({ @@ -29,74 +29,74 @@ module.exports = function (passport, config) { }, function(email, password, done) { User.findOne({ email: email }, function (err, user) { - if (err) { return done(err) } + if (err) { return done(err); } if (!user) { - return done(null, false, { message: 'Unknown user' }) + return done(null, false, { message: 'Unknown user' }); } if (!user.authenticate(password)) { - return done(null, false, { message: 'Invalid password' }) + return done(null, false, { message: 'Invalid password' }); } - return done(null, user) - }) + return done(null, user); + }); } - )) + )); // use twitter strategy passport.use(new TwitterStrategy({ - consumerKey: config.twitter.clientID - , consumerSecret: config.twitter.clientSecret - , callbackURL: config.twitter.callbackURL + consumerKey: config.twitter.clientID, + consumerSecret: config.twitter.clientSecret, + callbackURL: config.twitter.callbackURL }, function(token, tokenSecret, profile, done) { User.findOne({ 'twitter.id': profile.id }, function (err, user) { - if (err) { return done(err) } + if (err) { return done(err); } if (!user) { user = new User({ - name: profile.displayName - , username: profile.username - , provider: 'twitter' - , twitter: profile._json - }) + name: profile.displayName, + username: profile.username, + provider: 'twitter', + twitter: profile._json + }); user.save(function (err) { - if (err) console.log(err) - return done(err, user) - }) + if (err) console.log(err); + return done(err, user); + }); } else { - return done(err, user) + return done(err, user); } - }) + }); } - )) + )); // use facebook strategy passport.use(new FacebookStrategy({ - clientID: config.facebook.clientID - , clientSecret: config.facebook.clientSecret - , callbackURL: config.facebook.callbackURL + clientID: config.facebook.clientID, + clientSecret: config.facebook.clientSecret, + callbackURL: config.facebook.callbackURL }, function(accessToken, refreshToken, profile, done) { User.findOne({ 'facebook.id': profile.id }, function (err, user) { - if (err) { return done(err) } + if (err) { return done(err); } if (!user) { user = new User({ - name: profile.displayName - , email: profile.emails[0].value - , username: profile.username - , provider: 'facebook' - , facebook: profile._json - }) + name: profile.displayName, + email: profile.emails[0].value, + username: profile.username, + provider: 'facebook', + facebook: profile._json + }); user.save(function (err) { - if (err) console.log(err) - return done(err, user) - }) + if (err) console.log(err); + return done(err, user); + }); } else { - return done(err, user) + return done(err, user); } - }) + }); } - )) + )); // use github strategy passport.use(new GitHubStrategy({ @@ -108,22 +108,22 @@ module.exports = function (passport, config) { User.findOne({ 'github.id': profile.id }, function (err, user) { if (!user) { user = new User({ - name: profile.displayName - , email: profile.emails[0].value - , username: profile.username - , provider: 'github' - , github: profile._json - }) + name: profile.displayName, + email: profile.emails[0].value, + username: profile.username, + provider: 'github', + github: profile._json + }); user.save(function (err) { - if (err) console.log(err) - return done(err, user) - }) + if (err) console.log(err); + return done(err, user); + }); } else { - return done(err, user) + return done(err, user); } - }) + }); } - )) + )); // use google strategy passport.use(new GoogleStrategy({ @@ -135,20 +135,20 @@ module.exports = function (passport, config) { User.findOne({ 'google.id': profile.id }, function (err, user) { if (!user) { user = new User({ - name: profile.displayName - , email: profile.emails[0].value - , username: profile.username - , provider: 'google' - , google: profile._json - }) + name: profile.displayName, + email: profile.emails[0].value, + username: profile.username, + provider: 'google', + google: profile._json + }); user.save(function (err) { - if (err) console.log(err) - return done(err, user) - }) + if (err) console.log(err); + return done(err, user); + }); } else { - return done(err, user) + return done(err, user); } - }) + }); } )); -} +}; diff --git a/config/routes.js b/config/routes.js index 41d56e2ebd..bc837a3988 100755 --- a/config/routes.js +++ b/config/routes.js @@ -1,39 +1,39 @@ -var async = require('async') +var async = require('async'); module.exports = function (app, passport, auth) { // user routes - var users = require('../app/controllers/users') - app.get('/signin', users.signin) - app.get('/signup', users.signup) - app.get('/signout', users.signout) - app.post('/users', users.create) - app.post('/users/session', passport.authenticate('local', {failureRedirect: '/signin', failureFlash: 'Invalid email or password.'}), users.session) - app.get('/users/me', users.me) - app.get('/users/:userId', users.show) - app.get('/auth/facebook', passport.authenticate('facebook', { scope: [ 'email', 'user_about_me'], failureRedirect: '/signin' }), users.signin) - app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/signin' }), users.authCallback) - app.get('/auth/github', passport.authenticate('github', { failureRedirect: '/signin' }), users.signin) - app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/signin' }), users.authCallback) - app.get('/auth/twitter', passport.authenticate('twitter', { failureRedirect: '/signin' }), users.signin) - app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/signin' }), users.authCallback) - app.get('/auth/google', passport.authenticate('google', { failureRedirect: '/signin', scope: 'https://www.google.com/m8/feeds' }), users.signin) - app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/signin', scope: 'https://www.google.com/m8/feeds' }), users.authCallback) - - app.param('userId', users.user) - - var articles = require('../app/controllers/articles') - app.get('/articles', articles.all) - app.post('/articles', auth.requiresLogin, articles.create) - app.get('/articles/:articleId', articles.show) - app.put('/articles/:articleId', auth.requiresLogin, auth.article.hasAuthorization, articles.update) - app.del('/articles/:articleId', auth.requiresLogin, auth.article.hasAuthorization, articles.destroy) - - app.param('articleId', articles.article) + var users = require('../app/controllers/users'); + app.get('/signin', users.signin); + app.get('/signup', users.signup); + app.get('/signout', users.signout); + app.post('/users', users.create); + app.post('/users/session', passport.authenticate('local', {failureRedirect: '/signin', failureFlash: 'Invalid email or password.'}), users.session); + app.get('/users/me', users.me); + app.get('/users/:userId', users.show); + app.get('/auth/facebook', passport.authenticate('facebook', { scope: [ 'email', 'user_about_me'], failureRedirect: '/signin' }), users.signin); + app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/signin' }), users.authCallback); + app.get('/auth/github', passport.authenticate('github', { failureRedirect: '/signin' }), users.signin); + app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/signin' }), users.authCallback); + app.get('/auth/twitter', passport.authenticate('twitter', { failureRedirect: '/signin' }), users.signin); + app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/signin' }), users.authCallback); + app.get('/auth/google', passport.authenticate('google', { failureRedirect: '/signin', scope: 'https://www.google.com/m8/feeds' }), users.signin); + app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/signin', scope: 'https://www.google.com/m8/feeds' }), users.authCallback); + + app.param('userId', users.user); + + var articles = require('../app/controllers/articles'); + app.get('/articles', articles.all); + app.post('/articles', auth.requiresLogin, articles.create); + app.get('/articles/:articleId', articles.show); + app.put('/articles/:articleId', auth.requiresLogin, auth.article.hasAuthorization, articles.update); + app.del('/articles/:articleId', auth.requiresLogin, auth.article.hasAuthorization, articles.destroy); + + app.param('articleId', articles.article); // home route - var index = require('../app/controllers/index') - app.get('/', index.render) + var index = require('../app/controllers/index'); + app.get('/', index.render); -} +};