Example #1
0
function startServer(options, callback) {
  var app = express();
  app.use(express.cookieParser("secret cat"));
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(multipart());
  app.use(express.static(__dirname, {'index': ['index.html', 'index.htm']}));
  app.engine("vm", expVM({extname: ".vm"}));
  app.set("views", path.join(__dirname, "../../mocks/views"));
  app.set("view engine", "vm");
  app.use(function (req, res, next) {
    var headers = {};
    if(req.method.toUpperCase() === "OPTIONS") {
      headers["Access-Control-Allow-Origin"] = "*";
      headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
      headers["Access-Control-Allow-Credentials"] = true;
      headers["Access-Control-Max-Age"] = '86400'; // 24 hours
      headers["Access-Control-Allow-Headers"] = "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept";
    } else {
      headers["Access-Control-Allow-Origin"] = "*";
    }
    Object.keys(headers).forEach(function (k) {
      res.setHeader(k, headers[k]);
    });
    res.cookie("mock", "1", {httpOnly: true, maxAge: 900000});
    return next();
  });
  options.files.forEach(function (endpoint) {
    var fp = path.join(process.cwd(), endpoint),
        layer;
        
    if(fs.statSync(fp).isFile()) {
      delete require.cache[fp];
      layer = require(fp);
      if(layer.mock) {
        layer.mock(app);
      }
    }
  });
  app.server = app.listen(options.port, callback);
  return app;
}
module.exports = function(app) {
	var users = require('../../app/controllers/users');
	var tools = require('../../app/controllers/tools');
	var multiparty = require('connect-multiparty'),
	multipartyMiddleware = multiparty();

	// Tools Routes
	app.route('/tools');

	// custom tools routes
	app.route('/tools/sendtalentemails')
		.post(users.requiresLogin, tools.sendTalentEmails);

	app.route('/tools/sendPreCloseSummary')
		.get(tools.sendPreCloseSummary);

	// call list routes
	app.route('/tools/gatherTalentsToCall')
		.post(users.requiresLogin, tools.gatherTalentsToCall);

	app.route('/tools/gatherTalentsMessagesLeft')
		.post(users.requiresLogin, tools.gatherTalentsMessagesLeft);

	app.route('/tools/gatherTalentsAlreadyScheduled')
		.post(users.requiresLogin, tools.gatherTalentsAlreadyScheduled);

	app.route('/tools/gatherEmailedTalent')
		.post(users.requiresLogin, tools.gatherEmailedTalent);

	app.route('/tools/uploadTalentCSV')
		.post(users.requiresLogin, multipartyMiddleware, tools.uploadTalentCSV);

	app.route('/tools/processGoogleSheet')
		.post(users.requiresLogin, tools.processGoogleSheet);

	// added to display new project form submissions
	app.route('/tools/listNewprojects')
		.post(users.requiresLogin, tools.listNewprojects);
	app.route('/tools/newprojectByID')
		.post(users.requiresLogin, tools.newprojectByID);

};
Example #3
0
app.configure(function() {

    // set up our express application
    app.use(express.logger('dev')); // log every request to the console
    app.use(express.cookieParser()); // read cookies (needed for auth)
    app.use(express.json());
    app.use(express.urlencoded());
    app.set('view engine', 'ejs'); // set up ejs for templating

    app.use(express.static(__dirname + '/views'));

    app.use(multipart()) //Express 4

    // required for passport
    app.use(express.session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions
    app.use(flash()); // use connect-flash for flash messages stored in session

});
Example #4
0
module.exports =  function(app, middleware, controllers) {

	var router = express.Router();
	app.use('/api', router);

	router.get('/config', middleware.applyCSRF, controllers.api.getConfig);
	router.get('/widgets/render', controllers.api.renderWidgets);

	router.get('/user/uid/:uid', middleware.checkGlobalPrivacySettings, controllers.accounts.getUserByUID);
	router.get('/get_templates_listing', getTemplatesListing);
	router.get('/categories/:cid/moderators', getModerators);
	router.get('/recent/posts/:term?', getRecentPosts);

	var multipart = require('connect-multiparty');
	var multipartMiddleware = multipart();
	var middlewares = [multipartMiddleware, middleware.validateFiles, middleware.applyCSRF];
	router.post('/post/upload', middlewares, uploadsController.uploadPost);
	router.post('/topic/thumb/upload', middlewares, uploadsController.uploadThumb);
	router.post('/user/:userslug/uploadpicture', middlewares.concat([middleware.authenticate, middleware.checkGlobalPrivacySettings, middleware.checkAccountPermissions]), controllers.accounts.uploadPicture);
};
Example #5
0
function uploadFile(){
    app.post("/uploadFile", multipart(),function(req,res) {
       var i=0;
       while(i != null){
           if(req.files["file"+i]) upLoad(i);
            else{ i= null; res.json({infor:"success"});return;}
           i++;
       }
        //上传队列文件
       function upLoad(index){
            var filename = req.files["file"+index].originalFilename || path.basename(req.files["file"+index].path);

            //path接口可以指定文件的路径和文件名称,"\结尾默认为路径,字符串结尾默认为文件名"
            var targetPath = path.dirname("") + '/Uploads/' + filename;

            //fs创建指定路径的文件并将读取到的文件内容写入
            fs.createReadStream(req.files["file"+index].path).pipe(fs.createWriteStream(targetPath));
         }

    });
}
Example #6
0
exports.beforeRoutes = function (app, conf, mongoose) {

	// all environments
	app.set('port', conf.app.port);
	app.set('trust proxy', 'loopback');
	//TODO: Don't allow cross domain in production
	//if ('development' == app.get('env')) {
		// development only
		app.use(allowCrossDomain);
	//}
	app.use(expressLogger('short', {stream: {write: function (msg) {
		logger.info(msg.trim());
	}}}));
	app.engine('dot', dot.__express);
	app.set('views', path.join(__dirname, '../views'));
	app.set('view engine', 'dot');
	// TODO: create a separate configuration value for this?
	app.use(bodyParser.json({limit: conf.import.uploadLimit }));
	app.use(bodyParser.urlencoded({ limit: conf.import.uploadLimit, extended: false }));
	app.use(multipart({
		uploadDir: conf.import.uploadDir,
		keepExtensions: true,
		maxFieldsSize: conf.import.uploadLimit
	}));
	app.use(methodOverride());
	app.use(cookieParser(conf.app.cookie_secret));
	app.use(session({
		secret: conf.app.session_secret,
		resave: true,
		saveUninitialized: true,
		cookie: {
			maxAge: conf.app.cookie_expire
		},
		store: new MongoStore({
			mongooseConnection: mongoose.connection
		})
	}));
	app.use(passport.initialize());
	app.use(passport.session());
}
Example #7
0
(function () {
  "use strict";

  var _ = require("lodash"),
    flow = require("./flow-node.js")("../quarantine"),
    multipart = require("connect-multiparty"),
    multipartMiddleware = multipart();
  
  modules.export = function (app) {

    // Handle uploads through Flow.js
    app.post('/upload', multipartMiddleware, function(req, res) {
      flow.post(req, function(status, filename, original_filename, identifier) {
        res.status(status).send();
      });
    });
    
    
    app.options('/upload', function(req, res){
      res.status(200).send();
    });

    // Handle status checks on chunks through Flow.js
    app.get('/upload', function(req, res) {
      flow.get(req, function(status, filename, original_filename, identifier) {
        if (status === "found") {
          status = 200;
        } else {
          status = 204;
        }
        res.status(status).send();
      });
    });
    
    app.get('/download/:identifier', function(req, res) {
      flow.write(req.params.identifier, res);
    });
  }
}());
Example #8
0
function setupConfig(){

	app.use(bodyParser.json());
	app.use(cookieParser()); // required before session.
	app.use(session({ 
		secret: 'g30p0rt@l',
		resave: true,
		saveUninitialized: true
	}));
	app.use(multiparty());

	app.use(new logger('dev'));
	//app.use(new cookieParser());
	//app.use(bodyParser.json());
	app.use(bodyParser.urlencoded({ extended: true }));
	app.use(new methodOverride());
	//app.use(new session({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
	app.use(flash());
	app.use(passport.initialize());
	app.use(passport.session());

	
}
Example #9
0
module.exports = function(app, data) {
	middleware = require('./middleware')(app);

	relativePath = nconf.get('relative_path');
	themesPath = nconf.get('themes_path');

	app.engine('tpl', templates.__express);
	app.set('view engine', 'tpl');
	app.set('views', nconf.get('views_dir'));
	app.set('json spaces', process.env.NODE_ENV === 'development' ? 4 : 0);
	app.use(flash());

	app.enable('view cache');

	app.use(compression());

	setupFavicon(app);
	
	app.use(relativePath + '/apple-touch-icon', middleware.routeTouchIcon);

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

	var cookie = {
		maxAge: 1000 * 60 * 60 * 24 * parseInt(meta.config.loginDays || 14, 10)
	};
	if(meta.config.cookieDomain) {
		cookie.domain = meta.config.cookieDomain;
	}

	app.use(session({
		store: db.sessionStore,
		secret: nconf.get('secret'),
		key: 'express.sid',
		cookie: cookie,
		resave: true,
		saveUninitialized: true
	}));

	app.use(multipart());

	app.use(function (req, res, next) {
		res.setHeader('X-Powered-By', 'NodeBB');

		res.setHeader('X-Frame-Options', 'SAMEORIGIN');
		if (meta.config['allow-from-uri']) {
			res.setHeader('ALLOW-FROM', meta.config['allow-from-uri']);
		}

		next();
	});

	app.use(middleware.processRender);

	auth.initialize(app, middleware);

	routeCurrentTheme(app, data.currentThemeId, data.themesData);
	meta.templates.compile();

	return middleware;
};
Example #10
0
//noinspection JSUnresolvedFunction
exports.use = [
    express.cookieParser(),
    express.cookieSession({
        secret: '1387074910625' + version.replace(/\./g, '')
    }),
    express.favicon(),
    express.logger('dev'),
    express.compress(),
    express.json(),
    express.urlencoded(),
    express.methodOverride(),
    lessMiddleware({src: publicDir}),
    express.static(publicDir),
    multipart(),
    middlewares.flash(),
    middlewares.sign(),
    middlewares.lang('en'),
    middlewares.cache(),
];


/**
 * available databases
 */
var databases = {
    mongo: {
        kind: 'mongojs',
        host: 'localhost',
        name: 'filedrop'.replace(/\./g, '_')
Example #11
0
var multiparty = require('connect-multiparty');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));//设置视图文件夹路径
app.set('view engine', 'ejs');//设置模板引擎为ejs,也可以是其它的,比如jade
app.use(flash());
app.use(favicon());//和系统favicon有关信息

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));//使用bodyParser过滤器,并且指定上传的目录为public/upload,注意这里的目录为相对于express框架app运行的路径,或者指定绝对路径。
app.use(multiparty({uploadDir:'public/uploads/photo', keepExtensions:true})); 
app.use(cookieParser());
app.use(session({
  secret: settings.cookieSecret,
  key: settings.db,//cookie name
  cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
  store: new MongoStore({
    db: settings.db
  })
}));
//设置资源文件(public)的路径
app.use(express.static(path.join(__dirname, 'public')));
//配置路由规则
app.use('/', routes);

