Example #1
0
var express = require('express')
  , flash = require('connect-flash')
  , passport = require('passport')
  , http = require('http')
  , nconf = require('nconf');


var app = express();

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.cookieParser());
app.use(express.session({ secret: 'omglol' }));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
nconf.use('config', { type: "file", file: __dirname  + '/config/config.json' });


// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}
Example #2
0
var config = require('./config');
var log4js = require('log4js');
var logger = require('./common/logger').logger('istc');

routes.initIDKey();

var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(log4js.connectLogger(logger, {level:'auto'}));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser(config.sessionSecret));
app.use(express.session());
app.use(function(req, res, next){		
	res.locals.config = config;	//add config object to view   
	next();
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(authUser);
app.use(app.router);

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler({ dumpExceptions: true }));
}

routes.index(app);
Example #3
0
var flash = require('connect-flash');

var util = require('util');

app.use(logfmt.requestLogger());

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon('public/favicon.ico'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({secret: "MQ4MNOIq1Uv3dVIuxmvi", cookie: { maxAge: 60000 }}));
// Initialize Passport!  Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);

var admin_pw = process.env.ADMIN_PW || "";
var auth = express.basicAuth('admin', admin_pw);

var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.set('log level', 2);
Example #4
0
File: app.js Project: vas85/drywall
app.configure(function(){
  //settings
  app.disable('x-powered-by');
  app.set('sport', config.sport);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('strict routing', true);
  app.set('project-name', config.projectName);
  app.set('company-name', config.companyName);
  app.set('system-email', config.systemEmail);
  app.set('crypto-key', config.cryptoKey);
  app.set('require-account-verification', config.requireAccountVerification);

  //smtp settings
  app.set('smtp-from-name', config.smtp.from.name);
  app.set('smtp-from-address', config.smtp.from.address);
  app.set('smtp-credentials', config.smtp.credentials);

  //twitter settings
  app.set('twitter-oauth-key', config.oauth.twitter.key);
  app.set('twitter-oauth-secret', config.oauth.twitter.secret);

  //github settings
  app.set('github-oauth-key', config.oauth.github.key);
  app.set('github-oauth-secret', config.oauth.github.secret);

  //facebook settings
  app.set('facebook-oauth-key', config.oauth.facebook.key);
  app.set('facebook-oauth-secret', config.oauth.facebook.secret);

  //google settings
  app.set('google-oauth-key', config.oauth.google.key);
  app.set('google-oauth-secret', config.oauth.google.secret);

  //middleware
  app.use(express.logger('dev'));
  app.use(express.compress());
  app.use(express.favicon(__dirname + '/public/favicon.ico'));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.urlencoded());
  app.use(express.json());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({
    secret: config.cryptoKey,
    store: app.sessionStore
  }));
  app.use(passport.initialize());
  app.use(passport.session());
  helmet.defaults(app);

  //response locals
  app.use(function(req, res, next) {
    res.locals.user = {};
    res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
    res.locals.user.username = req.user && req.user.username;
    next();
  });

  //mount the routes
  app.use(app.router);

  //error handler
  app.use(require('./views/http/index').http500);

  //global locals
  app.locals.projectName = app.get('project-name');
  app.locals.copyrightYear = new Date().getFullYear();
  app.locals.copyrightName = app.get('company-name');
  app.locals.cacheBreaker = 'br34k-01';
});
var CLOUDANT_SERVICE = serviceStartsWith('Cloudant');
var CLOUDANT_URL = ( CLOUDANT_SERVICE.url ) ;
var CLOUDANT_DATABASE = (CLOUDANT_SERVICE.database || urllib.parse(CLOUDANT_URL).pathname.substring(1));
if (!CLOUDANT_SERVICE.database) CLOUDANT_URL = CLOUDANT_URL.substring(0, CLOUDANT_URL.length - CLOUDANT_DATABASE.length - 1);
var CLOUDANT_USERNAME = ( CLOUDANT_SERVICE.username );
var CLOUDANT_PASSWORD = ( CLOUDANT_SERVICE.password );

