Пример #1
0
module.exports = function () {
  // Initialize the app
  var app = express();

  // Setting application local variables
  app.locals.title = config.app.title;
  app.locals.description = config.app.description;

  // App favicon
  app.use(favicon(path.resolve("./public/favicons/favicon.ico")));

  // Pass url to environment locals
  app.use(function (req, res, next) {
    res.locals.url = req.protocol + "://" + req.headers.host + req.url;
    next();
  });
  app.use(bodyParser.json({limit: "2mb"}));
  app.use(bodyParser.urlencoded({limit: "2mb", extended: true}));

  // Set swig as the template engine
  app.engine("server.view.html", consolidate.swig);

  // view engine setup
  app.set("view engine", "server.view.html");
  app.set("views", "./app/views");

  // Environment dependent middleware
  if (process.env.NODE_ENV === "development") {
    // Enable logger
    app.use(morgan("dev"));

    // Disable views cache
    app.set("view cache", false);
  } else if (process.env.NODE_ENV === "production") {
    app.locals.cache = "memory";
  }

  // Request body parsing middleware
  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(bodyParser.json());

  // CookieParser should be above session
  app.use(cookieParser());

  // Express MySQL session storage
  app.use(session({
    secret: config.sessionSecret,
    store: new SessionStore(config.database.connection),
    resave: true,
    saveUninitialized: true
  }));

  // Setup flash messages
  app.use(require("connect-flash")());
  app.use(function (req, res, next) {
    res.locals.messages = require("express-messages")(req, res);
    next();
  });

  // Use passport session
  passport.serializeUser(passportSetup.serializeUser);
  passport.deserializeUser(passportSetup.deserializeUser);
  passport.use(new LocalStrategy(
    {usernameField: "username", passwordField: "password"},
    passportSetup.strategy)
  );
  app.use(passport.initialize());
  app.use(passport.session());

  // Use helmet to secure Express headers
  app.use(helmet.xframe());
  app.use(helmet.xssFilter());
  app.use(helmet.nosniff());
  app.use(helmet.ienoopen());
  app.disable("x-powered-by");

  // Static folder
  app.use(express.static(path.resolve("./public")));

  // Routing files
  require("../app/routes/index.server.routes")(app);

  app.use(function (err, req, res, next) {
    if (!err) { return next(); }

    console.error(err.stack);

    res.status(500).render("500", {
      error: err.stack
    });
  });

  // Assume 404 since no middleware responded
  app.use(function(req, res) {
    res.status(404).render("404", {
      url: req.originalUrl,
      error: "Not Found"
    });
  });

  if (process.env.NODE_ENV === "secure") {
    // Log SSL usage
    console.log("Securely using https protocol");

    // Load SSL key and certificate
    var privateKey = fs.readFileSync("./config/ssl_certs/key.pem", "utf8");
    var certificate = fs.readFileSync("./config/ssl_certs/cert.pem", "utf8");

    // Create HTTPS Server
    var httpsServer = https.createServer({
      key: privateKey,
      cert: certificate
    }, app);

    // Return HTTPS server instance
    return httpsServer;
  }

  return http.createServer(app);
};
Пример #2
0
module.exports = function (db) {
    var app = express();

    //Get all the model files
    config.getGlobbedFiles('./app/models/**/*.js').forEach(function (model) {
       require(path.resolve(model));
    });

    app.use(compress({
        filter: function (req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        level: 9
    }));

    app.set('showStackError', true);

    console.log(path.resolve('./app/views/', 'layouts'));
    console.log(process.cwd() + '/app/views/layouts');
    var hbsConfig = {
        defaultLayout: 'main',
        layoutsDir: './app/views/layouts'
    };


    app.engine('handlebars', exphbs(hbsConfig));
    app.set('view engine', 'handlebars');

    app.set('views', './app/views');


    if (process.env.NODE_ENV === 'development') {
        app.use(logger('dev'));
        app.set('view cache', false);
    } else if (process.env.NODE_ENV === 'production') {
        app.locals.cache = 'memory';
    }

    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());
    app.use(methodOverride());

    app.enable('jsonp callback');

    app.use(cookieParser());

    app.use(session({
        saveUnitialized: true,
        resave: true,
        secret: config.sessionSecret,
        store: new mongoStore({
            db: db.connection.db,
            collection: config.sessionCollection
        })
    }));

    // use passport session
    app.use(passport.initialize());
    app.use(passport.session());

    // connect flash for flash messages
    app.use(flash());

    // Use helmet to secure Express headers
    app.use(helmet.xframe());
    app.use(helmet.xssFilter());
    app.use(helmet.nosniff());
    app.use(helmet.ienoopen());
    app.disable('x-powered-by');

    // Setting the app router and static folder
    app.use(express.static(path.resolve('./public')));

    // Globbing routing files
    config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
        require(path.resolve(routePath))(app);
    });

    // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
    app.use(function(err, req, res, next) {
        // If the error object doesn't exists
        if (!err) return next();

        // Log it
        console.error(err.stack);

        // Error page
        res.status(500).render('500', {
            error: err.stack
        });
    });

    // Assume 404 since no middleware responded
    app.use(function(req, res) {
        res.status(404).render('404', {
            url: req.originalUrl,
            error: 'Not Found'
        });
    });

    return app;
};
Пример #3
0
module.exports = function (db) {

  // Initialize express app
  var app = express();

  // Setting application local variables
  // app.locals.config = config;
  app.locals.title = config.app.title;
  app.locals.description = config.app.description;
  app.locals.keywords = config.app.keywords;
  app.locals.url = config.app.url;
  app.locals.ROUTES = ROUTES;

  // Initialize models
  require('./../models/user.js');


  // Should be placed before express.static
  app.use(compress({
    filter: function (req, res) {
      return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
    },
    level: 9
  }));

  // Showing stack errors
  app.set('showStackError', true);

  // Set swig as the template engine
  require('./swig')(swig, app);
  // app.engine('html', swig.renderFile);
  app.engine('html', consolidate.swig);

  // Set views path and view engine
  app.set('view engine', 'html');
  app.set('views', './app/views');

  // Enable logger (morgan)
  if (process.env.NODE_ENV == 'development')
    app.use(morgan('dev'));

  // Environment dependent middleware
  if (process.env.NODE_ENV == 'development') {
    app.set('view cache', false); // Disable views cache
  } else if (process.env.NODE_ENV == 'production') {
    app.locals.cache = 'memory';
  }

  // Request body parsing middleware should be above methodOverride
  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(bodyParser.json());
  app.use(methodOverride());

  // CookieParser should be above session
  app.use(cookieParser());

  // Express MongoDB session storage
  app.use(session({
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret,
    store: new mongoStore({
      db: db.connection.db,
      collection: config.sessionCollection
    }),
    cookie: config.sessionCookie,
    name: config.sessionName
  }));

  // use passport session
  require('./passport')(passport);
  app.use(passport.initialize());
  app.use(passport.session());

  // connect flash for flash messages
  app.use(flash());
  app.use(function (req, res, next) {
    var render = res.render;
    res.render = function () {
      res.locals.messages = req.flash();
      render.apply(res, arguments);
    }
    var json = res.json;
    res.json = function () {
      res.locals.messages = req.flash();
      json.apply(res, arguments);
    }
    next();
  });

  // Passing user to environment locals
  app.use(function (req, res, next) {
    res.locals.user = req.isAuthenticated() ? req.user : null;
    next();
  });

  // Use helmet to secure Express headers
  app.use(helmet.xframe());
  app.use(helmet.xssFilter());
  app.use(helmet.nosniff());
  app.use(helmet.ienoopen());
  app.disable('x-powered-by');

  // Setting the app router and static folder
  // app.use(favicon(path.resolve('./public/favicon.ico')));
  app.use(express.static(path.resolve('./public')));

  app.use(require('prerender-node'));

  // Load routes
  app.use('/auth', require('./../routes/auth'));

  // var auth = require('./../middlewares/auth');

  // app.get('/', auth.authenticatedAccessMiddleware, function (req, res, next) {
  //   res.render('index.html');
  // });

  app.get('/', function (req, res, next) {
    res.redirect('/auth');
  });

  /*
   * Unauthorized access handler
   */
  app.use(function (err, req, res, next) {
    if (err.status !== 401)
      return next(err);
    if (req.xhr)
      res.json(401, {
        success: false,
        message: "Unauthorized Access"
      });
    else
      res.redirect(ROUTES.AUTH_LOGIN);
  });

  /*
   * development error handler
   * will print stacktrace
   */
  if (process.env.NODE_ENV == 'development')
    app.use(function (err, req, res, next) {
      console.error(err.stack);
      res.status(err.status || 500);
      if (req.xhr)
        res.json({
          success: false,
          message: err.message,
          error: err
        });
      else
        res.render('error', {
          message: err.message,
          error: err
        });
    });

  /*
   * production error handler
   * no stacktraces leaked to user
   */
  app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    if (req.xhr)
      res.json({
        success: false,
        message: err.message
      });
    else
      res.render('error', {
        message: err.message
      });
  });

  // Assume 404 since no middleware responded
  if (process.env.NODE_ENV != 'development')
    app.use(function (req, res) {
      if (req.xhr)
        res.json({
          url: req.originalUrl,
          error: 'Not Found'
        });
      res.status(404).render('404', {
        url: req.originalUrl,
        error: 'Not Found'
      });
    });

  console.log('LOCALS', app.locals);
  // console.log('ROUTES', app._router.stack);

  return app;
};
Пример #4
0
    auth0Api = require('./app/routes/auth0.api.routes'),
    electricImp = require('./app/routes/electricimp.routes'),
    authentication = require('./app/routes/authentication.auth0.routes'),
    installationsAPI = require('./app/routes/installations.routes'),
    requester = require('./app/routes/request.routes'),
    route = require('./app/routes/route'),
    runOptions = require('./app/options');