Example #12
0
        LDAP_RESULTS: result
      }));
    }
    req.session.LDAP_RESULTS = result;
    console.log(req.session.LDAP_RESULTS);
    next();
  });
}, function (req, res, next) {
  if (req.body.PORT || req.current_config.PORT) return next();
  freeport(function (er, port) {
    req.body.PORT = port;
    next();
  });
} , merge_config);

app.post('/server', multipart(), set_current_config, function (req, res, next) {
  if (req.body.PORT || req.current_config.PORT) return next();
  freeport(function (er, port) {
    req.body.PORT = port;
    next();
  });
}, function (req, res, next) {
  if (!req.files || !req.files.SSL_PFX || req.files.SSL_PFX.size === 0) return next();
  // upload pfx
  fs.readFile(req.files.SSL_PFX.path, function (err, pfxContent) {
    req.body.SSL_PFX = new Buffer(pfxContent).toString('base64');
    delete req.files;
    next();
  });
}, merge_config);
Example #13
0
module.exports = function(app) {
    // Configuramos o servidor para que mostre o stack en caso de error
    app.set('showStackError', true);

    // Configuramos o porto
    app.set('port', config.port);

    // Prettify HTML.
    app.locals.pretty = true;

    // Configuramos express para que comprima os arquivos antes
    // de envialos ó cliente.
    app.use(compression({
        // Filtramos só os arquivos que queremos que se compriman.
        filter: function() {
            return (/json|text|javascript|css/).text;
        },
        // Sinalamos o nivel de comprensión que se aplicará ó recursos
        // do 0 o 10, de menor a maior.
        level: 9
    }));

    // Buscamos recursos státicos que podan responder a consulta e se non cargamos
    // o necesario para tratar de responder a consulta
    app.use(serve_favicon(config.paths.webroot + '/favicon.ico'));
    app.use(serve_static(config.paths.webroot));

    // Configuramos o directorio das vistas e o motor de plantilla que vamos a utilizar.
    app.set('views', config.paths.root + '/app/views');
    app.engine('ejs', ejs.renderFile);
    app.set('view engine', 'ejs');
    app.set('layout', 'template');
    app.use(ejs_layouts);

    // ##Configuramos os middlewares dos que vai a facer uso o servidor.
    // CookieParser para manexar as cookies dunha forma máis sinxela.
    app.use(cookie_parser());

    // Os encargados de recoller información enviada mediante POST, PUT...
    app.use(body_parser.json());
    app.use(body_parser.urlencoded({extended: false}));

    // Activamos a opción de recoller arquivos enviados dende formularios
    // é decir datos enviados mediante enctype multipart/form-data.
    app.use(multiparty());

    // MethodOverride é realmente útil para enviar datos mediante métodos non soportados
    // polo navegador como PUT, DELETE... simplemente engadindo ?_method=PUT a URL.
    app.use(method_override());

    // Activamos o almacenamento de sesions na base de datos.
    app.use(cookie_session({
        secret: config.sessions.secret,
        name: config.sessions.name
    }));

    // Activamos o uso de mensaxes "flash" para notificacións
    app.use(flash());
    app.use(function(req, res, next) {
        res.locals.flash = req.flash();
        next();
    });

    // Engadimos a consulta á resposta para poder acceder a ela dende as vistas ou controladores.
    app.use(function(req, res, next) {
        res.locals.req = req;
        next();
    });

    // Engadimos lodash ós locals para acceder a el dende as vistas
    app.use(function(req, res, next) {
        res.locals._ = lodash;
        next();
    });

    // Helpers, os axudantes que utilizaremos para a xeneración de vistas e máis cousas.
    app.use(helpers());

    // Sistema de internacionalización
    app.use(i18n.init());

    // Sistema de autenticación
    app.use(auth.init());

    // Lanzamos o enrutador para redireccionar cada consulta o controlador correspondente
    app.use(router.init(app));

    // Se estamos en entorno de desenrolo activamos o logger para ver
    // as consultas que se fan en cada momento.
    if (process.env.NODE_ENV === 'development') {
        app.use(morgan('dev'));
    }
};
Example #14
0
global.sequelize = new Sequelize('postgres://' + postgres.username + ':' + postgres.password + '@' + postgres.host + ':' + postgres.port + '/' + postgres.database);
var model = require('./models/index')();
var routesFrameController = require('./routes/index');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(connectMultiparty());