var express = require('express');
var passport = require('passport');
var app = express();
app.use(express.static(__dirname + '/static'));
app.use(express.bodyParser());
var sessionStore  = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ secret: "somesecretmagicword", store: sessionStore}));
app.use(passport.initialize());
app.use(passport.session());
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
Example #6
0
var server = express.createServer();
var dnode = require('dnode');

//var orm = require('./lib/orm');
// not yet, see im-w for example invocation fro services

// if local ?
//server.use(express.logger());
server.use(express.cookieParser());

var sessionCookieMaxAge=365*24*60*60*1000; // 1 year
server.use(express.session({ 
  secret: "ekosekret",
  cookie: { 
    path:'/',
    // domain:'.dev.axialdev.net',
    httpOnly:false,
    maxAge: sessionCookieMaxAge
  }
}));

//CORS middleware - not using
if (0){
  var allowCrossDomain = function(req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET'); // 'GET,PUT,POST,DELETE'
      res.header('Access-Control-Allow-Headers', 'Content-Type');
      next();
  }
  server.use(allowCrossDomain);
}
Example #7
0
app.configure(function() {
  app.use(express.cookieParser());
  app.use(express.session({secret: 'secret', key: 'express.sid'}));
});
var browserid_init = require('../../connect-browserid').init,
    express = require('express');
var app = express.createServer();

