Example #1
0
module.exports = function(app, config) {

  var env = process.env.NODE_ENV || 'development';
      app.locals.ENV = env;
      app.locals.ENV_DEVELOPMENT = env == 'development';


  app.disable('x-powered-by');
  app.set('views', config.root + '/app/views');
  app.set('view engine', 'jade');


  const sopts = {
    secret:           'gdealisthebestdeal',
    saveUninitialied: true,
    resave:           true,
    key:              'sid',
    cookie:           {httpOnly: true, maxAge: 259200000},
    store:            new RedisStore({prefix: 'session:', ttl: 10800})
  };

  // app.use(favicon(config.root + '/public/img/favicon.ico'));
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(cookieParser());
  app.use(compress());
  app.use(express.static(config.root + '/public'));
  app.use(methodOverride());
  app.use(session(sopts));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use((req, res, next) => {

    //TODO: this should probably be in middlewares instead.
    if (!req.isAuthenticated) { return next(); }

    res.locals.user = req.user;
    res.locals.session = req.session;
    next();

  });


  const controllers = glob.sync(config.root + '/app/controllers/*.js');
        controllers.forEach(function (controller) {
          require(controller)(app);
        });



  app.use((req, res, next) => {
    var err    = new Error('Not Found');
    err.status = 404;
    next(err);
  });

  if (app.get('env') === 'development') {
    app.use((err, req, res) => {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error:   err,
        title:   'error'
      });
    });
  }

  app.use((err, req, res) => {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error:   {},
      title:   'error'
    });
  });

};
Example #2
0
var regist = require('./routes/regist');
var publish_topic = require('./routes/publish_topic');
var users = require('./routes/users');
var index = require('./routes/index');

var app = express();

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

// 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 }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/login', login);
app.use('/regist', regist);
app.use('/publish_topic',publish_topic);
app.use('/users', users);
// 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 #3
0
var config = require('./config');
var bodyParser = require('body-parser');
var routerParse = require('./routerParse');
var httpClient = require('./client/httpClient');
var log4js = require('log4js');


log4js.configure('./config/log4js.json');
var log = log4js.getLogger("app");


app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto' }));

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({
		extended : true
	})); // for parsing application/x-www-form-urlencoded


// 读取参数
/** 服务端口 */
var port = config.port;

/** 读取路由参数 */
var routerMap = routerParse(config);

app.get('/', function (req, res) {
	console.log('receive from : %s', req.ip)
	res.send('Hello World');
})
Example #4
0
module.exports = function(app, passport) {
    app.use(bodyParser.urlencoded({
        extended: true
    }));

    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        } else {

            res.send(JSON.stringify({
                error: "you are not logged in."
            }))
        }
    }

    var pollHandler = new PollHandler();
    var clickHandler = new ClickHandler();

    app.route('/')
        .get(function(req, res) {
            res.sendFile(path + '/public/index.html');
        });

    app.route('/login')
        .get(function(req, res) {
            res.sendFile(path + '/public/login.html');
        });

    app.route('/logout')
        .get(function(req, res) {
            req.logout();
            res.redirect('/login');
        });

    app.route('/profile')
        .get(isLoggedIn, function(req, res) {
            res.sendFile(path + '/public/profile.html');
        });

    app.route('/new-poll')
        .get(isLoggedIn, function(req, res) {
            res.sendFile(path + '/public/new-poll.html');
        });
    // vote on polls route
    app.route('/vote/api')
        .post(function(req, res) {
            var poll = '/polls/' + req.body.pollID;
            pollHandler.vote(req.body);
            res.redirect(poll);
        });

    app.route('/new-poll/api')
        .post(isLoggedIn, function(req, res) {
            var x = req.body;
            x.github = req.user;
            pollHandler.addPoll(x);
            res.redirect('/new-poll');
        });

    app.route('/api/:id')
        .get(isLoggedIn, function(req, res) {
            res.json(req.user.github);
        });

    app.route('/auth/github')
        .get(passport.authenticate('github'));

    app.route('/auth/github/callback')
        .get(passport.authenticate('github', {
            successRedirect: '/',
            failureRedirect: '/login'
        }));

    //get invididual polls display client
    app.route('/polls/:id')
        .get(function(req, res) {
            res.sendFile(path + '/public/polls.html');
        });

    //get invididual polls server
    app.route('/poll/:id')
        .get(pollHandler.getPoll)
        .delete(isLoggedIn, pollHandler.deletePoll);


    app.route('/profile/polls')
        .get(isLoggedIn, pollHandler.getPolls);

    app.route('/profile/delete')
        .get(isLoggedIn, pollHandler.getDelete);

    app.route('/api/:id/clicks')
        .get(pollHandler.getPolls)
        .post(isLoggedIn, clickHandler.addClick)
        .delete(isLoggedIn, clickHandler.resetClicks);
    /* quick and dirty table clearing    
    app.route('/testing')
        .get(pollHandler.getDrop)*/
};
Example #5
0
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();