app.use(cookieParser());
app.use(function(req, res, next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With');
  res.header('Access-Control-Allow-Headers', 'Content-Type,apiKey,Authorization,deviceKey');
  next();
});

app.use(express.static(path.join(__dirname, 'public')));

app.use('/sockets', function (req, res) {
  res.sendfile(__dirname + '/public/socket.io.html');
});
Example #15
0
module.exports = function(container, libs, next) {
	var app = container.resolveSync('App'),
		config = container.resolveSync('Config'),
		options = container.tryResolveSync('ExpressOptions') || {},
		log = container.resolveSync('Logger'),
		routeLocals = container.resolveSync('RouteLocals');

	app.enable('trust proxy');
	app.enable('strict routing');
	app.enable('case sensitive routing');
	if (!config.cacheViews) {
		log.debug('disabling view cache');
		app.disable('view cache');
	} else {
		log.debug('enabling view cache');
		app.enable('view cache');
	}
	app.set('views', path.join(container.resolveSync('AppRoot'), 'views'));
	app.set('view engine', 'jade');

	container
		.registerInstance(expressSession, 'ExpressSession')
		.registerInstance(bodyParser, 'BodyParser')
		.registerInstance(cookieParser, 'CookieParser');

	//expose some locals for use in templates
	app.locals.pretty = true;
	app.locals.config = {
		staticBasePath: config.staticBasePath,
		scheme: config.scheme
	};

	app.locals.formatDate = stringUtils.formatDate;
	app.locals.formatNumber = stringUtils.formatNumber;
	app.locals.formatMoney = stringUtils.formatMoney;

	for (var local in routeLocals) {
		app.locals[local] = routeLocals[local];
	}

	//lol
	app.use(function(req, res, next) {
		res.header('X-Powered-By', 'Crystalis');
		next();
	});

	app.use(log.middleware.bind(log));

	//destruct!
	app.use(function(req, res, next) {
		log.trace('middleware: destructors');
		var destructors = container.tryResolveSync('Destructors');
		if (!destructors || !destructors.length) {
			next();
			return;
		}

		res.on('finish', function() {
			log.trace('response finished - destructing');
			if (!req.container) {
				return;
			}

			destructors = destructors.map(function(destructor) {
				return function(callback) {
					destructor(req.container, callback);
				};
			});

			async.series(destructors, function(err) {
				err && log.error('Error destructing request', err);
			});
		});

		next();
	});

	//set up default middleware
	app.use(cookieParser());
	app.use(bodyParser(options.bodyParser));
	app.use(multipartParser());
	app.use(expressSession({
		secret: config.session.secret,
		key: config.session.key,
		proxy: true,
		store: container.resolveSync('SessionStore')
	}));

	//set up per-request container
	app.use(require('../middleware/per-request-container')(container, libs));

	//initialize controller context
	app.use(require('../middleware/controller-context')(container, libs));

	//set up request locals for use by other middleware
	app.use(function(req, res, next) {
		log.trace('middleware: request-locals');
		var container = req.container,
			locals = {};

		locals.req = req;
		container.registerInstance(locals, 'RequestLocals');
		var userId = req.session && req.session.user && req.session.user.id;
		req.isAuthenticated = locals.isAuthenticated = !!userId;
		log.debug('isAuthenticated: ' + req.isAuthenticated + (userId ? ' (' + userId + ')' : ''));
		next();
	});

	//execute custom middleware
	app.use(function(req, res, next) {
		log.trace('middleware: app-middleware');
		var middleware = req.container.tryResolveSync('Middleware');
		if (!middleware || !middleware.length) {
			next();
			return;
		}

		middleware = middleware.map(function(handler) {
			return function(next) {
				handler(req, res, next);
			};
		});

		async.series(middleware, next);
	});

	next();
};
Example #16
0
File: index.js Project: ew1773/ogre
exports.createServer = function (opts) {
  if (!opts) opts = {}

  var app = express()
  app.set('views', __dirname + '/views')
  app.set('view engine', 'jade')

  app.options('/convert', enableCors, optionsHandler('POST'))
  app.options('/convertJson', enableCors, optionsHandler('POST'))

  app.use(express.static(__dirname + '/public'))
  app.get('/', function (req, res) {
    res.render('home')
  })

  app.use(urlencoded({ extended: false, limit: 3000000 }))
  app.use(multiparty())

  app.post('/convert', enableCors, function (req, res, next) {
    var ogr = ogr2ogr(req.files.upload.path)

    if (req.body.targetSrs) {
      ogr.project(req.body.targetSrs, req.body.sourceSrs)
    }

    if ('skipFailures' in req.body) {
      ogr.skipfailures()
    }

    if (opts.timeout) {
      ogr.timeout(opts.timeout)
    }

    res.header('Content-Type', 'forcePlainText' in req.body ? 'text/plain; charset=utf-8' : 'application/json; charset=utf-8')

    ogr.exec(function (er, data) {
      fs.unlink(req.files.upload.path)
      if (er) return res.json({ errors: er.message.replace('\n\n','').split('\n') })
      if (req.body.callback) res.write(req.body.callback + '(')
      res.write(JSON.stringify(data))
      if (req.body.callback) res.write(')')
      res.end()
    })
  })

  app.post('/convertJson', enableCors, function (req, res, next) {
    if (!req.body.jsonUrl && !req.body.json) return next(new Error('No json provided'))

    var ogr
    if (req.body.jsonUrl) {
      ogr = ogr2ogr(req.body.jsonUrl)
    }
    else {
      ogr = ogr2ogr(JSON.parse(req.body.json))
    }

    if ('skipFailures' in req.body) {
      ogr.skipfailures()
    }

    if (opts.timeout) {
      ogr.timeout(opts.timeout)
    }

    ogr.format('shp').exec(function (er, buf) {
      if (er) return res.json({ errors: er.message.replace('\n\n','').split('\n') })
      res.header('Content-Type', 'application/zip')
      res.header('Content-Disposition', 'filename=' + (req.body.outputName || 'ogre.zip'))
      res.end(buf)
    })
  })

  app.use(function (er, req, res, next) {
    console.error(er.stack)
    res.header('Content-Type', 'application/json')
    res.json({ error: true, msg: er.message })
  })

  return app
}
Example #17
0
// modules
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
// var Post refers to mongoose model post.js
var Post = require('./app/models/post.js');