var browserid = browserid_init({
    //audience: 'http://127.0.0.1:3030',
    audience: 'http://127.0.0.1:3030',
    debug: true,
    auth_next: '/',
    logout_next: '/'
});
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.use(express.bodyParser());
app.use(express.csrf());
app.use(function (req, resp, next) {
    resp.local('csrf', req.session._csrf);
    next();
});
app.configure('development', function(){
    // A common error when developing locally is hitting your server as
    // http://127.0.0.1:3000 but setting up your audience as
    // http://dev.example.com:3000
    app.use(browserid.guarantee_audience);
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.use(browserid.authUser);
app.post('/auth', browserid.auth);
// Optional - use events to de-couple your app
browserid.events.on('login', function (email, req, resp) {
Example #9
0
var app = express()
var server = require( 'http' ).createServer( app )
var io = require( 'socket.io' ).listen( server )
var path = require( 'path' )

var port = (process.env.PORT || 8081)

//Setup Express
app.set( 'views', path.join( __dirname, '../views' ) )
app.set( 'view engine', 'jade' );
app.use( express.favicon() );
app.use( express.logger() )
app.use( express.compress() )
app.use( express.bodyParser() )
app.use( express.cookieParser() )
app.use( express.session( { secret: "m7g3MClazRYLCPnqqTU00QIbJEDH"} ) )
app.use( app.router )
app.use( express.static( path.join( __dirname, '../static' ) ) )
app.use( express.errorHandler() )

//Setup Socket.IO
//io.sockets.on('connection', function (socket) {
//    console.log('Client Connected');
//    socket.on('message', function (data) {
//        socket.broadcast.emit('server_message', data);
//        socket.emit('server_message', data);
//    });
//    socket.on('disconnect', function () {
//        console.log('Client Disconnected.');
//    });
//});
Example #10
0
var sys = require("sys"),
    express = require("express"),
    engine = require("ejs-locals"),
    db = require("./mydb"),
    formidable = require("formidable"),
    log = require("./public/js/log").getLogger(0),
    utils = require("./public/js/utils");
    
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
    
var app = express();
app.use(express.cookieParser());
app.use(express.session({secret: "proud in the cloud foundry"}));
app.use(app.router);
app.use(express.static(__dirname + "/public"));

app.engine("ejs", engine);

app.configure(function() {
    app.set("views", __dirname + "/tmpl");
    app.set("view engine", "ejs");
});

/**
 * Bind a closure for pagename context
 * @param pname the name of the page
 */
var context = function(pname) {
Example #11
0
var express = require('express'),
app = express(),
port = process.env.PORT || 8080,
mongoose = require('mongoose'),
MongoStore = require('connect-mongo')(express),
ioSession = require('socket.io-session')

var sessionKey = 'secret key'
var memoryStore = new MongoStore({ db: 'mongodb', url: 'mongodb://localhost/whisperchat' });

app.use(express.cookieParser());
app.use(express.session({ secret: sessionKey, store: memoryStore }));

module.exports = function(app,io){
	app.get('/', function(req, res){
		res.render('home');
	});
	app.get('/create', function(req,res){
		var id = Math.round((Math.random() * 1000000));
		res.redirect('/chat/'+id);
	});
	app.get('/chat/:id', function(req,res){
		res.render('chat');
	});

	io.set('authorization', ioSession(express.cookieParser(sessionKey), memoryStore));

	// Initialize a new socket.io application, named 'chat'
	var chat = io.of('/socket').on('connection', function (socket) {

		console.log(socket.handshake.session);
Example #12
0
    /*jslint camelcase: false*/
    auth_pass: app.config.redis.pass
    /*jslint camelcase: true*/
  }
);

var RedisStore = require('connect-redis')(express);
app.sessionStore = new RedisStore({
  client: redis,
  prefix: 'crypton.sid:'
});

app.use(express.session({
  secret: app.secret,
  store: app.sessionStore,
  key: 'crypton.sid',
  cookie: {
    secure: true
  }
}));

app.use(express.logger(function (info, req, res) {
  var color = 'green';

  if (res.statusCode == 404) {
    color = 'red';
  }

  var line = res.statusCode.toString()[color] + ' ' + req.method + ' ' + req.url;
  app.log('info', line);
}));
Example #13
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);
 });
Example #14
0
  app.config.init(function (err) {

    if (err) {
      return console.error(err.message);
    }

    // Default Theme
    calipso.defaultTheme = app.config.get('themes:default');

    app.use(express.bodyParser());
    // Pause requests if they were not parsed to allow PUT and POST with custom mime types
    app.use(function (req, res, next) {
      if (!req._body) {
        req.pause();
      }
      next();
    });
    app.use(express.methodOverride());
    app.use(express.cookieParser(app.config.get('session:secret')));
    app.use(express.responseTime());

    // Create dummy session middleware - tag it so we can later replace
    var temporarySession = app.config.get('installed') ? {} : express.session({ secret:"installing calipso is great fun" });
    temporarySession.tag = "session";
    app.use(temporarySession);

    // Create holders for theme dependent middleware
    // These are here because they need to be in the connect stack before the calipso router
    // THese helpers are re-used when theme switching.
    app.mwHelpers = {};

    calipso.auth = {
      password:app.config.get('server:authentication:password'),
      migrate2pbkdf2:app.config.get('server:authentication:migrate2pbkdf2')
    };
    if (calipso.auth.password === undefined) {
      app.config.set('server:authentication:password', true);
      calipso.auth.password = true;
    }
    if (calipso.auth.migrate2pbkdf2 === undefined) {
      app.config.set('server:authentication:migrate2pbkdf2', false);
      calipso.auth.migrate2pbkdf2 = false;
    }

    var appId = app.config.get('server:authentication:facebookAppId');
    var appSecret = app.config.get('server:authentication:facebookAppSecret');
    if (appId && appSecret) {
      calipso.auth.facebook = true;
      everyauth
        .facebook
        .myHostname(app.config.get('server:url'))
        .getSession(function (req) {
          if (!req.session) {
            req.session = { _pending:req };
          } else {
            req.session._pending = req;
          }
          return req.session;
        })
        .appId(appId)
        .appSecret(appSecret)
        .findOrCreateUser(function (sess, accessToken, accessTokenExtra, fbUserMetadata) {
          var promise = this.Promise();

          return calipsoFindOrCreateUser({username:'facebook:' + fbUserMetadata.username,
            email:fbUserMetadata.username + '@facebook.com', name:fbUserMetadata.name}, sess, promise);
        })
        .redirectPath('/');
    }

    var consumerKey = app.config.get('server:authentication:twitterConsumerKey');
    var consumerSecret = app.config.get('server:authentication:twitterConsumerSecret');
    if (consumerKey && consumerSecret) {
      calipso.auth.twitter = true;
      everyauth
        .twitter
        .getSession(function (req) {
          if (!req.session) {
            req.session = { _pending:req };
          } else {
            req.session._pending = req;
          }
          return req.session;
        })
        .myHostname(app.config.get('server:url'))
        .apiHost('https://api.twitter.com/1')
        .consumerKey(consumerKey)
        .consumerSecret(consumerSecret)
        .findOrCreateUser(function (sess, accessToken, accessSecret, twitUser) {
          var promise = this.Promise();

          return calipsoFindOrCreateUser({username:'twitter:' + twitUser.screen_name,
            email:twitUser.screen_name + '@twitter.com', name:twitUser.name}, sess, promise);
        })
        .redirectPath('/');
    }

    var clientId = app.config.get('server:authentication:googleClientId');
    var clientSecret = app.config.get('server:authentication:googleClientSecret');
    if (clientId && clientSecret) {
      calipso.auth.google = true;
      everyauth
        .google
        .myHostname(app.config.get('server:url'))
        .appId(clientId)
        .appSecret(clientSecret)
        .scope('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email')
        .getSession(function (req) {
          if (!req.session) {
            req.session = { _pending:req };
          } else {
            req.session._pending = req;
          }
          return req.session;
        })
        .findOrCreateUser(function (sess, accessToken, extra, googleUser) {
          googleUser.refreshToken = extra.refresh_token;
          googleUser.expiresIn = extra.expires_in;

          var promise = this.Promise();

          return calipsoFindOrCreateUser({username:'google:' + googleUser.email,
            email:googleUser.email, name:googleUser.name}, sess, promise);
        })
        .redirectPath('/');
    }

    app.use(everyauth.middleware());

    // Load placeholder, replaced later
    if (app.config.get('libraries:stylus:enable')) {
      app.mwHelpers.stylusMiddleware = function (themePath) {
        var mw = stylus.middleware({
          src:themePath + '/stylus',
          dest:themePath + '/public',
          debug:false,
          compile:function (str, path) { // optional, but recommended
            return stylus(str)
              .set('filename', path)
              .set('warn', app.config.get('libraries:stylus:warn'))
              .set('compress', app.config.get('libraries:stylus:compress'));
          }
        });
        mw.tag = 'theme.stylus';
        return mw;
      };
      app.use(app.mwHelpers.stylusMiddleware(''));
    }

    // Static
    app.mwHelpers.staticMiddleware = function (themePath) {
      var mw = express["static"](themePath + '/public', {maxAge:86400000});
      mw.tag = 'theme.static';
      return mw;
    };
    // Load placeholder, replaced later
    app.use(app.mwHelpers.staticMiddleware(''));

    // Core static paths
    app.use(express["static"](path + '/media', {maxAge:86400000}));
    app.use(express["static"](path + '/lib/client/js', {maxAge:86400000}));

    // Translation - after static, set to add mode if appropriate
    app.use(translate.translate(app.config.get('i18n:language'), app.config.get('i18n:languages'), app.config.get('i18n:additive')));

    // Core calipso router
    calipso.init(app, function () {
      // Add the calipso mw
      app.use(calipso.routingFn());

      // return our app refrerence
      next(app);

    })

  });
Example #15
0
 * License for the specific language governing permissions and limitations under
 * the License.
 */

var express = require('express');
var mu = require('mu2');
var util = require('util');
var http = require('http');
var https = require('https');
var D2L = require('../../lib/valence.js');

var app = express();
var store = new express.session.MemoryStore;

app.use(express.cookieParser());
app.use(express.session({ secret: 'SuperSecretKeyForCookies', store: store }));

function setProps(req, update) {
    req.session.props = req.session.props || {};
    var props = req.session.props;

    if(typeof props.Scheme === 'undefined') props.Scheme = 'https';
    else if(update) props.Scheme = req.param('schemeField') ? 'https' : 'http';
    props.HTTPS = props.Scheme === 'http' ? '' : 'checked="true"';

    props.Host = req.param('hostField') || props.Host || 'valence.desire2learn.com';
    props.Port = req.param('portField') || props.Port || '443';

    props.AppKey = req.param('appKeyField') || props.AppKey || 'ybZu7fm_JKJTFwKEHfoZ7Q';
    props.AppID = req.param('appIDField') || props.AppID || 'G9nUpvbZQyiPrk3um2YAkQ';
Example #16
0
        console.log(message.fullyFormattedMessage, level);
    }
});

app.set('port', process.env.PORT || 3001);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use('/upload', upload.fileHandler());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({"secret": "ajaySecret"}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.configure('development', function () {
    express.errorHandler.title = _config.appName;
    app.use(express.errorHandler());
});

//Export the bcrypt via getter in global
global.__defineGetter__("bcrypt", function () {
    return bcrypt;
});
var express = require('express')
  , passport = require('passport')
  , site = require('./site')
  , oauth2 = require('./oauth2')
  , user = require('./user')
  , partials = require('express-partials')
  
// Express configuration
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(partials());
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

// Passport configuration
require('./auth');

app.get('/', site.index);
app.get('/login', site.loginForm);
app.post('/login', site.login);
app.get('/logout', site.logout);
app.get('/account', site.account);

app.get('/dialog/authorize', oauth2.authorization);
Example #18
0
var initRoutes = require('./lib/init-routes');

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

/* --- pipeline begins */
app.use(initMongo.connect);
app.use(initRoutes);
app.use(express.logger(':remote-addr -> :method :url [:status]'));
app.use(express.favicon());
app.use(express.static(__dirname + '/static'));
app.use('/less', less(__dirname + '/less'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
  store : new RedisStore({host: 'localhost', port: 6379}),
  secret: 'change-this-to-a-super-secret-message',
  cookie: { maxAge: 24 * 60 * 60 * 1000 }
}));
app.use(app.router);
/* --- pipeline ends   */

var server = require('http').createServer(app);
server.listen(port, function(){
  console.log('Node server listening. Port: ' + port + ', Database: ' + dbname);
});

module.exports = app;

Example #19
0
var http    = require("http");
var async   = require('async');
var express = require('express');
var util    = require('util');

// Create an express webserver
var app = express();
app.use(express.logger());
app.use(express.compress());
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: process.env.SESSION_SECRET || 'secret123' }));
app.use(require('faceplate').middleware({
        app_id: 581546131861642,
        secret: "9d39b7d873b6b6d3ed27d536d05ad47b",
        scope:  'user_likes,user_photos,user_photo_video_tags'
    }));