var jsonParser = bodyParser.json()

var urlencodedParser = bodyParser.urlencoded({ extended: true });

var port = process.config.port || 8888;

app.use(function (req, res, next) {
    console.log('Time ', Date.now());
    next();
});
app.use(urlencodedParser);
// Static Middleware .....
app.use('/css',express.static(__dirname + '/client/css'));
app.use('/js/lib',express.static(__dirname + '/client/js/lib'));
app.use('/js/test_module',express.static(__dirname + '/client/js/test_module'));

app.use('/test', function (req, res, next) {
    console.log("Test middleware : ",req.params[0]);
    next();
});

app.post('/getJsonData', function (req, res) {
    console.log(req.body);
});

app.get('/',function(req,res){
Example #6
0
File: index.js Project: intern0t/QR
var qrLibrary = require('qr-image');
var parser = require('body-parser')
var express = require('express'),
	app = express();
app.use(parser.urlencoded({ extended : true }));
app.use(parser.json());

app.post('/', function (req, res) {
	if(req.body.auth == "prashant"){
		var generatedQR = qrLibrary.image(req.body.data, {type:'png', size: 10});
		res.type('png');
		generatedQR.pipe(res);
	}else{
		res.json({message:"Well, you know you aren't supposed to be here! Do you not understand English?", youDumb:true});
	}
});

app.get('/', function (req, res) {
	res.json({message:"You really shouldn't be here!", author:"Prashant M. Shrestha"});
});

app.listen(1337);
console.log('QR Generator running in *:1337');
var express = require('express');
var productsRoute = express.Router();
var bodyParser = require('body-parser');
var fs = require('fs');
var productModule = require('../models/products.js');
var validation = require('../middleware/validation');


productsRoute.use(bodyParser.urlencoded({extended: true}));

//POST
productsRoute.post('/', validation({"name" : "string", "price" : "number", "inventory" : "number"}), function(req, res) {

  var productData = { "id" : req.body.id, "name" : req.body.name, "price" : req.body.price, "inventory" : req.body.inventory};

  productModule.add(productData)
  console.log('Product: ' + productData.name + ' added')
  res.redirect('/products/');
});

//PUT ID
productsRoute.put('/:id', validation({"name" : "string", "price" : "number", "inventory" : "number"}), function(req, res){

  var updatedData = { "id" : req.body.id, "name" : req.body.name, "price" : req.body.price, "inventory" : req.body.inventory};

  productModule.editById(updatedData)
  console.log('Product: ' + updatedData.name + ' has been updated');
  res.redirect('/products/');
});

//DELETE BY ID
Example #8
0
module.exports = function (app, speechToText, textToSpeech) {

	// Configure Express
	app.use(bodyParser.urlencoded({ extended: true }));
	app.use(bodyParser.json());

	// Setup static public directory
	app.use(express.static(__dirname + '/../public'));
	app.use(express.static(__dirname + '/../bower_components'));

	// Add error handling in dev
	if (!process.env.VCAP_SERVICES) app.use(errorhandler());

	// Route For text 2 speech
	app.get('/synthesizeMale', function(req, res) {
		var synthReq = {
			accept: "audio/ogg; codecs=opus",
			voice: "VoiceEnUsMichael",
			text: req.query.text
		};
		var transcript = textToSpeech.synthesize(synthReq);
		transcript.on('response', function(response) {
	    	console.log(response.headers);
	    	if (req.query.download) {
	      		response.headers['content-disposition'] = 'attachment; filename=transcript.ogg';
	    	}
	  	});
	  	transcript.pipe(res);
	});

	// Route For text 2 speech
	app.get('/synthesizeMale', function(req, res) {
		var synthReq = {
			accept: "audio/ogg; codecs=opus",
			voice: "VoiceEnUsMichael",
			text: req.query.text
		};
		var transcript = textToSpeech.synthesize(synthReq);
		transcript.on('response', function(response) {
	    	console.log(response.headers);
	    	if (req.query.download) {
	      		response.headers['content-disposition'] = 'attachment; filename=transcript.ogg';
	    	}
	  	});
	  	transcript.pipe(res);
	});

	app.get('/synthesizeFemale', function(req, res) {
		var synthReq = {
			accept: "audio/ogg; codecs=opus",
			voice: "VoiceEnUsLisa",
			text: req.query.text
		};
		var transcript = textToSpeech.synthesize(synthReq);
		transcript.on('response', function(response) {
	    	console.log(response.headers);
	    	if (req.query.download) {
	      		response.headers['content-disposition'] = 'attachment; filename=transcript.ogg';
	    	}
	  	});
	  	transcript.pipe(res);
	});

	// For speech 2 text
	app.post('/', function(req, res) {
		var audio;

		if(req.body.url && req.body.url.indexOf('audio/') === 0) {
			// sample audio
	    	audio = fs.createReadStream(__dirname + '/../public/' + req.body.url);
	  	} else { // malformed url
	    	return res.status(500).json({ error: 'Malformed URL' });
	  	}

		speechToText.recognize({audio: audio, content_type: 'audio/l16; rate=44100'}, function(err, transcript){
	    	if (err) return res.status(500).json({ error: err });
	    	else return res.json(transcript);
	  	});
	});
};
Example #9
0
	// app
  	app.use("/app", express.static(__dirname + "/app"));
  	
	// static resources that don't need compiling
	app.use("/libs", express.static(__dirname + "/views/libs"));
	app.use("/img", express.static(__dirname + "/views/img"));	
	app.use("/styles", express.static(__dirname + "/views/styles"));
	
  	app.use(function(req, res, next) {
    	res.header("Access-Control-Allow-Origin", "*");
    	res.header("Access-Control-Allow-Headers", "X-Requested-With");
    	next();
  	});
	
	app.use(cookieParser());
	app.use(bodyParser.urlencoded({ extended: true, limit: "5mb" }));
	app.use(bodyParser.json({ limit: "5mb" }));
	app.use(session({ secret: config.sessionID, saveUninitialized: true, resave: true }));
	app.use(passport.initialize());
	app.use(passport.session());

// Create the http server and attach engine.io to it
	
	var http = require("http").createServer(app).listen(8080);
	
	var socket = io.attach(http);

	/*process.on("uncaughtException", function(err) {
		console.log("************************** UNCAUGHT EXCEPTION: " + err);
	});*/
module.exports = function(server){

  var email = require('../../email'),
      forEach = require('../../helper').forEach,
      auth = require('../../authHandler'),
      Blog = require('../../models/blog'),
      User = require('../../models/user'),
      bodyParser = require('body-parser');

  server.get('/disabled', auth.check, function(request, response){

    // Only disabled users can see this page
    if (request.user) return response.redirect('/');

    response.addLocals({
      partials: {yield: 'dashboard/disabled'},
      title: 'Your Blot account is disabled',
      noRobots: true
    });

    response.render('dashboard/_wrapper');
  });

  server.get('/disable-account', auth.enforce, function(request, response){

    var user = request.user;

    // Make sure users with a subscription ask them
    // to disable their subscription first
    if (user.isSubscribed) return response.redirect('/cancel');

    // If user is new or doesn't have a handle,
    // let them choose one
    response.addLocals({
      partials: {yield: 'dashboard/disable'},
      title: 'Disable your account'
    });

    response.render('dashboard/_wrapper');
  });

  // Takes a stripe token generated
  // on the client and creates a charge
  server.post('/disable-account', auth.enforce, bodyParser.urlencoded({extended:false}), function(request, response){

    var user = request.user,
        uid = user.uid;

    // Make sure users with a subscription
    // disable their subscription first
    if (user.isSubscribed) return response.redirect('/cancel');

    var shouldDisable = !!(request.body.disableAccount);

    if (!shouldDisable) return response.redirect('/settings');

    User.set(uid, {isDisabled: shouldDisable}, function(errors){

      if (errors) throw errors;

      forEach(user.blogs, function(blogID, nextBlog){

        Blog.set(blogID, {isDisabled: shouldDisable}, nextBlog);

      }, function(){

        email.DISABLED(uid);

        request.session.destroy(function() {
          response.redirect('/disabled');
        });
      });
    });
  });
};
Example #11
0
    if (!req.user) {
        const err = new Error('not allowed');
        err.status = 403;
        return next(err);
    }

    return res.render('user_settings.html', {
        req,
        res,
        user: req.user,
        meta: {}
    });
});