//middleware for images
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

// necessary for file uploading
// TODO: implement file uploading to use, install connect-multiparty
// var multipart = require('connect-multiparty');
// var multipartMiddleWare = multipart();

// configure and connect to database
var db = mongoose.connect('mongodb://tritiatimmins:Harley*8@ds019658.mlab.com:19658/biketrader');

var port = process.env.PORT || 8080;

app.enable('trust proxy');

// get all data of POST body
app.use(bodyParser.json());

// parse app/vnd as json
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
Example #18
0
module.exports = function(db) {
    // Initialize express app
    var app = express();

    // Initialize models
    utilities.walk('./app/models', /(.*)\.(js$|coffee$)/).forEach(function(modelPath) {
        require(path.resolve(modelPath));
    });

    // Setting the environment locals
    app.locals.title = config.app.title;
    app.locals.description = config.app.description;
    app.locals.keywords = config.app.keywords;

    // 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 jade as the template engine
    // app.engine('html', consolidate[config.templateEngine]);  

    // // Set views path and view engine
    app.set('view engine', 'jade');
    app.set('views', config.root + '/public');

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

    // Stylus set up
    app.use(stylusMiddleware({
        src: path.join(__dirname, '../public'),
        dest: path.join(__dirname, '../public'),
        compile: function(str, thisPath) {
            return stylus(str)
            .set('filename', thisPath)
            .set('paths', [path.join(__dirname, '../public/style-sheets/stylus-shared')])
            .set('compress', true)
            .use(nib());
        }
    }));

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

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

    // request 'files' parser
    app.use(multipartParser());

    // express/mongo 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());
    // app.use(logger());
    // simple logger
    app.use(function(req, res, next){
      console.log('%s %s', req.method, req.url);
      next();
    });

    // Load Client Applications Markup Routers
    require('./.configureMarkupRouters').createAppsLaunchRoutes(app);

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

    // Load Database API Routes
    utilities.walk('./app/routes', /(.*)\.(js$|coffee$)/).forEach(function(routePath) {
        require(path.resolve(routePath))(app);
    });

    // HTML5 Mode support
    require('./.configureMarkupRouters').setAppsAsDefaultRoutes(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);
        // logger.error(err);

        res.status(err.code || 500);

        // respond with html page
        if (req.accepts('html')) {
            // Error page
            return res.render('views/500.jade', {
                error: err.error
            });
        }

        // respond with json
        if (req.accepts('json')) {
            res.jsonp(err.code, {
                'message': err.error || 'Server Error'
            });
            return;
        }
        // default to plain-text. send()
        res.type('txt').send(err.error || 'Server Error');
    });

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

    return app;
};
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const Router = express.Router;
const path = require('path');
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();