var app = express(),
    port = config.port || 8080;

// Use helmet to secure Express headers
app.use(helmet.xframe());
app.use(helmet.iexss());
app.use(helmet.contentTypeOptions());
app.use(helmet.ienoopen());
app.disable('x-powered-by');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));


app.all('*', function (req, res, next) {

    if (req.headers.realm !== undefined) {
        runOptions.set({realm: req.headers.realm});
    } else {
        runOptions.set({realm: 'local'});
    }
    next();
Пример #5
0
module.exports = function() {
  // Initialize express app
  var app = express();

  // Globbing model files
  config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
    require(path.resolve(modelPath));
  });

  // compression
  app.use(compress({
    filter: function(req, res) {
      return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
    },
    level: 9
  }));

  // Showing stack errors
  app.enable('showStackError');

  // Env dependent middleware
  if (process.env.NODE_ENV === 'development') {
    // Enable logger
    app.use(morgan('dev'));
  }
  else if (process.env.NODE_ENV === 'production') {
    app.locals.cache = 'memory';
  }

  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(bodyParser.json());
  app.use(methodOverride());

  // Enable jsonp
  app.enable('jsonp callback');

  // Passport
  app.use(passport.initialize());

  // Helmet
  app.use(helmet.xframe());
  app.use(helmet.xssFilter());
  app.use(helmet.nosniff());
  app.use(helmet.ienoopen());
  app.disable('x-powered-by');

  // Routing
  config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
    require(path.resolve(routePath))(app);
  });

  // Error handling
  app.use(function(err, req, res, next) {
    if (!err) return next();
    console.error(err.stack);
    res.send(500);
  });
  app.use(function(req, res) {
    res.send(404);
  });

  return app;
};
Пример #6
0
module.exports = function(db) {
	// Initialize express app
	var app = express();

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.siteName = config.app.siteName;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();
	app.locals.gaID = config.gaID;

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}
	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true,
		limit: config.contentLimit
	}));
	app.use(bodyParser.json({limit: config.contentLimit}));
	app.use(methodOverride());

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		saveUninitialized: true,
		resave: true,
		secret: config.sessionSecret,
		store: new mongoStore({
			db: db.connection.db,
			collection: config.sessionCollection
		})
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(function (req, res, next) {
		passport.authenticate('token', function (err, user, info) {
			if (err) return next(err);
			if (info && info.has_token) {
				req.has_token = true;
				return next();
			}
			if (!user) return next();

			req.login(user, { session: false }, function (err) {
				if (err) return next(err);
				else return next();
			});

		})(req, res, next);
	});

	// connect flash for flash messages
	app.use(flash());
	//MEAN-SEO prerender pages for search engines
	app.use(seo({
		cacheClient: 'disk', // Can be 'disk' or 'redis'
		cacheDuration: 2 * 60 * 60 * 24 * 1000 // In milliseconds for disk cache
	}));
	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	app.use(function (req, res, next) {
		if (req.user || req.has_token) {
			next();
		} else if (checkPath(req)) {
			next();
		} else {
			res.sendStatus(401).end();
		}
	});
	//Check path for secure protection
	function checkPath (req) {
		var allowPaths = [    //@TODO: move to config
			'/',
			'/api/auth/signin',
			'/auth/facebook',
			'/auth/twitter',
			'/auth/google',
			'/auth/facebook/callback',
			'/auth/twitter/callback',
			'/auth/google/callback',
			'/newTwitterUser'
			];
		return _.some(allowPaths, function(path){
			return req.path === path;
		});
	}
	policy.init(app, db);

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});

	if (process.env.NODE_ENV === 'secure') {
		// Log SSL usage
		console.log('Securely using https protocol');

		// Load SSL key and certificate
		var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8');
		var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8');

		// Create HTTPS Server
		var httpsServer = https.createServer({
			key: privateKey,
			cert: certificate
		}, app);

		// Return HTTPS server instance
		return httpsServer;
	}

	// Return Express server instance
	return app;
};
Пример #7
0
module.exports = function(db) {
	// Initialize express app
	var app = express();

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	//handling multi/form-data
	app.use(multer({
	  dest: './public/uploads/',
	  rename: function (fieldname, filename) {
	    return filename.replace(/\W+/g, '-').toLowerCase() +'_'+Date.now();
	  }
	}));

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(methodOverride());

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		saveUninitialized: true,
		resave: true,
		secret: config.sessionSecret,
  		cookie: { maxAge: 60000 * 15 * 5},
		store: new mongoStore({
			db: db.connection.db,
			collection: config.sessionCollection,
			ttl: 15 * 60 * 60 
		})
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session());

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});

	if (process.env.NODE_ENV === 'secure') {
		// Log SSL usage
		console.log('Securely using https protocol');

		// Load SSL key and certificate
		var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8');
		var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8');

		// Create HTTPS Server
		var httpsServer = https.createServer({
			key: privateKey,
			cert: certificate
		}, app);

		// Return HTTPS server instance
		return httpsServer;
	}

	// Return Express server instance
	return app;
};
Пример #8
0
 app.configure(function(){
   app.engine('html', require('ejs').renderFile);
   app.set('view engine', 'html');
   app.use(express.logger('dev'));
   app.use(express.compress());
   app.use(express.methodOverride());
   app.use(express.urlencoded());
   app.use(express.json());
   app.set('uploadDir', path.join(config.root, 'uploads'));
   app.set('uploadRelative', 'uploads');
   app.use(function (req, res, next) {
     req.uploadDir = app.get('uploadDir');
     req.uploadRelative = app.get('uploadRelative');
     next();
   });
   app.use(express.bodyParser({ keepExtensions: true, uploadDir: app.get('uploadDir') }));
   app.use(express.cookieParser(settings.cookie.secret));
   // Used instead of app.use(express.cookieSession());
   app.use(express.session({
     store: new RedisStore({
       host: settings.redis.ip,
       port: settings.redis.port
     }),
     proxy: true, // Trust the reverse proxy when setting secure cookies
     cookie: {
       secure: false, // Important! Otherwise you'll get Forbidden 403
       maxAge: cacheMaxAge, // 1 week
       httpOnly: false // Disabling allows us to see the cookie in Angular
     }
   }));
   app.use(helmet.csp({
     'default-src': ["'self'"],
     'script-src': scriptSrc,
     'style-src': ["'self'", "'unsafe-inline'"],
     'img-src': ["'self'", "data:", "http://placehold.it"],
     'connect-src': connectSrc,
     'font-src': ["'self'"],
     'object-src': ["'self'"],
     'media-src': ["'self'"],
     'frame-src': ["'self'"],
     reportOnly: false, // set to true if you only want to report errors
     setAllHeaders: false, // set to true if you want to set all headers
     safari5: false // set to true if you want to force buggy CSP in Safari 5
   }));
   // This middleware adds the Strict-Transport-Security header to the response.
   // To use the default header of Strict-Transport-Security: maxAge=15768000 (about 6 months)
   app.use(helmet.hsts());
   // `X-Frame` specifies whether your app can be put in a frame or iframe.
   app.use(helmet.xframe('deny'));
   // The X-XSS-Protection header is a basic protection against XSS.
   app.use(helmet.iexss());
   // Sets the `X-Download-Options` header to noopen to prevent IE users from executing downloads in your site's context.
   app.use(helmet.ienoopen());
   // The following sets the `X-Content-Type-Options` header to its only and default option, nosniff.
   app.use(helmet.contentTypeOptions());
   // This middleware will remove the `X-Powered-By` header if it is set.
   app.use(helmet.hidePoweredBy());
   app.use(function (req, res, next) {
     // POSTS send an OPTIONS request first so let's make sure we handle those
     res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
     res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
     next();
   });
   // Router needs to be last
   app.use(app.router);
 });