router.post('/user/settings', bodyParser.urlencoded({
    extended: true,
    limit: '3mb'
}), function(req, res, next) {
    if (!req.user) {
        const err = new Error('not allowed');
        err.status = 403;
        return next(err);
    }

    if (req.body.imageBase64) {

        const blob = new Buffer(req.body.imageBase64.toString('base64').replace(/^data:image\/(png|gif|jpeg);base64,/, ''), 'base64');
        const filetype = fileTypeDetector(blob);

        if (filetype.ext == 'jpg' ||
            filetype.ext == 'jpeg' ||
            filetype.ext == 'png') {
Example #12
0
module.exports = function (app, passport) {

    // Compression middleware (should be placed before express.static)
    app.use(compression({
        threshold: 512
    }));

    // Static files middleware
    app.use(express.static(config.root + '/public'));

    // Use winston on production
    let log = 'dev';
    if (env !== 'development') {
        log = {
            stream: {
                write: message => winston.info(message)
            }
        };
    }

    // Don't log during tests
    // Logging middleware
    if (env !== 'test') app.use(morgan(log));

    // Swig template engine settings
    if (env === 'development' || env === 'test') {
        swig.setDefaults({
            cache: false
        });
    }

    // set views path, template engine and default layout
    app.engine('html', swig.renderFile);
    app.set('views', config.root + '/views');
    app.set('view engine', 'html');

    // expose package.json and environment to views (why ?!)
    app.use(function (req, res, next) {
        res.locals.pkg = pkg;
        res.locals.env = env;
        next();
    });

    // bodyParser should be above methodOverride
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(multer().array('image', 1));
    app.use(methodOverride(function (req) {
        if (req.body && typeof req.body === 'object' && '_method' in req.body) {
            // look in urlencoded POST bodies and delete it
            var method = req.body._method;
            delete req.body._method;
            return method;
        }
    }));

    // CookieParser should be above session
    app.use(cookieParser());
    app.use(cookieSession({ secret: 'secret' }));
    app.use(session({
        resave: true,
        saveUninitialized: true,
        secret: pkg.name,
        store: new mongoStore({
            url: config.db,
            collection : 'sessions'
        })
    }));

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

    // connect flash for flash messages - should be declared after sessions
    app.use(flash());

    // should be declared after session and flash
    app.use(helpers(pkg.name));

    if (env !== 'test') {
        app.use(csrf());

        // This could be moved to view-helpers :-)
        app.use(function (req, res, next) {
            res.locals.csrf_token = req.csrfToken();
            next();
        });
    }
};
Example #13
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;
};
Example #14
0
var http = require("http");
var handler = require("./request-handler");
var express = require("express");
var bodyParser = require('body-parser')
// TODO: requirements for request handler
var archive = require('../helpers/archive-helpers');
var helpers = require('./http-helpers.js');


var app = express();
var server = app.listen(8080, function() {
    console.log('Listening on port %d', server.address().port);
});

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use( bodyParser.urlencoded() ); // to support URL-encoded bodies


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


app.use('/', handler);

Example #15
0
 mongoose schema, is create table. 


mongoose model genaamd todo , is een klasse

todo.find => haalt alles op uit de database

 */


var express  = require('express');
var app      = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');


mongoose.connect('mongodb://localhost/todo');
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json

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

app.listen(3000, function () {
  console.log('todo app on port 3000');
});

require('./app/routes')(app);



Example #16
0
var express = require('express')
var config = require("./config")
var bodyParser = require('body-parser')
var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var async = require("async")
var parseString = require('xml2js').parseString;
var accessToken = null
var wechat = require('wechat')
var flash = require('connect-flash');
var cookieParser = require('cookie-parser')
var session = require('express-session')
var _ = require('lodash')
var formidable = require('formidable')
var fs = require('fs')
var path = require('path')
var helpers = require("./helpers")
var moment = require('moment')
var fs        = require('fs');
var app = express();
var admin = express();
var OAuth = require('wechat-oauth');

var Payment = require('wechat-pay').Payment;
var initConfig = {
  partnerKey: config.partnerKey,
  appId: config.appId,
  mchId: config.mchId,
  notifyUrl: "http://" + config.hostname + "/paymentconfirm",
  pfx: fs.readFileSync(process.env.PWD + '/cert/apiclient_cert.p12')
};
Example #17
0
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var request = require('request');

var config = require('./config');

var Job = require('./models/Job');
var Movie = require('./models/Movie');
var Theater = require('./models/Theater');

mongoose.connect(config.mongo.url);

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());

/*
	/api/search
	Access Fandango's autocomplete API and convert their movie results to slugs that follow their format(sanitize name then append the ID).
*/
app.get('/api/search', function(req, res) {
    var q = req.query.q;
    var type = req.query.type ? req.query.type : 'Movie';
	request('https://www.fandango.com/api/search/autocompletemulti?q=' + q + '&callback=callback&_=' + Date.now(), function(error, response, body) {
		var response = [];
		var callback = function(results) {
			results.forEach(function(result) {
				if (result.Type === type) {
					var obj = {
//Anlegen globaler Variablen
var lastDice = 0;               //Letzter Würfelwurfs
var gamefieldArray = Array(40); //40 Mögliche Spielfeldpositionen (ohne goal und home)
var homeArray = Array(16);      //Home der Spielfiguren
var goalArray = Array(16);      //Goal der Spielfiguren
var homeCount = 0;              //Anzahl der Spieler im Goal
var playerCount = 0;            //Anzahl verbundener Spieler
var diceCount = 0;              //Anzahl der erlaubten Würfelwürfe (nicht alle Fälle)
var currentPosition = 0;        //Aktuelle Position der gewählten Figur
var unusedMoves = 0;            //Unbenutzte Feldzüge bei Arrayübergang

//Spielfeld aufbauen oder zurücksetzen
resetGame();

//****************************************Spielfigurposition ermitteln****************************************
app.put('/spielfigur/position',bodyParser.urlencoded({extended:true}) ,function(req, res){
  var id = req.body.id;
  //Figuren ID ermitteln
  var figureID = String(id);
  //Alle Spielfelder durchlaufen
  for(var i = 0; i < gamefieldArray.length; i++){
    console.log("Auf Spielfeld " + i + " befindet sich die Figur" + gamefieldArray[i]);
    //ID des Felds = Figuren ID -> Rückgabe
    if(gamefieldArray[i] == figureID){
      res.end(i.toString());
    }
  }
  //Figur nicht auf Spielfeldern -> Alle Goalfelder durchlaufen
  for(var i = 0; i < goalArray.length; i++){
    //ID des Felds = Figuren ID -> Rückgabe
    if(goalArray[i] == figureID){
Example #19
0
setupMiddleware = function (server) {
    var logging = config.logging,
        subdir = config.paths.subdir,
        corePath = config.paths.corePath,
        oauthServer = oauth2orize.createServer();

    // silence JSHint without disabling unused check for the whole file
    authStrategies = authStrategies;

    // Cache express server instance
    expressServer = server;
    middleware.cacheServer(expressServer);
    middleware.cacheOauthServer(oauthServer);
    oauth.init(oauthServer, middleware.resetSpamCounter);

    // Make sure 'req.secure' is valid for proxied requests
    // (X-Forwarded-Proto header will be checked, if present)
    expressServer.enable('trust proxy');

    // Logging configuration
    if (logging !== false) {
        if (expressServer.get('env') !== 'development') {
            expressServer.use(logger(logging || {}));
        } else {
            expressServer.use(logger(logging || 'dev'));
        }
    }

    // Favicon
    expressServer.use(subdir, favicon(corePath + '/shared/favicon.ico'));

    // Static assets
    expressServer.use(subdir + '/shared', express['static'](path.join(corePath, '/shared'), {maxAge: utils.ONE_HOUR_MS}));
    expressServer.use(subdir + '/content/images', storage.get_storage().serve());
    expressServer.use(subdir + '/ghost/scripts', express['static'](path.join(corePath, '/built/scripts'), {maxAge: utils.ONE_YEAR_MS}));
    expressServer.use(subdir + '/public', express['static'](path.join(corePath, '/built/public'), {maxAge: utils.ONE_YEAR_MS}));

    // First determine whether we're serving admin or theme content
    expressServer.use(updateActiveTheme);
    expressServer.use(decideContext);

    // Admin only config
    expressServer.use(subdir + '/ghost', middleware.whenEnabled('admin', express['static'](path.join(corePath, '/client/assets'), {maxAge: utils.ONE_YEAR_MS})));

    // Force SSL
    // NOTE: Importantly this is _after_ the check above for admin-theme static resources,
    //       which do not need HTTPS. In fact, if HTTPS is forced on them, then 404 page might
    //       not display properly when HTTPS is not available!
    expressServer.use(checkSSL);

    // Theme only config
    expressServer.use(subdir, middleware.staticTheme());

    // Serve robots.txt if not found in theme
    expressServer.use(robots());

    // Add in all trailing slashes
    expressServer.use(slashes(true, {headers: {'Cache-Control': 'public, max-age=' + utils.ONE_YEAR_S}}));

    // Body parsing
    expressServer.use(bodyParser.json());
    expressServer.use(bodyParser.urlencoded());

    expressServer.use(passport.initialize());

    // ### Caching
    expressServer.use(middleware.cacheControl('public'));
    expressServer.use(subdir + '/ghost/', middleware.cacheControl('private'));


    // enable authentication
    expressServer.use(middleware.authenticate);

    // local data
    expressServer.use(ghostLocals);

    // ### Routing
    // Set up API routes
    expressServer.use(subdir + routes.apiBaseUri, routes.api(middleware));

    // Set up Admin routes
    expressServer.use(subdir, routes.admin(middleware));

    // Set up Frontend routes
    expressServer.use(subdir, routes.frontend());

    // ### Error handling
    // 404 Handler
    expressServer.use(errors.error404);

    // 500 Handler
    expressServer.use(errors.error500);
};
Example #20
0
var user = require('./lib/middleware/user');
var page = require('./lib/middleware/page');
var Entry = require('./lib/entry');
var api = require('./routes/api');

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); //extended设为true才能使用表单的对象表示法
app.use(cookieParser());
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  // cookie: { maxAge: 60 * 60 * 1000 } //one hour
  // cookie: { secure: true }
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', api.auth);
app.use(user);
app.use(messages);

app.get('/register', register.form);
app.post('/register', register.submit);
Example #21
0
    origin: true
}))
backend.enable('trust proxy');
backend.use(session({
    secret: 'Nguoi yeu dau hoi~ em mai la mat troiiii',
    resave: false,
    proxy: true,
    saveUninitialized: false,
    cookie: {
        secure: true,
        httpOnly: false,
        maxAge: 1000 * 60 * 60 * 24 * 7
    }
}))

backend.use(bodyParser.urlencoded({ extended: false, limit:'10mb' }));
backend.use(bodyParser.json({limit: '10mb'}));
backend.use(passport.initialize());
backend.use(passport.session());

backend.use((req, res, next) => {
   
    next();
})


backend.use('/api', apiRouter);
var authFB = require('./router/auth.fb')(passport);
backend.use('/api', authFB);

Example #22
0
module.exports = function(settings, catalog, callback) {
    var https = require('https');
    var http = require('http');
    var express = require('express');
    var basicAuth = require('basic-auth');
    var bodyParser = require('body-parser');
    var fs = require('fs');
    var path = require('path');
    var logger = require(path.join(__dirname, './logger/logger.js'));
    var models = require(path.join(__dirname, './models'))(settings.db, callback);
    
    var publicPort = settings.publicPort;
    var port = settings.port;
    var publicOptions = {};
    
    if(settings.publicTls){
        if(!fs.existsSync(settings.publicTls.keyFile)){
            logger.error("Invalid TLS key path: " + settings.publicTls.keyFile);
            throw new Error("Invalid TLS key path: " + settings.publicTls.keyFile);
        }
        if(!fs.existsSync(settings.publicTls.certFile)){
            logger.error("Invalid TLS certificate path: " + settings.publicTls.certFile);
            throw new Error("Invalid TLS certificate path: " + settings.publicTls.certFile);
        }
        if(!fs.existsSync(settings.publicTls.caCertFile)){
            logger.error("Invalid TLS ca certificate path: " + settings.publicTls.caCertFile);
            throw new Error("Invalid TLS ca certificate path: " + settings.publicTls.caCertFile);
        }

        publicOptions = {
            key: fs.readFileSync(settings.publicTls.keyFile),
            cert: fs.readFileSync(settings.publicTls.certFile),
            ca: fs.readFileSync(settings.publicTls.caCertFile)
        }
    }

    var options = {};
    
    if(settings.tls){
        if(!fs.existsSync(settings.tls.keyFile)){
            logger.error("Invalid TLS key path: " + settings.tls.keyFile);
            throw new Error("Invalid TLS key path: " + settings.tls.keyFile);
        }
        if(!fs.existsSync(settings.tls.certFile)){
            logger.error("Invalid TLS certificate path: " + settings.tls.certFile);
            throw new Error("Invalid TLS certificate path: " + settings.tls.certFile);
        }
        if(!fs.existsSync(settings.tls.caCertFile)){
            logger.error("Invalid TLS ca certificate path: " + settings.tls.caCertFile);
            throw new Error("Invalid TLS ca certificate path: " + settings.tls.caCertFile);
        }

        options = {
            key: fs.readFileSync(settings.tls.keyFile),
            cert: fs.readFileSync(settings.tls.certFile),
            ca: fs.readFileSync(settings.tls.caCertFile)
        }
    }

    var app = express();
    var auth = function(req, res, next) {
        function unauthorized(res) {
            res.set('WWW-Authenticate', 'Basic realm="serviceBrokerAuth"');
            return res.sendStatus(401);
        };

        var user = basicAuth(req);
        if (!user || !user.name || !user.pass) {
            return unauthorized(res);
        };

        if (user.name === settings.username && user.pass === settings.password) {
            return next();
        } else {
            return unauthorized(res);
        };
    };


    //define the sequence of middleware
    app.use(auth);
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    require('./routes')(app, settings, catalog, models);

    var internalApp = express();
    internalApp.use(bodyParser.urlencoded({ extended: true }));
    internalApp.use(bodyParser.json());
    require('./internalRoutes')(internalApp, settings);


    var publicServer;
    if(settings.publicTls){
        publicServer = https.createServer(publicOptions, app).listen(publicPort, function() {
            var port = publicServer.address().port;
            logger.info('Service broker app is running in secure mode', { 'port': port });
        });
    }else{
        publicServer = http.createServer(app).listen(publicPort, function() {
            var port = publicServer.address().port;
            logger.info('Service broker app is running', { 'port': port });
        });
    }

    var internalServer;
    if(settings.tls){
        internalServer = https.createServer(options, internalApp).listen(port, function() {
            var port = internalServer.address().port;
            logger.info('Service broker internal app is running in secure mode', { 'port': port });
        });
    }else{
        internalServer = http.createServer(internalApp).listen(port, function() {
            var port = internalServer.address().port;
            logger.info('Service broker internal app is running', { 'port': port });
        });
    }

    var gracefulShutdown = function(signal) {
        logger.info("Received " + signal + " signal, shutting down gracefully...");
        publicServer.close(function() {
            logger.info('Everything is cleanly shutdown for service broker server');
            internalServer.close(function() {
                logger.info('Everything is cleanly shutdown for service broker internal server');
                process.exit();
            });
        });
    }

    //listen for SIGUSR2 signal e.g. user-defined signal
    process.on ('SIGUSR2', function(){
        gracefulShutdown('SIGUSR2')
    });

    return  {"internalServer": internalServer, "publicServer": publicServer};;
}
        //edge labels
        var label = $(e).find('y\\:EdgeLabel').first().text().trim()
        if (label) output[nodes[target]].push(label)
    })

    fs.writeFile(ontologyOutFile, 'ontology = ' + JSON.stringify(output))

    console.log('Updated ontology'.green + ontologyOutFile)

}


///////////////////////////////////////////////////////////////////////////////////////////////////
// EXPRESS SERVER

var urlencodedParser = myParser.urlencoded({ extended:true,limit:5000000, parameterLimit: 5000000 })
app.use(urlencodedParser);

app.use(myParser.json({limit: '5mb'}));
app.use(cors())


// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'null');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
Example #24
0
var slack = require('./slackmn');

//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
//  * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);


router.use( bodyParser.json() );       // to support JSON-encoded bodies
router.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

router.use(express.static(path.resolve(__dirname, 'client')));

// Slack messagges reception Manager
router.all('/slack',function(req, res) {
  
  var message = slack.parseHeader( req );
  slack.saveMessage(message);
  res.send( JSON.stringify( slack.loadMessages() ) );
});

server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
  var addr = server.address();
  console.log("Chat server listening at", addr.address + ":" + addr.port);
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.disable('etag');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

/// 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

// development error handler
Example #26
0
// require express
var express = require("express");
// path module -- try to figure out where and why we use this
var path = require("path");
// create the express app
var app = express();
// require body-parser
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
        extended: false,
     parameterLimit: 10000,
     limit: 1024 * 1024 * 10
}));
app.use(bodyParser.json({
        extended: false,
     parameterLimit: 10000,
     limit: 1024 * 1024 * 10
}));

// static content
app.use(express.static(path.join(__dirname, "./client")));
// setting up ejs and our views folder
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'ejs');

// This goes in our server.js file so that we actually use the mongoose config file!
require('./config/mongoose.js');

// this line requires and runs the code from our routes.js file and passes it app so that we can attach our routing rules to our express application!
require('./config/routes.js')(app);
Example #27
0
File: app.js Project: johnz/qme
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var routes = require('./api')(app);

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/', express.static('./client/'));
app.use('/', express.static('./'));

var server = app.listen(3000, function () {

  var host = server.address().address
  var port = server.address().port

  console.log('Example app listening at http://%s:%s', host, port)

})
Example #28
0
module.exports = function (app, config, passport) {

  app.set('showStackError', true);

  if (process.env.NODE_ENV === 'dev') {
    app.use(express.static('./static'));
  }

  app.use(morgan('dev')); // LOGGING

  // set views path, template engine and default layout and static
  app.use('/static/', express.static(path.join(__dirname, 'static')));
  app.set('views', config.root + '/assets/templates/server');
  app.set('view engine', 'jade');
  app.disable('view cache');

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

  // bodyParser should be above methodOverride
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended: false}));


  app.use(session({
    store: new pgSession({
      pg: pg,
      conString: config.db
    }),
    secret: config.sessionSecret,
    cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
  }));


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

  // adds CSRF support
  app.use(csrf());

  app.use(function(req, res, next) {
    res.cookie('CSRF-TOKEN', req.csrfToken());
    next();
  });

  // Bootstrap routes
  require('./routes')(app, passport);

  // error
  app.use(function(err, req, res, next) {
    console.log(err);
    if (typeof err.name === 'string') {
      console.log(err.stack);
      return res.json(500, {
        data: 'wow such error.',
        error: true,
        status: 500
      });
    }
    else if (typeof err.name === 'number') {
      res.json(err.name, {
        status: err.name,
        error: true,
        data: err.message
      });
    }
  });

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

};
Example #29
0
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express();
        self.app.use(bodyParser.json());
        self.app.use(bodyParser.urlencoded({ extended: true }));
        self.app.use(express.static(path.join(__dirname, 'public')));
        self.app.use(function (req, res, next) {

            // Website you wish to allow to connect
            res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
            //res.setHeader('Access-Control-Allow-Origin', 'http://BetYou.Fail'); //Allow BYF to connect

            // 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();
        });
        
                
        self.app
            .post('/api/schools', function(req, res){
                console.log(schools);
        })
            .post('/api/wagers/wager', function(req,res){
                console.log(req.body.amount);
                console.log(req.body.amountBTC);
                var keyPair = bitcoinCtrl.CreateKeyPair();
                req.body.publicAddress = keyPair.getAddress();
                req.body.dateSubmitted = Date();
                console.log(req.body.dateSubmitted);
                console.log(req.body.publicAddress + " "+keyPair.toWIF());
                res.send(req.body);
        })
            .get('/api/schools', function(req, res){
                console.log(schools.school.ID);
                res.send(schools); 
        })
            .get('/api/students', function(req, res){
                console.log(students);
                res.json(students); 
        })
            .get('/api/sms', function(req, res){
                // Create a TwiML response
                var twiml = new twilio.TwimlResponse();
                var smsNumber = req.from;
            

                // The TwiML response object will have functions on it that correspond
                // to TwiML "verbs" and "nouns". This example uses the "Say" verb.
                // Passing in a string argument sets the content of the XML tag.
                // Passing in an object literal sets attributes on the XML tag.
                twiml.message('ahoy hoy! Testing Twilio and node.js');

                //Render the TwiML document using "toString"
                res.writeHead(200, {
                    'Content-Type':'text/xml'
                });
                res.end(twiml.toString());
        });
           
        schools.forEach(function(school){
            console.log(school.ID);
            self.app.get('/api/schools/'+ school.ID, self.routes['/api/schools/'+school.ID]);
        });
        /*schools.forEach(function(obj){
            self.app.get('/api/schools/'+obj.school.ID, self.routes['/api/schools/'+obj.school.ID]);
            console.log(obj.school.ID)
        });*/
        
    };
Example #30
0
'use strict';

let express = require('express');
let bodyParser = require('body-parser');
let ejs = require('ejs');
let app = express();
let path = require('path');
let port = process.env.PORT || 8081;
let urlParser = bodyParser.urlencoded({extended: true});
let getWeather = require('./src/services/openWeather');

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

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

app.get('/', (req, res) => {
  res.status(200).render('index');
});

app.get('/api/:lat/:lng', (req, res) => {
  getWeather(req.params.lat, req.params.lng, (err, data) => {
    if (err) {
      res.status(500).send('Error');
    }
    res.status(200).send(data);
  });
});

app.listen(port, (err) => {
  if (err) {