// Set default template engine to Handlebars.js using hbs package.
// Add html filetype as template for development.
app.set('view engine', 'hbs');
app.engine('html', require('hbs').__express);

// Launch server.
var port = process.env.PORT || 4444;
http.createServer(app).listen(port);

console.log("Running on " + port);

// Render the index page.
Example #20
0
  base.configure(function() {
    
    base.set('port', process.env.PORT || 3000);
    
    base.set('views', path.join(rootDir, 'views')); // use appRootDir/views as template directory
    //~ 
    //~ ejs.open = '{{';
    //~ ejs.close = '}}';

    require(path.join(__dirname, 'ejsfilters'))();
    
    base.set('view engine','ejs');  // use the EJS node module
      
    base.use(express.favicon(path.join(rootDir, '/public/images/favicon.ico')));
    
    function compile(str, path) {
      return stylus(str)
        .set('filename', path)
        .set('compress', true);
        //.use(nib());
    }

    base.use(stylus.middleware({
        src: rootDir + '/public/'
      , compile: compile
    }));
    
    base.use(express.static(path.join(rootDir, 'public')));
    
    base.use(express.logger('dev'));
    
    base.use(express.compress());
    base.use(express.cookieParser('etgvwezgwegwgwgw'));
    base.use(express.bodyParser());
    base.use(express.methodOverride());
    
    base.use(express.session());
    // Initialize Passport!  Also use passport.session() middleware, to support
    // persistent login sessions (recommended).
    base.use(passport.initialize());
    base.use(passport.session());
    
    
    
    //custom middleware to get all base.locals that we need...
    base.use(function(req,res,next) {
      
      base.locals.utils = utils;
    
      mongoose.model("PageData")
      .findOne({"values.appname": "base"}, function(err, pageData) {
        
        if(!pageData) {
        
          if(req.path.indexOf('setup') === -1) {
            res.redirect('/setup');
            return;
          }
        
        }
        if(pageData && pageData.values) {
          base.locals.pageData = pageData.values;
        }
        
        next();
      });      
    });

    //custom middleware to get all base.locals that we need...
    base.use(function(req,res,next) {
     
      mongoose.model("MenuItem").find({}, function(err, menuItems) {
        
        console.log('menuITems in base middleware=');
        console.log(menuItems);
        
        var mIs = {
            header: []
          , footer: []
        }
        
        utils.each(menuItems, function(mI){
          console.log('saving menuitem to ');
          console.log(mI.value);
          //~ mIs[mI.value.values.menu].push(mI.value.values);
        });
        
        if(utils.count(mIs) > 0 ) {
          base.locals.menuItems = mIs;
        }
        next();
      });      
    });
    
    
    //add custom plugin middleware from bonobo if any is there.
    utils.each(bonobo.middleWare, function(mW) {
      if(typeof mW === 'function' ) {
        base.use(mW);
      }
    });
    //route page calls last
    base.use(base.router);

  });