Пример #9
0
module.exports = function() {
	// Initialize express app
	var app = express();

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded());
	app.use(bodyParser.json());
	app.use(methodOverride());

	// Enable jsonp
	app.enable('jsonp callback');

	// CookieParser should be above session
	app.use(cookieParser());

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.iexss());
	app.use(helmet.contentTypeOptions());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Continue along unless there is a 500
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.send(500, {
			message: err.message
		});	
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found',
			user: req.user || null
		});
	});

	return app;
};
Пример #10
0
module.exports = function(db) {
  // Initialize express app
  var app = express();

  app.post('/api/v1/upload/image', function(req, res) {
    
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {  
      
    var obj = JSON.parse(fields.sizes);
      
      
      var medium = JSON.parse(fields.medium);
      var thumbnail = JSON.parse(fields.thumbnail);
               
      var file = files.file[0];
      var contentType = file.headers['content-type'];
      var extension = file.path.substring(file.path.lastIndexOf('.'));
      //var destPath = '/nicklewis/profile' + '/' + uuid.v4() + extension;      
      
      // TODO: Pass in the username from the front-end and store it in this variable
      var userName = '******';
      
      
      // console.log(fields.s3bucket);
      // TODO: Thinking of storing this in a config file or passing it in from client???
      var bucketName = 'nfolio-images';
      
      // TODO: Imagefile, Avatar and so on
      // var type = obj.type;
      
      // TODO: Merge fullpath and keyname variables together for cleaner code?
      // TODO: Need to introduce another directory level for different image sizes
      // TODO: Original image is passed to server by client and this function creates variants
      // TODO: Thumb, medium, original - what other sizes are likely to be needed??
      var keyName = userName + '/' + uuid.v4() + '/' + file.originalFilename;
      var fullPath = bucketName + '/' + keyName;
      
      // TODO: I would prefere that this was a similar name to that of the main image
      // TODO: Must delete these temporary files as soon as they are uploaded
      var tmpFile = 'tmp/images/' + uuid.v4();
      
      resize(file,tmpFile,fullPath,bucketName,keyName,800,800);
      
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ fileName: fullPath }, null, 3));                     
    });
  });

  function resize(file,tmpFile,fullPath,bucketName,keyName,width,height) {
    // STEP 1 - RESIZE
      // TODO: Would it be better to pass in sizes from client??            
      im.resize({
        srcPath: file.path,
        dstPath: tmpFile,
        width: width,
        height: height
      }, function(err, stdout, stderr){
        if (err) {
          // It is possible that the resize may fail, perhaps lack of memory or some other reason?
          // TODO: What should we do if the resize fails? Just pass a message back to the client???
          console.log('error while resizing images' + stderr);
        } else {
          // STEP 2 - UPLOAD TO S3
          // I moved this within this callback, so that we know the file has been resized and output file EXISTS!
          console.log('Image resized successfully: ' + tmpFile);
          sendToS3(tmpFile,fullPath,bucketName,keyName);
                  
          
        }
      });
  }
  
  function sendToS3(tmpFile,fullPath,bucketName,keyName) {
    // Loads the credentials from a file on the server (more secure)
      AWS.config.loadFromPath('./config/config.json');
      
      var s3 = new AWS.S3();
    console.log(tmpFile);
    var rs = fs.createReadStream(tmpFile);
    var params = {Bucket: bucketName, Key: keyName, Body: rs};
    s3.putObject(params, function(err, data) {
      if (err) {
        // TODO: Take action if this fails but in what way?
        // TODO: Send a fail back to the client which should then message the user accordingly
        console.log(err);
      } else {
        // Success return the filename generated for this upload
        console.log('Successfully uploaded data to ' + fullPath);
      }
    });
  }
  
	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + ':// ' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded());
	app.use(bodyParser.json());
	app.use(methodOverride());

	// Enable jsonp
	app.enable('jsonp callback');

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		secret: config.sessionSecret,
		store: new mongoStore({
			db: db.connection.db,
			collection: config.sessionCollection
		})
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session());

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.iexss());
	app.use(helmet.contentTypeOptions());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});

	return app;
};
Пример #11
0
// Easy form validation!
app.use(expressValidator());

