diff --git a/.editorconfig b/.editorconfig index 06dd60bfd1..6c012e5334 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,6 +1,6 @@ # EditorConfig is awesome: http://EditorConfig.org -# Howto with your editor: +# Howto with your editor: http://editorconfig.org/#download # Sublime: https://github.com/sindresorhus/editorconfig-sublime # top-most EditorConfig file @@ -34,3 +34,9 @@ indent_style = tab # Standard at: [Makefile] indent_style = tab + +# The indentation in package.json will always need to be 2 spaces +# https://github.com/npm/npm/issues/4718 +[package.json, bower.json] +indent_style = space +indent_size = 2 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 3ec34150c9..0d3109886d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,63 @@ +# OS +# =========== .DS_Store +ehthumbs.db +Icon? +Thumbs.db + +# Node and related ecosystem +# ========================== .nodemonignore .sass-cache/ -npm-debug.log node_modules/ public/lib/ -public/dist/ +app/tests/coverage/ .bower-*/ .idea/ + +# MEAN.js app and assets +# ====================== +public/dist/ uploads modules/users/client/img/profile/uploads +config/env/local.js +*.pem + +# Sublime editor +# ============== +.sublime-project +*.sublime-project +*.sublime-workspace + +# Eclipse project files +# ===================== +.project +.settings/ +.*.md.html +.metadata +*~.nib +local.properties + +# IntelliJ +# ======== +*.iml + +# Cloud9 IDE +# ========= +.c9/ +data/ +mongod + +# General +# ======= +*.log +*.csv +*.dat +*.out +*.pid +*.gz +*.tmp +*.bak +*.swp +logs/ +build/ diff --git a/.travis.yml b/.travis.yml index 32edf2495e..eef75fbf97 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,7 @@ language: node_js node_js: - "0.10" + - "0.12" env: - NODE_ENV=travis services: diff --git a/Dockerfile b/Dockerfile index de61a99205..d6a654b74b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM dockerfile/nodejs +FROM node:0.10 MAINTAINER Matthias Luebken, matthias@catalyst-zero.com @@ -20,7 +20,7 @@ RUN bower install --config.interactive=false --allow-root # Make everything available for start ADD . /home/mean -# currently only works for development +# Set development environment as default ENV NODE_ENV development # Port 3000 for server diff --git a/README.md b/README.md index dec285d123..45660e3868 100644 --- a/README.md +++ b/README.md @@ -2,68 +2,73 @@ [![Build Status](https://travis-ci.org/meanjs/mean.svg?branch=master)](https://travis-ci.org/meanjs/mean) [![Dependencies Status](https://david-dm.org/meanjs/mean.svg)](https://david-dm.org/meanjs/mean) +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/meanjs/mean?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -MEAN.JS is a full-stack JavaScript open-source solution, which provides a solid starting point for [MongoDB](http://www.mongodb.org/), [Node.js](http://www.nodejs.org/), [Express](http://expressjs.com/), and [AngularJS](http://angularjs.org/) based applications. The idea is to solve the common issues with connecting those frameworks, build a robust framework to support daily development needs, and help developers use better practices while working with popular JavaScript components. +MEAN.JS is a full-stack JavaScript open-source solution, which provides a solid starting point for [MongoDB](http://www.mongodb.org/), [Node.js](http://www.nodejs.org/), [Express](http://expressjs.com/), and [AngularJS](http://angularjs.org/) based applications. The idea is to solve the common issues with connecting those frameworks, build a robust framework to support daily development needs, and help developers use better practices while working with popular JavaScript components. -## Before You Begin -Before you begin we recommend you read about the basic building blocks that assemble a MEAN.JS application: +## Before You Begin +Before you begin we recommend you read about the basic building blocks that assemble a MEAN.JS application: * MongoDB - Go through [MongoDB Official Website](http://mongodb.org/) and proceed to their [Official Manual](http://docs.mongodb.org/manual/), which should help you understand NoSQL and MongoDB better. -* Express - The best way to understand express is through its [Official Website](http://expressjs.com/), particularly [The Express Guide](http://expressjs.com/guide.html); you can also go through this [StackOverflow Thread](http://stackoverflow.com/questions/8144214/learning-express-for-node-js) for more resources. +* Express - The best way to understand express is through its [Official Website](http://expressjs.com/), which has a [Getting Started](http://expressjs.com/starter/installing.html) guide, as well as an [ExpressJS Guide](http://expressjs.com/guide/error-handling.html) guide for general express topics. You can also go through this [StackOverflow Thread](http://stackoverflow.com/questions/8144214/learning-express-for-node-js) for more resources. * AngularJS - Angular's [Official Website](http://angularjs.org/) is a great starting point. You can also use [Thinkster Popular Guide](http://www.thinkster.io/), and the [Egghead Videos](https://egghead.io/). * Node.js - Start by going through [Node.js Official Website](http://nodejs.org/) and this [StackOverflow Thread](http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js), which should get you going with the Node.js platform in no time. ## Prerequisites -Make sure you have installed all these prerequisites on your development machine. -* Node.js - [Download & Install Node.js](http://www.nodejs.org/download/) and the npm package manager, if you encounter any problems, you can also use this [Github Gist](https://gist.github.com/isaacs/579814) to install Node.js. +Make sure you have installed all of the following prerequisites on your development machine: +* Node.js - [Download & Install Node.js](http://www.nodejs.org/download/) and the npm package manager. If you encounter any problems, you can also use this [GitHub Gist](https://gist.github.com/isaacs/579814) to install Node.js. * MongoDB - [Download & Install MongoDB](http://www.mongodb.org/downloads), and make sure it's running on the default port (27017). -* Bower - You're going to use the [Bower Package Manager](http://bower.io/) to manage your front-end packages, in order to install it make sure you've installed Node.js and npm, then install bower globally using npm: +* Bower - You're going to use the [Bower Package Manager](http://bower.io/) to manage your front-end packages. Make sure you've installed Node.js and npm first, then install bower globally using npm: -``` +```bash $ npm install -g bower ``` -* Grunt - You're going to use the [Grunt Task Runner](http://gruntjs.com/) to automate your development process, in order to install it make sure you've installed Node.js and npm, then install grunt globally using npm: +* Grunt - You're going to use the [Grunt Task Runner](http://gruntjs.com/) to automate your development process. Make sure you've installed Node.js and npm first, then install grunt globally using npm: -``` -$ sudo npm install -g grunt-cli +```bash +$ npm install -g grunt-cli ``` ## Downloading MEAN.JS -There are several ways you can get the MEAN.JS boilerplate: +There are several ways you can get the MEAN.JS boilerplate: -### Yo Generator -The recommended way would be to use the [Official Yo Generator](http://meanjs.org/generator.html) which will generate the latest stable copy of the MEAN.JS boilerplate and supplies multiple sub-generators to ease your daily development cycles. +### Yo Generator +The recommended way would be to use the [Official Yo Generator](http://meanjs.org/generator.html), which generates the latest stable copy of the MEAN.JS boilerplate and supplies multiple sub-generators to ease your daily development cycles. ### Cloning The GitHub Repository You can also use Git to directly clone the MEAN.JS repository: -``` + +```bash $ git clone https://github.com/meanjs/mean.git meanjs ``` + This will clone the latest version of the MEAN.JS repository to a **meanjs** folder. ### Downloading The Repository Zip File -Another way to use the MEAN.JS boilerplate is to download a zip copy from the [master branch on github](https://github.com/meanjs/mean/archive/master.zip). You can also do this using `wget` command: -``` +Another way to use the MEAN.JS boilerplate is to download a zip copy from the [master branch on GitHub](https://github.com/meanjs/mean/archive/master.zip). You can also do this using `wget` command: + +```bash $ wget https://github.com/meanjs/mean/archive/master.zip -O meanjs.zip; unzip meanjs.zip; rm meanjs.zip ``` + Don't forget to rename **mean-master** after your project name. ## Quick Install -Once you've downloaded the boilerplate and installed all the prerequisites, you're just a few steps away from starting to develop you MEAN application. +Once you've downloaded the boilerplate and installed all the prerequisites, you're just a few steps away from starting to develop your MEAN application. -The first thing you should do is install the Node.js dependencies. The boilerplate comes pre-bundled with a package.json file that contains the list of modules you need to start your application, to learn more about the modules installed visit the NPM & Package.json section. +The first thing you should do is install the Node.js dependencies. The boilerplate comes pre-bundled with a package.json file that contains the list of modules you need to start your application. To learn more about the modules installed visit the NPM & Package.json section. -To install Node.js dependencies you're going to use npm again, in the application folder run this in the command-line: +To install Node.js dependencies you're going to use npm again. In the application folder run this in the command-line: -``` +```bash $ npm install ``` This command does a few things: * First it will install the dependencies needed for the application to run. * If you're running in a development environment, it will then also install development dependencies needed for testing and running your application. -* Finally, when the install process is over, npm will initiate a bower installcommand to install all the front-end modules needed for the application +* Finally, when the install process is over, npm will initiate a bower install command to install all the front-end modules needed for the application ## Running Your Application After the install process is over, you'll be able to run your application using Grunt, just run grunt default task: @@ -72,19 +77,66 @@ After the install process is over, you'll be able to run your application using $ grunt ``` -Your application should run on the 3000 port so in your browser just go to [http://localhost:3000](http://localhost:3000) - -That's it! your application should be running by now, to proceed with your development check the other sections in this documentation. -If you encounter any problem try the Troubleshooting section. +Your application should run on port 3000 with the *development* environment configuration, so in your browser just go to [http://localhost:3000](http://localhost:3000) + +That's it! Your application should be running. To proceed with your development, check the other sections in this documentation. +If you encounter any problems, try the Troubleshooting section. + +* explore `config/env/development.js` for development environment configuration options + +### Running in Production mode +To run your application with *production* environment configuration, execute grunt as follows: + +```bash +$ grunt prod +``` + +* explore `config/env/production.js` for production environment configuration options + +### Running with TLS (SSL) +Application will start by default with secure configuration (SSL mode) turned on and listen on port 8443. +To run your application in a secure manner you'll need to use OpenSSL and generate a set of self-signed certificates. Unix-based users can use the following command: + +```bash +$ sh ./scripts/generate-ssl-certs.sh +``` + +Windows users can follow instructions found [here](http://www.websense.com/support/article/kbarticle/How-to-use-OpenSSL-and-Microsoft-Certification-Authority). +After you've generated the key and certificate, place them in the *config/sslcerts* folder. + +Finally, execute grunt's prod task `grunt prod` +* enable/disable SSL mode in production environment change the `secure` option in `config/env/production.js` + + +## Testing Your Application +You can run the full test suite included with MEAN.JS with the test task: + +```bash +$ grunt test +``` + +This will run both the server-side tests (located in the app/tests/ directory) and the client-side tests (located in the public/modules/*/tests/). + +To execute only the server tests, run the test:server task: + +```bash +$ grunt test:server +``` + +And to run only the client tests, run the test:client task: + +```bash +$ grunt test:client +``` ## Development and deployment With Docker -* Install [Docker](http://www.docker.com/) -* Install [Fig](https://github.com/orchardup/fig) +* Install [Docker](https://docs.docker.com/installation/#installation) +* Install [Compose](https://docs.docker.com/compose/install/) -* Local development and testing with fig: +* Local development and testing with compose: ```bash -$ fig up +$ docker-compose up ``` * Local development and testing with just Docker: @@ -95,17 +147,17 @@ $ docker run -p 3000:3000 --link db:db_1 mean $ ``` -* To enable live reload forward 35729 port and mount /app and /public as volumes: +* To enable live reload, forward port 35729 and mount /app and /public as volumes: ```bash -$ docker run -p 3000:3000 -p 35729:35729 -v /Users/mdl/workspace/mean-stack/mean/public:/home/mean/public -v /Users/mdl/workspa/mean-stack/mean/app:/home/mean/app --link db:db_1 mean +$ docker run -p 3000:3000 -p 35729:35729 -v /Users/mdl/workspace/mean-stack/mean/public:/home/mean/public -v /Users/mdl/workspace/mean-stack/mean/app:/home/mean/app --link db:db_1 mean ``` ## Getting Started With MEAN.JS -You have your application running but there are a lot of stuff to understand, we recommend you'll go over the [Offical Documentation](http://meanjs.org/docs.html). -In the docs we'll try to explain both general concepts of MEAN components and give you some guidelines to help you improve your development procees. We tried covering as many aspects as possible, and will keep update it by your request, you can also help us develop the documentation better by checking out the *gh-pages* branch of this repository. +You have your application running, but there is a lot of stuff to understand. We recommend you go over the [Official Documentation](http://meanjs.org/docs.html). +In the docs we'll try to explain both general concepts of MEAN components and give you some guidelines to help you improve your development process. We tried covering as many aspects as possible, and will keep it updated by your request. You can also help us develop and improve the documentation by checking out the *gh-pages* branch of this repository. ## Community -* Use to [Offical Website](http://meanjs.org) to learn about changes and the roadmap. +* Use the [Official Website](http://meanjs.org) to learn about changes and the roadmap. * Join #meanjs on freenode. * Discuss it in the new [Google Group](https://groups.google.com/d/forum/meanjs) * Ping us on [Twitter](http://twitter.com/meanjsorg) and [Facebook](http://facebook.com/meanjs) diff --git a/bower.json b/bower.json index 951e48aaac..8ea5593a60 100644 --- a/bower.json +++ b/bower.json @@ -1,16 +1,19 @@ { - "name": "meanjs", - "version": "0.4.0", - "description": "Fullstack JavaScript with MongoDB, Express, AngularJS, and Node.js.", - "dependencies": { - "bootstrap": "~3", - "angular": "~1.2", - "angular-resource": "~1.2", - "angular-animate": "~1.2", - "angular-mocks": "~1.2", - "angular-bootstrap": "~0.11.0", - "angular-ui-utils": "~0.1.1", - "angular-ui-router": "~0.2.10", - "angular-file-upload": "~1.1.5" - } + "name": "meanjs", + "version": "0.4.0", + "description": "Fullstack JavaScript with MongoDB, Express, AngularJS, and Node.js.", + "dependencies": { + "bootstrap": "~3", + "angular": "~1.3", + "angular-resource": "~1.3", + "angular-animate": "~1.3", + "angular-mocks": "~1.3", + "angular-bootstrap": "~0.13", + "angular-ui-utils": "bower", + "angular-ui-router": "~0.2", + "angular-file-upload": "~1.1.5" + }, + "resolutions": { + "angular": "~1.3" + } } diff --git a/config/config.js b/config/config.js index 670cd3f341..cabe4654ef 100644 --- a/config/config.js +++ b/config/config.js @@ -6,6 +6,7 @@ var _ = require('lodash'), chalk = require('chalk'), glob = require('glob'), + fs = require('fs'), path = require('path'); /** @@ -60,8 +61,6 @@ var validateEnvironmentVariable = function() { console.error(chalk.red('NODE_ENV is not defined! Using default development environment')); } process.env.NODE_ENV = 'development'; - } else { - console.log(chalk.bold('Application loaded using the "' + process.env.NODE_ENV + '" environment configuration')); } // Reset console color console.log(chalk.white('')); @@ -139,7 +138,9 @@ var initGlobalConfig = function() { var environmentConfig = require(path.join(process.cwd(), 'config/env/', process.env.NODE_ENV)) || {}; // Merge config files - var config = _.extend(defaultConfig, environmentConfig); + var envConf = _.extend(defaultConfig, environmentConfig); + + var config = _.merge(envConf, (fs.existsSync(path.join(process.cwd(), 'config/env/local.js')) && require(path.join(process.cwd(), 'config/env/local.js'))) || {}); // Initialize global globbed files initGlobalConfigFiles(config, assets); diff --git a/config/env/development.js b/config/env/development.js index c61be6e592..df4f2a3813 100644 --- a/config/env/development.js +++ b/config/env/development.js @@ -1,7 +1,22 @@ 'use strict'; module.exports = { - db: 'mongodb://localhost/mean-dev', + db: { + uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean-dev', + options: { + user: '', + pass: '' + } + }, + log: { + // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny' + format: 'dev', + // Stream defaults to process.stdout + // Uncomment to enable logging to a log on the file system + options: { + //stream: 'access.log' + } + }, app: { title: 'MEAN.JS - Development Environment' }, diff --git a/config/env/local.example.js b/config/env/local.example.js new file mode 100644 index 0000000000..824a29930f --- /dev/null +++ b/config/env/local.example.js @@ -0,0 +1,23 @@ +'use strict'; + +// Rename this file to local.js for having a local configuration variables that +// will not get commited and pushed to remote repositories. +// Use it for your API keys, passwords, etc. + +/* For example: + +module.exports = { + db: { + uri: 'mongodb://localhost/local-dev', + options: { + user: '', + pass: '' + } + }, + facebook: { + clientID: process.env.FACEBOOK_ID || 'APP_ID', + clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', + callbackURL: '/auth/facebook/callback' + } +}; +*/ \ No newline at end of file diff --git a/config/env/production.js b/config/env/production.js index 003be5fe35..f660add711 100644 --- a/config/env/production.js +++ b/config/env/production.js @@ -1,46 +1,63 @@ 'use strict'; module.exports = { - db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean', - facebook: { - clientID: process.env.FACEBOOK_ID || 'APP_ID', - clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', - callbackURL: '/api/auth/facebook/callback' - }, - twitter: { - clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', - clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', - callbackURL: '/api/auth/twitter/callback' - }, - google: { - clientID: process.env.GOOGLE_ID || 'APP_ID', - clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', - callbackURL: '/api/auth/google/callback' - }, - linkedin: { - clientID: process.env.LINKEDIN_ID || 'APP_ID', - clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', - callbackURL: '/api/auth/linkedin/callback' - }, - github: { - clientID: process.env.GITHUB_ID || 'APP_ID', - clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', - callbackURL: '/api/auth/github/callback' - }, - paypal: { - clientID: process.env.PAYPAL_ID || 'CLIENT_ID', - clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET', - callbackURL: '/api/auth/paypal/callback', - sandbox: false - }, - mailer: { - from: process.env.MAILER_FROM || 'MAILER_FROM', - options: { - service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', - auth: { - user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', - pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' - } - } - } + secure: true, + port: process.env.PORT || 8443, + db: { + uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean', + options: { + user: '', + pass: '' + } + }, + log: { + // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny' + format: 'combined', + // Stream defaults to process.stdout + // Uncomment to enable logging to a log on the file system + options: { + stream: 'access.log' + } + }, + facebook: { + clientID: process.env.FACEBOOK_ID || 'APP_ID', + clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', + callbackURL: '/api/auth/facebook/callback' + }, + twitter: { + clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', + clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', + callbackURL: '/api/auth/twitter/callback' + }, + google: { + clientID: process.env.GOOGLE_ID || 'APP_ID', + clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', + callbackURL: '/api/auth/google/callback' + }, + linkedin: { + clientID: process.env.LINKEDIN_ID || 'APP_ID', + clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', + callbackURL: '/api/auth/linkedin/callback' + }, + github: { + clientID: process.env.GITHUB_ID || 'APP_ID', + clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', + callbackURL: '/api/auth/github/callback' + }, + paypal: { + clientID: process.env.PAYPAL_ID || 'CLIENT_ID', + clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET', + callbackURL: '/api/auth/paypal/callback', + sandbox: false + }, + mailer: { + from: process.env.MAILER_FROM || 'MAILER_FROM', + options: { + service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', + auth: { + user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', + pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' + } + } + } }; diff --git a/config/env/test.js b/config/env/test.js index 9a6d9514e2..34c6ba8553 100644 --- a/config/env/test.js +++ b/config/env/test.js @@ -1,8 +1,14 @@ 'use strict'; module.exports = { - db: 'mongodb://localhost/mean-test', - port: 3001, + db: { + uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean-test', + options: { + user: '', + pass: '' + } + }, + port: process.env.PORT || 3001, app: { title: 'MEAN.JS - Test Environment' }, diff --git a/config/lib/express.js b/config/lib/express.js index b01eb9abf1..a208695df4 100644 --- a/config/lib/express.js +++ b/config/lib/express.js @@ -27,6 +27,7 @@ module.exports.initLocalVariables = function (app) { // Setting application local variables app.locals.title = config.app.title; app.locals.description = config.app.description; + app.locals.secure = config.secure; app.locals.keywords = config.app.keywords; app.locals.googleAnalyticsTrackingID = config.app.googleAnalyticsTrackingID; app.locals.facebookAppId = config.facebook.clientID; @@ -54,7 +55,7 @@ module.exports.initMiddleware = function (app) { // Should be placed before express.static app.use(compress({ filter: function (req, res) { - return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); + return (/json|text|javascript|css|font|svg/).test(res.getHeader('Content-Type')); }, level: 9 })); diff --git a/config/lib/mongoose.js b/config/lib/mongoose.js index 51eb37f76a..731abb62b8 100644 --- a/config/lib/mongoose.js +++ b/config/lib/mongoose.js @@ -20,7 +20,7 @@ module.exports.loadModels = function() { module.exports.connect = function(cb) { var _this = this; - var db = mongoose.connect(config.db, function (err) { + var db = mongoose.connect(config.db.uri, config.db.options, function (err) { // Log Error if (err) { console.error(chalk.red('Could not connect to MongoDB!')); diff --git a/config/lib/socket.io.js b/config/lib/socket.io.js index 3312bb4ad4..18adffd0d0 100644 --- a/config/lib/socket.io.js +++ b/config/lib/socket.io.js @@ -2,60 +2,75 @@ // Load the module dependencies var config = require('../config'), - path = require('path'), + path = require('path'), + fs = require('fs'), + http = require('http'), + https = require('https'), cookieParser = require('cookie-parser'), passport = require('passport'), socketio = require('socket.io'), - session = require('express-session'), - MongoStore = require('connect-mongo')(session), - http = require('http'); + session = require('express-session'), + MongoStore = require('connect-mongo')(session); // Define the Socket.io configuration method module.exports = function(app, db) { - // Create a new HTTP server - var server = http.createServer(app); + var server; + if (config.secure === true) { + // Load SSL key and certificate + var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'); + var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'); + var options = { + key: privateKey, + cert: certificate + }; - // Create a new Socket.io server - var io = socketio.listen(server); + // Create new HTTPS Server + server = https.createServer(options, app); + } else { + // Create a new HTTP server + server = http.createServer(app); + } + // Create a new Socket.io server + var io = socketio.listen(server); - // Create a MongoDB storage object - var mongoStore = new MongoStore({ - mongooseConnection: db.connection, - collection: config.sessionCollection - }); + // Create a MongoDB storage object + var mongoStore = new MongoStore({ + mongooseConnection: db.connection, + collection: config.sessionCollection + }); + + // Intercept Socket.io's handshake request + io.use(function(socket, next) { + // Use the 'cookie-parser' module to parse the request cookies + cookieParser(config.sessionSecret)(socket.request, {}, function(err) { + // Get the session id from the request cookies + var sessionId = socket.request.signedCookies['connect.sid']; - // Intercept Socket.io's handshake request - io.use(function(socket, next) { - // Use the 'cookie-parser' module to parse the request cookies - cookieParser(config.sessionSecret)(socket.request, {}, function(err) { - // Get the session id from the request cookies - var sessionId = socket.request.signedCookies['connect.sid']; - - // Use the mongoStorage instance to get the Express session information - mongoStore.get(sessionId, function(err, session) { - // Set the Socket.io session information - socket.request.session = session; - - // Use Passport to populate the user details - passport.initialize()(socket.request, {}, function() { - passport.session()(socket.request, {}, function() { - if (socket.request.user) { - next(null, true); - } else { - next(new Error('User is not authenticated'), false); - } - }); - }); - }); + // Use the mongoStorage instance to get the Express session information + mongoStore.get(sessionId, function(err, session) { + // Set the Socket.io session information + socket.request.session = session; + + // Use Passport to populate the user details + passport.initialize()(socket.request, {}, function() { + passport.session()(socket.request, {}, function() { + if (socket.request.user) { + next(null, true); + } else { + next(new Error('User is not authenticated'), false); + } + }); }); + }); }); + }); - // Add an event listener to the 'connection' event - io.on('connection', function(socket) { - config.files.server.sockets.forEach(function(socketConfiguration) { - require(path.resolve(socketConfiguration))(io, socket); - }); + // Add an event listener to the 'connection' event + io.on('connection', function(socket) { + config.files.server.sockets.forEach(function(socketConfiguration) { + require(path.resolve(socketConfiguration))(io, socket); }); + }); - return server; + return server; }; diff --git a/fig.yml b/docker-compose.yml similarity index 100% rename from fig.yml rename to docker-compose.yml diff --git a/gruntfile.js b/gruntfile.js index ea4eb0d88e..132e209dc3 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -5,7 +5,8 @@ */ var _ = require('lodash'), defaultAssets = require('./config/assets/default'), - testAssets = require('./config/assets/test'); + testAssets = require('./config/assets/test'), + fs = require('fs'); module.exports = function (grunt) { // Project Configuration @@ -190,6 +191,15 @@ module.exports = function (grunt) { args: {} // Target-specific arguments } } + }, + copy: { + localConfig: { + src: 'config/env/local.example.js', + dest: 'config/env/local.js', + filter: function() { + return !fs.existsSync('config/env/local.js'); + } + } } }); @@ -220,14 +230,16 @@ module.exports = function (grunt) { grunt.registerTask('build', ['env:dev', 'lint', 'ngAnnotate', 'uglify', 'cssmin']); // Run the project tests - grunt.registerTask('test', ['env:test', 'mongoose', 'mochaTest', 'karma:unit']); + grunt.registerTask('test', ['env:test', 'copy:localConfig', 'mongoose', 'mochaTest', 'karma:unit']); + grunt.registerTask('test:server', ['env:test', 'mongoose', 'mochaTest']); + grunt.registerTask('test:client', ['env:test', 'mongoose', 'karma:unit']); // Run the project in development mode - grunt.registerTask('default', ['env:dev', 'lint', 'concurrent:default']); + grunt.registerTask('default', ['env:dev', 'lint', 'copy:localConfig', 'concurrent:default']); // Run the project in debug mode - grunt.registerTask('debug', ['env:dev', 'lint', 'concurrent:debug']); + grunt.registerTask('debug', ['env:dev', 'lint', 'copy:localConfig', 'concurrent:debug']); // Run the project in production mode - grunt.registerTask('prod', ['build', 'env:prod', 'concurrent:default']); + grunt.registerTask('prod', ['build', 'env:prod', 'copy:localConfig', 'concurrent:default']); }; diff --git a/karma.conf.js b/karma.conf.js index 0b6ead26de..2e926ad5f3 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -18,7 +18,6 @@ module.exports = function(karmaConfig) { // Test results reporter to use // Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' - //reporters: ['progress'], reporters: ['progress'], // Web server port diff --git a/modules/articles/client/controllers/articles.client.controller.js b/modules/articles/client/controllers/articles.client.controller.js index 2ea4e2a856..a54e32ea7e 100644 --- a/modules/articles/client/controllers/articles.client.controller.js +++ b/modules/articles/client/controllers/articles.client.controller.js @@ -1,17 +1,23 @@ 'use strict'; +// Articles controller angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', function($scope, $stateParams, $location, Authentication, Articles) { $scope.authentication = Authentication; + // Create new Article $scope.create = function() { + // Create new Article object var article = new Articles({ title: this.title, content: this.content }); + + // Redirect after save article.$save(function(response) { $location.path('articles/' + response._id); + // Clear form fields $scope.title = ''; $scope.content = ''; }, function(errorResponse) { @@ -19,6 +25,7 @@ angular.module('articles').controller('ArticlesController', ['$scope', '$statePa }); }; + // Remove existing Article $scope.remove = function(article) { if (article) { article.$remove(); @@ -35,6 +42,7 @@ angular.module('articles').controller('ArticlesController', ['$scope', '$statePa } }; + // Update existing Article $scope.update = function() { var article = $scope.article; @@ -45,10 +53,12 @@ angular.module('articles').controller('ArticlesController', ['$scope', '$statePa }); }; + // Find a list of Articles $scope.find = function() { $scope.articles = Articles.query(); }; + // Find existing Article $scope.findOne = function() { $scope.article = Articles.get({ articleId: $stateParams.articleId diff --git a/modules/articles/server/controllers/articles.server.controller.js b/modules/articles/server/controllers/articles.server.controller.js index a50b1edf75..8f063226f2 100644 --- a/modules/articles/server/controllers/articles.server.controller.js +++ b/modules/articles/server/controllers/articles.server.controller.js @@ -89,10 +89,21 @@ exports.list = function(req, res) { * Article middleware */ exports.articleByID = function(req, res, next, id) { + + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).send({ + message: 'Article is invalid' + }); + } + Article.findById(id).populate('user', 'displayName').exec(function(err, article) { if (err) return next(err); - if (!article) return next(new Error('Failed to load article ' + id)); + if (!article) { + return res.status(404).send({ + message: errorHandler.getErrorMessage(err) + }); + } req.article = article; next(); }); -}; +}; \ No newline at end of file diff --git a/modules/articles/tests/client/articles.client.controller.tests.js b/modules/articles/tests/client/articles.client.controller.tests.js index 326a9b45c8..04c0918437 100644 --- a/modules/articles/tests/client/articles.client.controller.tests.js +++ b/modules/articles/tests/client/articles.client.controller.tests.js @@ -2,7 +2,7 @@ (function() { // Articles Controller Spec - describe('ArticlesController', function() { + describe('Articles Controller Tests', function() { // Initialize global variables var ArticlesController, scope, diff --git a/modules/articles/tests/server/article.server.routes.tests.js b/modules/articles/tests/server/article.server.routes.tests.js index c8c35c8718..de27b640f6 100644 --- a/modules/articles/tests/server/article.server.routes.tests.js +++ b/modules/articles/tests/server/article.server.routes.tests.js @@ -16,8 +16,8 @@ var app, agent, credentials, user, article; /** * Article routes tests */ -describe('Article CRUD tests', function() { - before(function(done) { +describe('Article CRUD tests', function () { + before(function (done) { // Get application app = express.init(mongoose); agent = request.agent(app); @@ -25,7 +25,7 @@ describe('Article CRUD tests', function() { done(); }); - beforeEach(function(done) { + beforeEach(function (done) { // Create user credentials credentials = { username: 'username', @@ -44,7 +44,7 @@ describe('Article CRUD tests', function() { }); // Save a user to the test db and create new article - user.save(function() { + user.save(function () { article = { title: 'Article Title', content: 'Article Content' @@ -54,13 +54,15 @@ describe('Article CRUD tests', function() { }); }); - it('should be able to save an article if logged in', function(done) { + it('should be able to save an article if logged in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) - .end(function(signinErr, signinRes) { + .end(function (signinErr, signinRes) { // Handle signin error - if (signinErr) done(signinErr); + if (signinErr) { + return done(signinErr); + } // Get the userId var userId = user.id; @@ -69,15 +71,19 @@ describe('Article CRUD tests', function() { agent.post('/api/articles') .send(article) .expect(200) - .end(function(articleSaveErr, articleSaveRes) { + .end(function (articleSaveErr, articleSaveRes) { // Handle article save error - if (articleSaveErr) done(articleSaveErr); + if (articleSaveErr) { + return done(articleSaveErr); + } // Get a list of articles agent.get('/api/articles') - .end(function(articlesGetErr, articlesGetRes) { + .end(function (articlesGetErr, articlesGetRes) { // Handle article save error - if (articlesGetErr) done(articlesGetErr); + if (articlesGetErr) { + return done(articlesGetErr); + } // Get articles list var articles = articlesGetRes.body; @@ -93,26 +99,28 @@ describe('Article CRUD tests', function() { }); }); - it('should not be able to save an article if not logged in', function(done) { + it('should not be able to save an article if not logged in', function (done) { agent.post('/api/articles') .send(article) .expect(403) - .end(function(articleSaveErr, articleSaveRes) { + .end(function (articleSaveErr, articleSaveRes) { // Call the assertion callback done(articleSaveErr); }); }); - it('should not be able to save an article if no title is provided', function(done) { + it('should not be able to save an article if no title is provided', function (done) { // Invalidate title field article.title = ''; agent.post('/api/auth/signin') .send(credentials) .expect(200) - .end(function(signinErr, signinRes) { + .end(function (signinErr, signinRes) { // Handle signin error - if (signinErr) done(signinErr); + if (signinErr) { + return done(signinErr); + } // Get the userId var userId = user.id; @@ -121,7 +129,7 @@ describe('Article CRUD tests', function() { agent.post('/api/articles') .send(article) .expect(400) - .end(function(articleSaveErr, articleSaveRes) { + .end(function (articleSaveErr, articleSaveRes) { // Set message assertion (articleSaveRes.body.message).should.match('Title cannot be blank'); @@ -131,13 +139,15 @@ describe('Article CRUD tests', function() { }); }); - it('should be able to update an article if signed in', function(done) { + it('should be able to update an article if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) - .end(function(signinErr, signinRes) { + .end(function (signinErr, signinRes) { // Handle signin error - if (signinErr) done(signinErr); + if (signinErr) { + return done(signinErr); + } // Get the userId var userId = user.id; @@ -146,9 +156,11 @@ describe('Article CRUD tests', function() { agent.post('/api/articles') .send(article) .expect(200) - .end(function(articleSaveErr, articleSaveRes) { + .end(function (articleSaveErr, articleSaveRes) { // Handle article save error - if (articleSaveErr) done(articleSaveErr); + if (articleSaveErr) { + return done(articleSaveErr); + } // Update article title article.title = 'WHY YOU GOTTA BE SO MEAN?'; @@ -157,9 +169,11 @@ describe('Article CRUD tests', function() { agent.put('/api/articles/' + articleSaveRes.body._id) .send(article) .expect(200) - .end(function(articleUpdateErr, articleUpdateRes) { + .end(function (articleUpdateErr, articleUpdateRes) { // Handle article update error - if (articleUpdateErr) done(articleUpdateErr); + if (articleUpdateErr) { + return done(articleUpdateErr); + } // Set assertions (articleUpdateRes.body._id).should.equal(articleSaveRes.body._id); @@ -172,17 +186,17 @@ describe('Article CRUD tests', function() { }); }); - it('should be able to get a list of articles if not signed in', function(done) { + it('should be able to get a list of articles if not signed in', function (done) { // Create new article model instance var articleObj = new Article(article); // Save the article - articleObj.save(function() { + articleObj.save(function () { // Request articles request(app).get('/api/articles') - .end(function(req, res) { + .end(function (req, res) { // Set assertion - res.body.should.be.an.Array.with.lengthOf(1); + res.body.should.be.instanceof(Array).and.have.lengthOf(1); // Call the assertion callback done(); @@ -192,16 +206,16 @@ describe('Article CRUD tests', function() { }); - it('should be able to get a single article if not signed in', function(done) { + it('should be able to get a single article if not signed in', function (done) { // Create new article model instance var articleObj = new Article(article); // Save the article - articleObj.save(function() { + articleObj.save(function () { request(app).get('/api/articles/' + articleObj._id) - .end(function(req, res) { + .end(function (req, res) { // Set assertion - res.body.should.be.an.Object.with.property('title', article.title); + res.body.should.be.instanceof(Object).and.have.property('title', article.title); // Call the assertion callback done(); @@ -209,13 +223,27 @@ describe('Article CRUD tests', function() { }); }); - it('should be able to delete an article if signed in', function(done) { + it('should return proper error for single article which doesnt exist, if not signed in', function (done) { + request(app).get('/api/articles/test') + .end(function (req, res) { + console.log(res.body); + // Set assertion + res.body.should.be.instanceof(Object).and.have.property('message', 'Article is invalid'); + + // Call the assertion callback + done(); + }); + }); + + it('should be able to delete an article if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) - .end(function(signinErr, signinRes) { + .end(function (signinErr, signinRes) { // Handle signin error - if (signinErr) done(signinErr); + if (signinErr) { + return done(signinErr); + } // Get the userId var userId = user.id; @@ -224,17 +252,21 @@ describe('Article CRUD tests', function() { agent.post('/api/articles') .send(article) .expect(200) - .end(function(articleSaveErr, articleSaveRes) { + .end(function (articleSaveErr, articleSaveRes) { // Handle article save error - if (articleSaveErr) done(articleSaveErr); + if (articleSaveErr) { + return done(articleSaveErr); + } // Delete an existing article agent.delete('/api/articles/' + articleSaveRes.body._id) .send(article) .expect(200) - .end(function(articleDeleteErr, articleDeleteRes) { + .end(function (articleDeleteErr, articleDeleteRes) { // Handle article error error - if (articleDeleteErr) done(articleDeleteErr); + if (articleDeleteErr) { + return done(articleDeleteErr); + } // Set assertions (articleDeleteRes.body._id).should.equal(articleSaveRes.body._id); @@ -246,31 +278,31 @@ describe('Article CRUD tests', function() { }); }); - it('should not be able to delete an article if not signed in', function(done) { - // Set article user + it('should not be able to delete an article if not signed in', function (done) { + // Set article user article.user = user; // Create new article model instance var articleObj = new Article(article); // Save the article - articleObj.save(function() { + articleObj.save(function () { // Try deleting article request(app).delete('/api/articles/' + articleObj._id) - .expect(403) - .end(function(articleDeleteErr, articleDeleteRes) { - // Set message assertion - (articleDeleteRes.body.message).should.match('User is not authorized'); + .expect(403) + .end(function (articleDeleteErr, articleDeleteRes) { + // Set message assertion + (articleDeleteRes.body.message).should.match('User is not authorized'); - // Handle article error error - done(articleDeleteErr); - }); + // Handle article error error + done(articleDeleteErr); + }); }); }); - afterEach(function(done) { - User.remove().exec(function() { + afterEach(function (done) { + User.remove().exec(function () { Article.remove().exec(done); }); }); diff --git a/modules/core/client/views/header.client.view.html b/modules/core/client/views/header.client.view.html index 754e9bc241..486b104219 100644 --- a/modules/core/client/views/header.client.view.html +++ b/modules/core/client/views/header.client.view.html @@ -10,11 +10,8 @@