Example #21
0
require.paths.unshift(__dirname + '/lib');

var cradle  = require('cradle');
var express = require('express');
var fs      = require('fs');
var spawner = require('spawner').create();
var sys     = require('sys');
var uuid    = require('node-uuid');

var app = express.createServer(
  express.logger(),
  express.cookieParser(),
  express.session({ secret: process.env.SECRET || 'secret' }),
  require('connect-form')({ keepExtensions: true })
);

// connect to couchdb
var couchdb_url = require('url').parse(process.env.CLOUDANT_URL);
var couchdb_options = couchdb_url.auth ?
  { auth: { username: couchdb_url.auth.split(':')[0], password: couchdb_url.auth.split(':')[1] }  } :
  { }
var db = new(cradle.Connection)(couchdb_url.hostname, couchdb_url.port || 5984, couchdb_options).database('make');
db.create();

// POST /make starts a build
app.post('/make', function(request, response, next) {

  // require a form
  if (! request.form) {
    response.write('invalid form');
    response.send(500);
Example #22
0
app.set('views', path.join(__dirname, 'views'));//设置views文件夹为存放视图文件的目录
app.set('view engine', 'ejs');//设置视图模块引擎为ejs
app.use(flash());
app.use(express.favicon());//使用默认的favicon图标
app.use(express.logger('dev'));//在终端显示日志

// app.use(express.json());
// app.use(express.urlencoded());
app.use(express.bodyParser());//表单的时候用
app.use(express.methodOverride());//协助出来POST请求

app.use(express.cookieParser());
app.use(express.session({
	secret: settings.cookieSecret,
	key: settings.db,//cookie name
	cookie: {maxAge: 1000*60*60*24*30},//30 days
	store: new MongoStore({
		db: settings.db
	})
}));

app.use(app.router);//调用路由解析的规则
app.use(express.static(path.join(__dirname, 'public')));

// development only  错误处理 输出错误信息
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// app.get('/', routes.index); //控制路由器
// app.get('/users', user.list);
Example #23
0
// app.set('view engine', 'ejs');
app.set('view engine','html');//使用原生html
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.bodyParser({ keepExtensions: true, uploadDir: './public/upload' }));
app.use(express.methodOverride());
app.use(express.cookieParser());

//session相关
app.use(express.session({
	secret : config.cookieSecret,
	cookie : {
		maxAge : 60000 * 30	//30 minutes
	},
	store : new MongoStore({ 
		url:config.connectString
	})
}));

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

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

routes(app);
Example #24
0
app.configure(function() {
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
});
Example #25
0
var express = require('express');
var MedeaStore = require('../')(express);

var app = express();

var sessionStore = new MedeaStore();

app.use(express.cookieParser());
app.use(express.session({ store: sessionStore, secret: 'choopa_the_cat', cookie: { maxAge: 30000 } }));

app.get('/', function(req, res) {
  res.send('Hello World!');
});

app.listen(3000);

console.log('Listening on http://localhost:3000...');
Example #26
0
var app = express();

//ejs
var pbc = path.join(__dirname, '../public/');
app.use(express.static(pbc));
app.set('views', pbc);
app.engine('html', require('ejs').renderFile);


app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());

app.use(express.session({
    secret: config.session.key,
    cookie: {
        _expires: config.session.maxAge
    }
}));

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

// all environments
app.set('port', config.server_config.port);
// app.set('view engine', 'jade');
app.use(express.favicon());
//app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(app.router);
Example #27
0
File: app.js Project: ksc4130/barn2
var connect = require('connect');
var secret = 'Askindl23@146Fscmaijnd523CXVWGN#63@#7efbsd23#$Rb';


var app = express();

// all environments
app.set('port', process.env.PORT || 4130);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({secret: secret, key: 'express.sid'}));app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