module.exports = function(program, app) {
	const logger = program.getLogger('router');
	const config = program.config.defaults;
	const AppController = program.require('controllers/app-controller');

	let router = new Router();
	let appController = new AppController(program);


	router.get('/', appController.index);
	router.get('/upload/:id?', appController.get_upload);
	router.post('/upload/:id?', multipartMiddleware, appController.post_upload);
	router.post('/log', bodyParser.json(), appController.post_log);

	var middleware = [
		path.resolve(__dirname, './jps-middleware-auth'),
		path.resolve(__dirname, './jps-middleware-admin'),
		path.resolve(__dirname, './jps-middleware-db'),
		path.resolve(__dirname, './jps-middleware-devices'),
		path.resolve(__dirname, './jps-middleware-passes')
	];

	middleware.forEach(function(m) {
Example #20
0
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    next();
});

var txtbefore = require('./src/common').txtbefore,
    hash = require('./src/hash'),
    txthash = hash.txthash,
    basedecode = hash.basedecode;
var jsug = require('./src/jsmin'),
    txtuglify = jsug.txtuglify,
    fileuglify = jsug.fileuglify;

app.get('/', (req, res) => {
        res.send('hello!');
    })
    .post('/hash/txt', txtbefore, txthash)
    .post('/hash/basedecode', txtbefore, basedecode)
    .post('/hash/file', function(req, res) {
        require('./src/hash').filehash(req, res);
    })
    .post('/js/txt', txtbefore, txtuglify)
    .post('/js/file', multipart(), fileuglify);

var server = app.listen(3000, () => {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
})
Example #21
0
var express=require('express');
var app = express();
var activityFunc = require('./controller/activityController');
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var multipart = require('connect-multiparty');
var multipartAction = multipart();
var user = require('./controller/user');
var party = require('./controller/party');
var themes = require('./controller/themesController');
var frozen=require('./controller/frozenController');
var wish = require('./controller/wishController')


app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.set('port', port);

app.use('/showActivity', express.static('./public'));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
app.set('json spaces', 4);
res.set("Content-Type", "application/json");
  next();
});