// If you want to simulate DELETE and PUT
// in your app you need methodOverride.
app.use(methodOverride());

// Use sessions
// NOTE: cookie-parser not needed with express-session > v1.5
app.use(session(config.session));

// Security Settings
app.disable('x-powered-by');          // Don't advertise our server type
app.use(csrf());                      // Prevent Cross-Site Request Forgery
app.use(helmet.nosniff());            // Sets X-Content-Type-Options to nosniff
app.use(helmet.ienoopen());           // X-Download-Options for IE8+
app.use(helmet.xssFilter());          // sets the X-XSS-Protection header
app.use(helmet.xframe('deny'));       // Prevent iframe
app.use(helmet.crossdomain());        // crossdomain.xml

// Content Security Policy:
//   http://content-security-policy.com/
//   http://www.html5rocks.com/en/tutorials/security/content-security-policy/
//   http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
//
//   NOTE: TURN THIS OFF DURING DEVELOPMENT
//   IT'S JUST PAINFUL OTHERWISE! OR DON'T
//   EVEN USE IT AT ALL - I JUST WANTED TO
//   LEARN HOW IT WORKS. :)

app.use(helmet.csp({
Пример #12
0
module.exports = function(db) {
	// Initialize express app
	var app = express();
	var OAuth2 = require('oauth').OAuth2;
	var https = require('https');
	
  app.get('/public/Indexpage.jpg', function(req, res) {
    var img = fs.readFileSync('./public/Indexpage.jpg');
    res.writeHead(200, {'Content-Type': 'image/gif' });
    res.end(img, 'binary');
  });
  app.get('/public/lib/hello/dist/hello.all.min.js', function(req, res) {
    var img = fs.readFileSync('./public/lib/hello/dist/hello.all.min.js');
    res.writeHead(200, {'Content-Type': 'text/javascript' });
    res.end(img, 'binary');
  });

  app.get('/places', function(req, res) {
    var uri = '/maps/api/place/textsearch/json?query=' + req.query.query;
    if (req.query.language !== undefined) {
      uri = uri + '&language=' + req.query.language;
    }
    uri = uri + '&key=AIzaSyBXXWUbms4wO48NHxmFUPmVE0AlrY0ztZ8';
    var options = {
      hostname: 'maps.googleapis.com',
      path: encodeURI(uri),
    };

    https.get(options, function(result) {
      var buffer = '';
      result.setEncoding('utf8');
      result.on('data', function (data) {
        buffer += data;
      });
      result.on('end', function() {
        var tweets = JSON.parse(buffer);
        res.send(tweets);
      });
    });
  });

/*
  app.get('/placeId', function(req, res) {
    var uri = '/maps/api/place/details/json?placeid=' + req.query.placeId;
    uri = uri + '&key=AIzaSyBXXWUbms4wO48NHxmFUPmVE0AlrY0ztZ8';
    var options = {
      hostname: 'maps.googleapis.com',
      path: encodeURI(uri),
    };

    console.log(uri);
    console.log('!!!!!!!!!!!!!!');
    https.get(options, function(result) {
      var buffer = '';
      result.setEncoding('utf8');
      result.on('data', function(data) {
        buffer += data;
      });
      result.on('end', function() {
        var tweets = JSON.parse(buffer);
        res.send(tweets); 
      });
    });
  });

*/
	app.get('/tweets', function(req, res) {

var oauth2 = new OAuth2('uRpaaKqj9e4ombt4ZniARqKHW', 'Y8T9NnZrpl0P2lHXLatB7DblSq7nKVtTgrBYnJOdtU9frl2AeD', 'https://api.twitter.com/', null, 'oauth2/token', null);
oauth2.getOAuthAccessToken('', {
    'grant_type': 'client_credentials'
}, function (e, access_token) {
    console.log(access_token); //string that we can use to authenticate request
    
    var query = req.query;

    var options = {
        hostname: 'api.twitter.com',
        path: encodeURI('/1.1/search/tweets.json?q=' + query.q + '&geocode=' + query.geocode + 'km' + '&result_type=recent&count=100'),
        headers: {
            Authorization: 'Bearer ' + access_token
        }
    };

    console.log('AUTHED');

    https.get(options, function (result) {
        var buffer = '';
        result.setEncoding('utf8');
        result.on('data', function (data) {
            buffer += data;
        });
        result.on('end', function () {
            var tweets = JSON.parse(buffer);
        res.send(tweets);
        });
    });
});
	});

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();
	app.locals.secure = config.secure;

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	// Setting the app router and static folder
	app.use(express.static(__dirname + '/public'));

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(methodOverride());

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		saveUninitialized: true,
		resave: true,
		secret: config.sessionSecret,
		store: new mongoStore({
			db: db.connection.db,
			collection: config.sessionCollection
		})
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session());

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});

	if (app.locals.secure) {
		console.log('Securely using https protocol');
		var https = require('https'),
		privateKey  = fs.readFileSync('./config/sslcert/key.pem', 'utf8'),
		certificate = fs.readFileSync('./config/sslcert/cert.pem', 'utf8'),
		credentials = {key: privateKey, cert: certificate},
		httpsServer = https.createServer(credentials, app);
		return httpsServer;
	} else {
		console.log('Insecurely using http protocol');
		var httpServer = http.createServer(app);
		return httpServer;
	}
};
Пример #13
0
module.exports = function() {
	// Quando chamado retorna uma instancia do modulo armazenado.
	var app = express();

	// Define variavel de ambiente (chave, valor).
	app.set('port', config.port);

	// Configuracao do template.

	// Define o 'ejs' como template utilizado.
	app.set('view engine', 'ejs');
	// Define o diretorio que contera as views.
	app.set('views', './app/views');

	// Middlewares.
	app.use(express.static('./public'));

	// Middlewares 'body-parser' e 'method-override'.
	app.use(bodyParser.urlencoded({extended: true}));
	app.use(bodyParser.json());
	app.use(require('method-override')());

	app.use(cookieParser());
	app.use(session({
		secret: 'Jessi',
		resave: true,
		saveUninitialized: true
	}));
	app.use(passport.initialize());
	app.use(passport.session());

	// app.use(helmet());

	app.use(helmet.xframe());

	app.use(helmet.xssFilter());

	app.use(helmet.nosniff());

	app.use(helmet.ienoopen());

	app.disable('x-powered-by');
	// ou.
	// app.use(helmet.hidePoweredBy({ setTo: 'PHP 5.5.14' }));

	// Inicia o modulo com as rotas (DEPRECATED - Agora usando 'express-load').
	// home(app);

	// O load() carrega todos os scripts dentro de 'app/models', 'app/controllers' e 'app/routes' seguindo a ordem correta 'model -> controller -> route'.
	// O 'cwd' foi necessario pois por padrao os diretorios sao procurados na raiz.
	load('models', {cwd: 'app'})
		.then('controllers')
		.then('routes/auth.js')
		.then('routes')
		.into(app);

	// Se nenhum rota atender, direciona para página 404.
	app.get('*', function(req, res) {
		res.status(404).render('404');
	});

	return app;
};
Пример #14
0
module.exports = function(db) {
	// Initialize express app
	var app = express();

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.google_analytics_id = config.app.google_analytics_id;
	app.locals.title = config.app.title;
	app.locals.signupDisabled = config.signupDisabled;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.socketPort = config.socketPort;

	app.locals.bowerJSFiles = config.getBowerJSAssets();
	app.locals.bowerCssFiles = config.getBowerCSSAssets();
	app.locals.bowerOtherFiles = config.getBowerOtherAssets();

	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

    //Setup Prerender.io
    app.use(require('prerender-node').set('prerenderToken', process.env.PRERENDER_TOKEN));

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		if(config.baseUrl === ''){
			config.baseUrl = req.protocol + '://' + req.headers.host;
		}
	    res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compression({
		// only compress files for the following content types
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		// zlib option for compression level
		level: 3
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Enable logger (morgan)
	app.use(morgan(logger.getLogFormat(), logger.getLogOptions()));

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(methodOverride());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');


	// Setting the app router and static folder
	app.use('/', express.static(path.resolve('./public')));
	app.use('/uploads', express.static(path.resolve('./uploads')));

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage

	app.use(session({
		saveUninitialized: true,
		resave: true,
		secret: config.sessionSecret,
		store: new MongoStore({
	      mongooseConnection: db.connection,
	      collection: config.sessionCollection
	    }),
		cookie: config.sessionCookie,
		name: config.sessionName
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session());

	// setup express-device
	app.use(device.capture({ parseUserAgent: true }));

	// connect flash for flash messages
	app.use(flash());

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});


	// Add headers for Sentry

	app.use(function (req, res, next) {

	    // Website you wish to allow to connect
	    res.setHeader('Access-Control-Allow-Origin', 'https://sentry.polydaic.com');

	    // Request methods you wish to allow
	    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

	    // Request headers you wish to allow
	    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

	    // Set to true if you need the website to include cookies in the requests sent
	    // to the API (e.g. in case you use sessions)
	    res.setHeader('Access-Control-Allow-Credentials', true);

	    // Pass to next layer of middleware
	    next();
	});

	// Sentry (Raven) middleware
	// app.use(raven.middleware.express.requestHandler(config.DSN));

	// Should come before any other error middleware
	// app.use(raven.middleware.express.errorHandler(config.DSN));

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);
		client.captureError(err);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		client.captureError(new Error('Page Not Found'));
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});

	if (process.env.NODE_ENV === 'secure') {
		// Load SSL key and certificate
		var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8');
		var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8');

		// Create HTTPS Server
		var httpsServer = https.createServer({
			key: privateKey,
			cert: certificate
		}, app);

		// Return HTTPS server instance
		return httpsServer;
	}

	app = configureSocketIO(app, db);

	// Return Express server instance
	return app;
};
Пример #15
0
module.exports = function(db) {
    // Initialise express app
    var app = express();

    // Globbing model files
    config.getGlobbedFiles('./app/components/**/*.server.model.js').forEach(function(modelPath) {
        require(path.resolve(modelPath));
    });

    // Setting application local variables
    app.locals.title = config.app.title;
    app.locals.description = config.app.description;
    app.locals.keywords = config.app.keywords;
    app.locals.jsFiles = config.getJavascriptAssets();
    app.locals.cssFiles = config.getCSSAssets();

    app.use(compress({
        filter: function(req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        level: 9
    }));

    app.set('showStackError', true);

    app.engine('server.view.html', consolidate[config.templateEngine]);

    app.set('view engine', 'server.view.html');
    // set the default views location
    // todo: would like this to support multiple view locations so they can exist specific component folders
    app.set('views', './app/components/views');

    // Environment dependant middleware
    if (process.env.NODE_ENV === 'development') {
        // Enable logger
        app.use(morgan('dev'));
        // Disable views cache
        app.set('view cache', false);
    } else if (process.env.NODE_ENV === 'production') {
        app.locals.cache = 'memory';
    }

    // Request body parsing middleware
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());
    app.use(methodOverride());

    // Enable jsonp
    app.enable('jsonp callback');

    app.use(cookieParser());

    // Express MongoDB session storage
    app.use(session({
        saveUninitialized: true,
        resave: true,
        secret: config.sessionSecret,
        store: new mongoStore({
            db: db.connection.db,
            collection: config.sessionCollection
        })
    }));

    // Connect flash for flash messages
    app.use(flash());

    // Use helmet to secure Express headers
    app.use(helmet.xframe());
    app.use(helmet.xssFilter());
    app.use(helmet.nosniff());
    app.use(helmet.ienoopen());
    app.disable('x-powered-by');

    // Set static folder
    app.use(express.static(path.resolve('./public')));

    // Globbing routing files
    config.getGlobbedFiles('./app/components/**/*.server.routes.js').forEach(function(routePath) {
        require(path.resolve(routePath))(app);
    });

    // Assume 'not found' in the error msgs is a 404
    app.use(function(err, req, res, next) {
        if (!err) {
            return next();
        }

        res.status(500).render('500', {
            error: err.stack
        });
    });

    // Assume 404 since no middleware responded
    app.use(function(req, res) {
        res.status(404).render('404', {
            url: req.originalUrl,
            error: 'Not found'
        });
    });

    return app;
};
Пример #16
0
module.exports = function(db) {
	// Initialize express app
	var app = express();

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(methodOverride());

	// Enable jsonp
	app.enable('jsonp callback');

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		saveUninitialized: true,
		resave: true,
		secret: config.sessionSecret,
		store: new mongoStore({
			db: db.connection.db,
			collection: config.sessionCollection
		})
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session());

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});
	
	// Attach Socket.io
	
	var server = http.createServer(app);
	app.set('server', server);
	var io = socketio.listen(server);
	app.set('socketio', io);
	
	io.sockets.on('connection', socket);
	
	return app;
};
Пример #17
0
module.exports = function(db) {
	// Initialize express app
	var app = express();

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables from loaded config.js file, which has got variables from 
        // env/all.js
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets(); // get all public/lib/ public/modules/ js files
	app.locals.cssFiles = config.getCSSAssets(); // get all public/lib/ public/modules/ css files

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
        // i think it should not be seen in case of production
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(methodOverride());

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		saveUninitialized: true,
		resave: true,
		secret: config.sessionSecret, // env/all.js contains sessionSecret
		store: new mongoStore({
			db: db.connection.db,  // development.js/production.js/test.js has db field which gets in config.js
                        // i think db.connection.db value is not present, don't know how it will work
			collection: config.sessionCollection
		})
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session()); // persistent login sessions

	// // use connect-flash for flash messages stored in session
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files,
        // here we are auto loading the server route files
        // i think, these route files use controllers, which load views, views use models for data
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', { 
                    // don't know why they haven't used full name 500.server.view.html, how using '500' only works
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});

	return app;
};