app.post('/yup', function(req, res){

});
Example #28
0
swig.setFilter('length', filters.length);
swig.setFilter('genLink', filters.genLink);
swig.setFilter('countFormat', filters.countFormat);
swig.setFilter('toString', filters.toString);
app.use(express.favicon(__dirname + '/web/favicon.ico'));
app.use('/upload/', express.static(settings.UPLOAD_DIR, {maxAge: maxAge}));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser(settings.COOKIE_SECRET));
// debug on win platform
// app.use(express.session({secret: settings.SESSION_SECRET}));
app.use(express.session({
    store: new RedisStore({
        host: settings.SESSION_HOST,
        port: settings.SESSION_PORT
    }),
    secret: settings.COOKIE_SECRET
}));
app.use(express.csrf());
app.use(function(req, res, next) {
    res.locals.token = req.session ? req.session._csrf : '';
    res.locals.env = app.settings.env;
    next();
});
app.use(connectDomain());
app.use(app.router);

routes(app);

app.use(function(err, req, res, next) {
Example #29
0
var routes = require('./routes');
var api = require('./routes/api');

var app = module.exports = express();
var server = http.createServer(app);

app.set('port', process.env.PORT || nconf.get('port'));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser( nconf.get('cookieKey') ));
app.use(express.session({ secret: nconf.get('sessionKey'), maxAge: new Date(Date.now() + 3600000) }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);

if (app.get('env') === 'development') {
  setTimeout(function() {
    setInterval(function() {
      var barcode = {
        left: '',
        right: '',
        event: Math.floor((Math.random()*2)+2)
      };
      var i = Math.floor((Math.random()*global.barcodes.length));
      barcode.left = global.barcodes[i].barcode;
      if (Math.random() < 0.1) barcode.left = 'none';
      //journalWrite(barcode);
Example #30
0
    , url = require('url')
    , fs = require('fs')
    , path = require('path')
    , ejs = require('ejs')
    , passport = require('passport')
    , FacebookStrategy = require('passport-facebook').Strategy
    , app = express()
    , Firebase = require('firebase')
    , config = require('./config'); //make sure it's pointing in the right direction. config.js doesn't sync w/ git

    
    var fbURL = config['FIREBASE_FORGE']; //firebase endpoint
    
    //Configure sessions and passport
    app.use(express.cookieParser(config['SESSION_SECRET'])); //make it a good one
    app.use(express.session({secret: config['SESSION_SECRET']}));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(express.favicon(__dirname + '/views/favicon.ico'));
    // Use the GitHubStrategy within Passport.
    //   Strategies in Passport require a `verify` function, which accept
    //   credentials (in this case, an accessToken, refreshToken, and GitHub
    //   profile), and invoke a callback with a user object.
    passport.use(new FacebookStrategy({
        clientID: config['FACEBOOK_CLIENT'],
        clientSecret: config['FACEBOOK_SECRET'],
        callbackURL: "http://localhost:3000/login/facebook/callback" //change for production
      },
      function(accessToken, refreshToken, profile, done) {
        // asynchronous verification, for effect...