app.use('/addActivity', express.static('./public'));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Example #22
0
/**
 * Created by jialao on 2016/7/12.
 */
var express = require('express');
var auth = require('../../auth/auth.service');
var controller = require('./article.controller');
var multipart = require('connect-multiparty')
var router = express.Router();

router.post('/addArticle',auth.hasRole('admin'),controller.addArticle);
router.get('/getArticleList',auth.hasRole('admin'),controller.getArticleList);
// router.put('/:id/updateArticle',auth.hasRole('admin'),controller.updateArticle);
router.delete('/:id',auth.hasRole('admin'),controller.destroy);


router.get('/getFrontArticleList',controller.getFrontArticleList);
router.get('/getFrontArticleCount',controller.getFrontArticleCount);
router.get('/:id/getFrontArticle',controller.getFrontArticle);

router.get('/:id/getPrenext',controller.getPrenext);
router.put('/:id/toggleLike',auth.isAuthenticated(),controller.toggleLike);
router.post('/upload',multipart(),controller.upload);

module.exports = router;
Example #23
0
					require(newPath);
				}
			}else if(stat.isDirectory()){
				walk(newPath);
			}
		});
}

walk(models_path);
*/

app.set('views','./app/views/pages');
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(multipart());
app.use(cookieParser());
app.use(session({
	secret: 'MoviesSite',
	store: new mongoStore({
		url: dbUrl,
		colletion: 'sessions'
	})
}));

var env = process.env.NODE_ENV || 'dev';
if('development' === env){
	app.set('showStackError',true);
	app.use(logger(':method :url :status'));
	app.locals.pretty = true;
	mongoose.set('debug',true);
Example #24
0
"use strict";

var router = vulpejs.express.router;
var multipart = require('connect-multiparty');
var flow = require(vulpejs.root.dir + '/uploader/flow.js')(vulpejs.app.upload.files);

var ACCESS_CONTROLL_ALLOW_ORIGIN = false;

router.post('/flow/upload', multipart({
  uploadDir: vulpejs.app.upload.tmp
}), function(req, res) {
  flow.post(req, function(status, filename, original_filename, identifier) {
    if (ACCESS_CONTROLL_ALLOW_ORIGIN) {
      res.header("Access-Control-Allow-Origin", "*");
    }
    res.status(status).send();
  });
});

router.options('/flow/upload', function(req, res) {
  if (ACCESS_CONTROLL_ALLOW_ORIGIN) {
    res.header("Access-Control-Allow-Origin", "*");
  }
  res.status(200).send();
});

router.get('/flow/upload', function(req, res) {
  flow.get(req, function(status, filename, original_filename, identifier) {
    if (ACCESS_CONTROLL_ALLOW_ORIGIN) {
      res.header("Access-Control-Allow-Origin", "*");
    }
Example #25
0
var bodyParser = require('body-parser');
var multiparty = require('connect-multiparty');
var app = express();

// ip port setup
app.set('ip', ip);
app.set('port', port);
app.enable('trust proxy');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(multiparty({uploadDir: './public/upload', maxFieldsSize: 5 * 1024 * 1024}));
app.use(express.static(path.join(__dirname, 'public')));

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
  next();
});

app.use(function (req, res, next) {
  console.log(req.path);
  //angular启动页
  if (req.path.indexOf('/app') >= 0) {
    res.sendFile(__basename + '/public/index.html');
Example #26
0
var logger = require('_pr/logger')(module);
var expressLogger = require('_pr/logger').ExpressLogger();
var passport = require('passport');
var passportLdapStrategy = require('./lib/ldapPassportStrategy.js');
var passportADStrategy = require('./lib/adPassportStrategy.js');
var globalData = require('_pr/config/global-data.js');
var Tail = require('tail').Tail;

// express middleware
var expressCompression = require('compression');
var expressFavicon = require('serve-favicon');
var expressCookieParser = require('cookie-parser');
var expressSession = require('express-session');
var expressBodyParser = require('body-parser');
var multipart = require('connect-multiparty');
var expressMultipartMiddleware = multipart();
var appConfig = require('_pr/config');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(expressSession);
var mongoDbConnect = require('_pr/lib/mongodb');
var mongoose = require('mongoose');




logger.debug('Starting Catalyst');
logger.debug('Logger Initialized');
var LDAPUser = require('_pr/model/ldap-user/ldap-user.js');
var catalystSync = require('_pr/cronjobs/catalyst-scheduler/catalystScheduler.js');
LDAPUser.getLdapUser(function(err, ldapData) {
    if (err) {
Example #27
0
var exphbs  = require('express-handlebars');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/gmaps');
var flash = require('connect-flash');

var passport = require('passport');
require('./src/config/passport')(passport);
var session = require('express-session');
var webRouter = require('./src/routes/webRouter')();
var apiRouter = require('./src/routes/apiRouter')(passport);

var multiParty = require('connect-multiparty');
var multiPartyMiddleware = multiParty();

app.use(multiPartyMiddleware);
app.set('views', __dirname + '/src/views');
app.engine('.hbs',exphbs({defaultLayout:'body',extname:'.hbs',layoutsDir:'src/views/layouts',partialsDir:'src/views/partials'}));
app.set('view engine', '.hbs');
app.use(flash());
app.use(express.static(__dirname + '/src/public'));
app.use(express.static(__dirname + '/node_modules'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.use(morgan('dev'));
app.use(cookieParser());
app.use(session({
    secret:'express-app',
Example #28
0
   var express=require('express'),
      app=express(),
      mongo=require('mongoose'),
      bodyparser=require('body-parser'),
      multipart=require('connect-multiparty');
    var multipartmiddleware=multipart();
      app.use(bodyparser());
      app.use(multipart());
   var profilecontroller=require('./server/controllers/profile-controller.js'); 
var wastecontroller=require('./server/controllers/waste-controller.js');
var userscontroller=require('./server/controllers/users-controller.js');

   var authenticationcontroller=require('./server/controllers/authentication-controller.js');
   mongo.connect('mongodb://127.0.0.1/time-waste', function(err){
      if(err)
         throw err;
   });

      app.get('/',function(req,res)
      {
      	res.sendfile('./index.html');
      })
  
app.use('/index',express.static(__dirname+"/index.html"));
app.use('/uploads',express.static(__dirname+"/uploads"));
app.use('/app',express.static(__dirname+"/app"));
app.use('/node_modules',express.static(__dirname+"/node_modules"));
      //for authentication
      app.post('/api/user/signup',authenticationcontroller.signup);
      app.post('/api/user/login',authenticationcontroller.login);
   //for profile editing
Example #29
0
var routes = require('./routes/index');
var log = require('./routes/log');

var app = express();

// global
baseDir = __dirname;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(multipart({ uploadDir: path.join(__dirname, 'tmp') }));
app.use(cookieParser());
app.use('/public', express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/log', log);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers
Example #30
0
var EventHandler = require('../event')
  , UploadHandler = require('../upload')
  , DownloadHandler = require('../download')
  , multipart = require('connect-multiparty')
  , configuration = require('../configuration')
  , path = require("path")
  , WebSiteHandler = require('../webSite');
// , ErrorHandler = require('../error').consoleErrorHandler;


var uploadDirectory = path.join(__dirname,"..",configuration.targetImagesDirectory);
var multipartMiddleware = multipart({ keepExtensions: true, uploadDir: uploadDirectory });


module.exports = exports = function(app, db) {

	/*Handlers*/
	var eventHandler = new EventHandler(db);
	var uploadHandler = new UploadHandler(db);
	var downloadHandler = new DownloadHandler(db);
	var webSiteHandler = new WebSiteHandler(db);

	/*General*/
	app.get('/',webSiteHandler.webSiteIndex);
	
	/*Events*/
	app.get('/createNewEvent', eventHandler.displayCreateNewEventPage);
	app.post('/postNewEvent' , eventHandler.createNewEvent);
	app.post('/event_status',  eventHandler.isEventExistsAndOpen);

	/*Upload*/