Example #1
0
module.exports = function (app, config, passport) {
  app.set('showStackError', true);
  // should be placed before express.static
  app.use(express.compress({
    filter: function (req, res) {
      return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
    },
    level: 9
  }));

  app.use(stylus.middleware({
    src: config.root + '/app',
    dest: config.root + '/public',
    compile: function (str, path) {
      return stylus(str)
        .set('filename', path)
        .set('compress', config.app.compressCss)
        .use(nib())
        .import('nib');
    }
  }));

  app.use(express.static(config.root + '/public'));
  if (config.accessLog) {
    app.use(express.logger('dev'));
  }
  app.set('views', config.root + '/app/views');
  app.set('view engine', 'jade');

  app.configure(function () {
    // dynamic helpers
    app.use(helpers(config));

    // bodyParser should be above methodOverride
    app.use(express.bodyParser());
    app.use(express.methodOverride());

    // cookieParser should be above session
    app.use(express.cookieParser());
    //Mostly for testing, never for production code
    if (config.useMemorySessionStore) {
      app.use(express.session({ secret: config.sessionSecret }));
    } else {
      app.use(express.session({
        secret: config.sessionSecret,
        store: new MongoStore({
          url: config.db,
          collection : 'sessions'
        })
      }));
    }

    if (passport) {
      app.use(passport.initialize());
      app.use(passport.session());
    }

    if (config.accessControl) {
      app.use(function (req, res, next) {
        res.set('Access-Control-Allow-Origin', '*');
        res.set('Access-Control-Allow-Headers', 'Authorization, X-Requested-With');
        res.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
        res.set('Access-Control-Allow-Credentials', 'true');
        res.set('Access-Control-Max-Age', '3600');
        if ('OPTIONS' === req.method) { return res.send(200); }
        next();
      });
    }

    app.use(auth.requiresAuth);

    // routes should be at the last
    app.use(app.router);

    // use express favicon
    app.use(express.favicon(config.root + '/public/images/favicon.ico'));

    // custom error handler
    app.use(function (err, req, res, next) {
      if (err.message.indexOf('not found') > -1) {
        return next();
      }
      console.error(err);
      logger.log('error', 'UNCAUGHT EXCEPTION: %j', err);
      res.status(httpStatus.INTERNAL_SERVER_ERROR).render('500', { title: 'Justbrew' });
    });

    app.use(function (req, res) {
      res.status(httpStatus.NOT_FOUND).render('404', {title: 'Justbrew', url: req.originalUrl });
    });

  });
};
Example #2
0
//     });
//   }
// };

// Setup express
if (!process.NODE_ENV) {
  app.use(express.logger());
}

var cookieParser = express.cookieParser(nconf.get('sessionSecret'));
app.use(cookieParser);

app.use(stylus.middleware({
  src: __dirname + '/public',
  compile: function compile(str, path) {
    return stylus(str)
      .set('filename', path)
      .use(nib());
  }
}));

// Static sources
var maxAge = process.NODE_ENV ? 86400000 : 0;
app.use(express.static(__dirname + '/public', {
  maxAge: maxAge
}));

var nap = require('nap');

nap({
  mode: 'development',
  assets: {
Example #3
0
File: index.js Project: 4nodejs/kue
    .set('filename', path)
    .use(nib());
}

// config

app.set('view options', { doctype: 'html' });
app.set('view engine', 'jade');
app.engine('jade', jade.renderFile);
app.set('views', __dirname + '/views');
app.set('title', 'Kue');
app.locals     = { inspect: util.inspect };

// middlewares

app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }));
app.use(express.static(__dirname + '/public'));

// JSON api

app.get('/stats', provides('json'), json.stats);
app.get('/job/search', provides('json'), json.search);
app.get('/jobs/:from..:to/:order?', provides('json'), json.jobRange);
app.get('/jobs/:type/:state/:from..:to/:order?', provides('json'), json.jobTypeRange);
app.get('/jobs/:type/:state/stats', provides('json'), json.jobTypeStateStats);
app.get('/jobs/:state/:from..:to/:order?', provides('json'), json.jobStateRange);
app.get('/job/types', provides('json'), json.types);
app.get('/job/:id', provides('json'), json.job);
app.get('/job/:id/log', provides('json'), json.log);
app.put('/job/:id/state/:state', provides('json'), json.updateState);
app.put('/job/:id/priority/:priority', provides('json'), json.updatePriority);
Example #4
0
appController.initPromise().done(function() {
  let config = configController.config;
  configController.print();

  app.configure(function() {
    // Attach the i18n property to the express request object
    // And attach helper methods for use in templates
    I18n.expressBind(app, {
        // setup some locales - other locales default to en silently
        locales: ['en', 'fr'],
        // change the cookie name from 'lang' to 'locale'
        cookieName: 'locale'
    });

    app.use(function(req, res, next) {
        req.i18n.setLocaleFromCookie();
        next();
    });
  });

  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', { layout: false, pretty: true });
  app.use(express.urlencoded())
     .use(express.bodyParser())
     .use(express.cookieParser())
     .use(express.json()) 
     .use(stylus.middleware({
       src: __dirname + '/public',
       compress: true
     }))
     .use(express.static(__dirname + '/public'))
     .use(express.session({
       secret: config.sessionSecret,
       store: new RedisStore({
         port: config.redisPort,
         host: config.redisHost,
       }),
       // Expire cookies by default 30 days from now
       cookie: { path: '/', httpOnly: true, maxAge: DAY * 30 }
     }))
     .use(function(req, res, next) {
        // session updated
        // Allow the session variables to be accessible from res.locals
        // session contains:
        //   email
        //   isAdmin
        res.locals.session = req.session;
        if (res.locals.session.isAdmin === undefined)
          res.locals.session.isAdmin = false;
        res.locals.session.serverRunningSince = serverRunningSince;

        //console.log(req.url);

        // Allowed to modify session
        if (req.url == '/persona/verify' || req.url == '/persona/logout') {
          console.log('Request for: ' + req.url);
        } else {
          req.session = null;
        }
         
        next();
     });

  let serverURL = 'http://' + config.host +
    (config.port == 80 ? '' : (':' + config.port));
  console.log('server callback URL for Persona: ' + serverURL);
  require('express-persona')(app, {
    audience: serverURL,
    verifyResponse: function(error, req, res, email) {
      if (error) {
        res.json({ status: 'failure', reason: error });
      } else {

        // Session vars that our server should know about
        req.session.isAdmin = false;
        config.admins.forEach(function(e) {
          req.session.isAdmin = req.session.isAdmin || req.session.email == e;
        });
        req.session.isTrusted =  req.session.isAdmin;

        console.log('User logged in: ' + req.session.email);
         let ip = req.connection.remoteAddress;
         if (ip == '127.0.0.1' &&
             config.host == 'codefirefox.com') {
           ip = req.get('HTTP_X_FORWARDED_FOR');
         }
        userController.reportUserLogin(req.session.email, ip, function(err) {
          // Stuff to let the client know about
          res.json({
                    isAdmin: req.session.isAdmin,
                    isTrusted: req.session.isTrusted,
                    status: err ? 'failure' : 'okay',
                    reason: err,
                    email: req.session.email
                  });
        });
      }
    },
  });

  // GET
  app.get('/', routes.outline);
  app.get('/videos', routes.outline);
  app.get('/exercises', routes.outline);
  app.get('/tagged/:tagged', routes.outline);
  app.get('/comments/:slug', routes.comments);
  app.get('/user/info.json', routes.userInfo);
  app.get('/video/:video', routes.video);
  app.get('/lesson/:slug', routes.lesson);
  app.get('/exercise', routes.exerciseDemo);
  app.get('/exercise/:exercise', routes.exercise);
  app.get('/:category/:video', routes.video);
  app.get('/cheatsheet', routes.cheatsheet);
  app.get('/initData', routes.initData);
  app.get('/about', routes.about);
  app.get('/profile', routes.profile);
  app.get('/admin', routes.admin);
  app.get('/tags', routes.tags);
  app.get('/rss', routes.rss);

  // POST
  app.post('/check-code/:slug', routes.checkCode);
  app.post('/comments/:slug', routes.postComment);
  app.post('/user/info.json', routes.postUserInfo);
  app.post('/video/:slug', routes.completedLesson);
  app.post('/exercise/:slug', routes.completedLesson);

  // DELETE
  app.del('/profile', routes.delProfile);
  app.del('/comments/:slug/:id', routes.delComment);

  app.use(function(req,res){
    res.render('notFound');
  });

  // Determine the environment like this: NODE_ENV=production node app.js
  app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
    app.locals.pretty = true;
  });

  app.configure('production', function(){
    app.use(express.errorHandler());
    process.on('uncaughtException', function (exception) {
      console.error(exception);
    });
  });

  app.listen(config.internalPort, function() {
    console.log('Starting server on port %d in %s mode', config.internalPort, app.settings.env);
  });
}, function onFailure(err) {
Example #5
0
 * To change this template use File | Settings | File Templates.
 */

var util = require('util'),
    connect = require('connect'),
    port = 8000,
    stylus = require("stylus"),
    axis = require("axis-css");


var server = connect();


function compile(str, path) {
    util.puts("compiling stylus");
    return stylus(str)
        .set('filename', path)
        .use(axis());
}

server.use(stylus.middleware({
    src: __dirname
    , compile: compile
}));
server.use(connect.static(__dirname));
server.listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');


Example #6
0
File: app.js Project: Astraport/njs
app.configure(function () {
  app.use(stylus.middleware({ src: __dirname + '/public' }))
  app.use(express.static(__dirname + '/public'));
  app.set('views', __dirname);
  app.set('view engine', 'jade');
});
Example #7
0
app.set('env','development')

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(session({ secret: 'lksjiwKsd23sNS4Na'}));

app.use(stylus.middleware({
    src: __dirname + '/',
    dest: __dirname + '/public/',
    debug: true,
    force: true,
    compile: function compile(str, path) {
        return stylus(str)
        .set('filename', path)
        .set('compress', true)
        .use(nib()).use(jeet()).use(typeUtils()).use(fontFace()).use(autoprefixer()).use(flatuicolors())
    }
}));


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


app.use('/', routes);

var shared = ['underscore','superagent'];
app.get('/js/bundle.js', browserify(shared));
Example #8
0
      pass: appConfig.redis.password
    };
    app.use(express.session({ secret: "dillinger", cookie: { maxAge: 60000*( (60*24) * 30)}, store: new RedisStore(redisOptions) })); // 30 days
    require('./routes').add(app);
    init();
  });
});

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
//app.use(express.session({ secret: "dillinger", cookie: { maxAge: 60000*( (60*24) * 30)}})); // 30 days
app.use(stylus.middleware({
  src: __dirname + "/public",
  compile: !appConfig.debug
}));
app.use(express.static(__dirname + '/public'));

app.dynamicHelpers({
    readme: function(req,res)
    {
      return dillingerReadme.toString();
    }// end readme
});
function initRedis(){
  var redisClient = redis.createClient(appConfig.redis.port, appConfig.redis.host, appConfig.redis);

  redisClient.on("error", function (err) {
      console.log("Redis connection error to " + redisClient.host + ":" + redisClient.port + " - " + err);
  });
Example #9
0
var stylus = require('stylus'),
    express = require('express'),
    path = require('path'),
    pugstore = require('./store/pug'),
    view = require('./view')
    app = express(),
    port = process.env.PORT || 3000,
    errorHandler = require('errorhandler');

app.set('view engine', 'jade');

if ('development' == app.get('env')) {
  app.use(stylus.middleware({ src: path.join(__dirname, 'public') }));
  app.use(express.static(path.join(__dirname, '/public')));
  app.use(errorHandler({ dumpExceptions: true, showStack: true }));
}

if ('production' == app.get('env')) {
  var oneYear = 31557600000;

  app.use(stylus.middleware({ src: path.join(__dirname, 'public'), compress: true }));
  app.use(express.static(path.join(__dirname, '/public'), { maxAge: oneYear }));
  app.use(errorHandler());
}

app.get('/',
  pugstore.find(1),
  view.photo);

app.get('/:server/:size/:key.:format',
  pugstore.findByName('server', '', 'key', 'size', 'format'),
Example #10
0
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Before executing this, you have to make sure permissions are set correctly,
 * or the workshopper doesn't work:
 *     chmod -R 0777 \
 *     /usr/local/lib/node_modules/expressworks/problems/stylish_css/public
 */

var express = require('express')                                              
var app = express()

// Require stylus CSS generator
var stylus = require('stylus')

// Add middleware that parses stylus stylesheets
app.use(stylus.middleware(process.argv[3]))

// Middleware that serves everything else.
app.use(express.static(process.argv[3]))

// Port is specified by `process.argv[2]`
app.listen(Number(process.argv[2]))
Example #11
0
var app = express();

// 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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(stylus.middleware(
                  {
                 src: __dirname + '/stylus',
                 dest: __dirname + '/public/stylesheets'
                 }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
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 #12
0
app.configure(function() {
  var coffee = require('coffee-script')
    , uglify_jsp = require("uglify-js").parser
    , uglify_pro = require("uglify-js").uglify
    , stylus = require('stylus');

  app.use(stylus.middleware({
    src: app.paths.public,
    dest: app.paths.public,
    compile: function(str, path) {
      return stylus(str)
        .set('compress', true)
        .set('filename', path)
        .set('paths', [ __dirname, app.paths.public ]);
    }
  }));

  var assetManager = require('connect-assetmanager')({
    js: {
      route: /\/javascripts\/[a-z0-9]+\/all\.js/,
      path: __dirname + '/../public/javascripts/',
      dataType: 'javascript',
      debug: true,
      preManipulate: {
        '^': [
          function(file, path, index, isLast, callback) {
            callback(file.replace(/#socketIoPort#/g, env.port));
          }
          , function(file, path, index, isLast, callback) {
            if (/\.coffee$/.test(path)) {
              callback(coffee.compile(file));
            } else {
              callback(file);
            }
          }
        ]
      },
      files: [ // order matters here
        'polyfills.js',
        'vendor/hoptoad-notifier.js',
        'vendor/hoptoad-key.js',
        'vendor/json2.js',
        'vendor/jquery-1.6.2.js',
        'vendor/jquery.ba-hashchange.js',
        'vendor/jquery.border-image.js',
        'vendor/jquery.infinitescroll.js',
        'vendor/jquery.keylisten.js',
        'vendor/jquery.pjax.js',
        'vendor/jquery.transform.light.js',
        'vendor/jquery.transloadit2.js',
        'vendor/md5.js',
        'application.coffee',
        '*'
      ]
      , 'postManipulate': {
        '^': [
          function(file, path, index, isLast, callback) {
            if (env.production) {
              var ast = uglify_jsp.parse(file);
              ast = uglify_pro.ast_mangle(ast);
              ast = uglify_pro.ast_squeeze(ast);
              callback(uglify_pro.gen_code(ast, { beautify: true, indent_level: 0 }));
            } else {
              callback(file);
            }
          }
        ]
      }
    }
  });
  app.use(assetManager);
  app.helpers({ assetManager: assetManager });
});
Example #13
0
var app = express();

var exphbs = require('express-handlebars');
var hbsHelpers = require('./lib/helpers/handlebars');
var stylus = require('stylus');

// Loading config
global.$config = require('./lib/config');

if (!$config().html.css.stylusPreCompile) {
    // Set and configurate stylus middleware
    app.use(
        stylus.middleware({
            src: __dirname + '/stylus',
            dest: __dirname + '/public/css',
            compile: function(str, path) {
                return stylus(str).set('filename', path).set('compress', true);
            }
        })
    );
}

// Handlebars setup
app.engine($config().views.engine, exphbs({
    extname: $config().views.extension,
    defaultLayout: $config().views.layout,
    layoutsDir: __dirname + '/views/layouts',
    partialsDir: __dirname + '/views/partials',
    helpers: hbsHelpers
}));
Example #14
0
var express = require("express"),
    app = express.createServer(),
    csv = require("csv"),
    stylus = require("stylus"),
    scheduleFile = __dirname + "/data/schedule.csv",
    port = process.env.PORT || 8080;

app.set("view engine", "jade");

app.use(stylus.middleware({
  src: __dirname + "/public",
  dest: __dirname + "/public"
}));

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

app.get("/", function (req, res) {
  var events = [];

  csv()
    .fromPath(scheduleFile)
    .on("data", function (data) {
      events.push({
        start: data[0],
        end: data[1],
        room: data[2],
        title: data[3],
        speaker: data[4],
        description: data[5]
      });
    })
Example #15
0
// all environments
app.set('port', process.env.PORT || 1337);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({secret: 'password'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(stylus.middleware({
  src: path.join(__dirname, 'public'),
  compile: compile
}));
app.use(express.static(path.join(__dirname, 'public')));


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

app.get('/', indexController.index);
app.get('/random-background', photosController.randomBackground);
app.get('/login', authController.login);
app.get('/register', authController.register);
app.get('/user/:id', authController.ensureAuthenticated, userController.userProfile);
app.get('/profile/:userSlug', authController.ensureAuthenticated, userController.userView);
Example #16
0
    User = new Schema({
      email: String,
      projects: [Project],
    }),
    UserModel = mongoose.model( 'User', User );

if ( !path.existsSync( PUBLISH_DIR ) ) {
  fs.mkdirSync( PUBLISH_DIR );
} 

app.use(express.logger(CONFIG.logger))
  .use(express.bodyParser())
  .use(express.cookieParser())
  .use(express.session(CONFIG.session))
  .use(stylus.middleware({
    src: WWW_ROOT
  }))
  .use(express.static( WWW_ROOT ))
  .use(express.static( PUBLISH_DIR ))
  .use(express.directory( WWW_ROOT, { icons: true } ) );

require('express-browserid').plugAll(app);

function publishRoute( req, res ){
  var email = req.session.email || DEFAULT_USER,
      id = req.params.id;

  if (!email) {
    res.json({ error: 'unauthorized' }, 403);
    return;
  }
Example #17
0
'use strict';

var express = require('express');
var stylus  = require('stylus');

var app = module.exports = exports = express();

// Configuration

app.set('port', process.env.PORT || 8123);
app.set('views', './views');
app.set('view engine', 'jade');

// Middleware

app.use(require('morgan')('dev'));

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

app.use(stylus.middleware({
	src: './public',
	compress: true
}));

// DOES'T WORK !!!!!!!!!!!!!!!!!!!!!!!!1
// app.use(express.logger('dev'));

// app.use(app.router);
Example #18
0
var express = require('express');
var stylus  = require('stylus');
var nib = require('nib');

var app = express();

app.use(stylus.middleware({
    src     : __dirname + '/public/assets/styl',
    dest    : __dirname + '/public/assets/css',
    compile : function(str, path) {
      return stylus(str)
        .set('filename', path)
        .set('warn', true)
        .set('compress', true)
        .use(nib());
    }
}));

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

app.listen(3000);
Example #19
0
    // this has to be the fully-qualified path to a folder, typically "/public",
    // where public/static assets will be served from
    absolutePathToPublicAssets = path.join(__dirname, 'public'),

    // this has to be the fully-qualified path to a folder, typically "/templates",
    // where view templates will be found
    absolutePathToViewFolder = path.join(__dirname, 'views'),

    db = require('./notes-mysql/models/index.js'),
    app = express();
    

app.use(bodyparser.json()); // for parsing application/json
app.use(bodyparser.urlencoded({extended: false}));
app.use(express.static(absolutePathToPublicAssets));
app.use(stylus.middleware(absolutePathToPublicAssets));
app.set('views', absolutePathToViewFolder);
app.set('view engine', 'jade');

app.get("/api/tags",function(req,res){

    db.Tags.findAll().then(function(tags){
        console.log("Sending back tags:\n" + JSON.stringify(tags) + "\n");
        res.json(tags);
    }).catch(function(err){
        console.log("got an error finding all tags: " + err);
        res.status(500).json(err);
    });

});
app.post("/api/tags",function(req,res){
Example #20
0
app.configure(function() {
  var user = process.env.ADMIN_USERNAME || 'user'
    , pass = process.env.ADMIN_PASSWORD || 'pass'
    , basicAuth = express.basicAuth(user, pass);
  
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  
  app.engine('.ejs', cons.ejs);
  app.engine('.html', cons.ejs);
  app.engine('.jade', cons.jade);
  
  app.enable('trust proxy');
  
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.compress());
  
  app.use(function(req, res, next) {
    var render = res.render;
    
    res.render = function() {
      var args = [].slice.call(arguments);
      args[1] = args[1] || {};
      args[1].layout = false // !!res.req.get('X-PJAX');
      args[1].pretty = true;
      // console.log(args[1]);
      return render.apply(res, args);
    };
    
    next();
  });
  
  app.use(stylus.middleware({
      src: path.join(__dirname, 'public')
    , compile: function(str, path) {
        return stylus(str)
          .set('filename', path)
          .use(nib());
      }
  }));
  
  if ('development' === app.get('env')) {
    app.use(function(req, res, next) {
      exec('make', next);
    });
  }
  if ('production' === app.get('env')) {
    app.use('/admin', basicAuth);
    exec('make', function(err, stdout, stderr) {
      console.log(stdout);
      console.log(stderr);
      console.log(' building components is done.');
    });
  }
  
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});
Example #21
0
      return moment(arguments).lang(req.i18n.getLocale());
    }
  });
  next();
});

// Notices
app.use(require('./notices'));

app.use(app.router);

app.use(stylus.middleware({
  src: publicPath,
  compile: function(str, path) {
    return stylus(str)
      .set('filename', path)
      .set('compress', true)
      .use(nib());
  }
}));

app.use(express.static(publicPath));

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

require('./routes/index');

mongoose.connect(conf.mongoURL, function(err) {
  if (err) {
Example #22
0
var express = require('express');
var routes = require('./routes/index');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
var stylus = require('stylus');
app.use(stylus.middleware(path.join(__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('/about', routes.about);
app.get('/contact', routes.contact);
http.createServer(app).listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});
//# sourceMappingURL=app.js.map
Example #23
0
models = require('../models')(mongoose);

mongoose.connect(config.db);
app = express();

app.set('views', path.join(__dirname, '..', 'views'));
app.set('view engine', 'jade');
app.use(require('serve-favicon')(path.join(__dirname, '..', '/public/favicon.ico')));
app.use(require('morgan')('combined'));
app.use(stylus.middleware({
    src: path.join(__dirname, '..', 'views')
  , dest: path.join(__dirname, '..', 'public')
  , compile: function(str, path){
    return stylus(str)
      .set('filename', path)
      .set('compress', false)
      .use(require('nib')())
      .import('nib');
  }
}));
app.use(express.static(path.join(__dirname, '..', 'public')));
app.use(express.static(path.join(__dirname, '..', 'bower_components')))
app.use(methodOverride('_method'));
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
app.use(require('cookie-parser')());
app.use(require('express-session')({
  secret: config.session_secret,
  resave: false,
  saveUninitialized: false
Example #24
0
/*
 * Module dependencies
 */
var express = require('express');
var stylus = require('stylus');
var nib = require('nib');
  
var app = express();
function compile(str, path) {
  return stylus(str)
    .set('filename', path)
    .use(nib());
}
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
//app.use(express.logger('dev'));
app.use(stylus.middleware(
  { src: __dirname + '/assets'
  , compile: compile
  }
));
app.use(express.static(__dirname + '/assets'));
app.get('/', function (req, res) {
  res.render('index',
  { title : 'Home' }
  )
});
app.listen(3000,function () {
  console.log('Example app listening on port 3000!');
});
Example #25
0
 * Express app
 */

var app = express();

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

app.use(express.compress());
app.use(express.logger('dev'));
app.use(express.favicon(__dirname + '/static/favicon.ico'));
app.use(stylus.middleware({
   src: __dirname + '/styles',
   dest: __dirname,
   compile: function(string, filePath) {
      return stylus(string)
         .set('filename', filePath)
         .set('compress', true)
         .use(nib());
   }
}));
app.use('/static', express.static(__dirname + '/static'));

// If the request subdomain does not correspond to a game, throw an error
app.use(function(request, response, next) {
   var gameName = request.headers.host.split('.')[0];
   var query = '   SELECT game.name                               \n' +
               '     FROM game                                    \n' +
               'LEFT JOIN game_alias                              \n' +
               '       ON game.id = game_alias.game_id            \n' +
               '    WHERE game.name = (?) OR game_alias.name = (?)\n' +
               ' GROUP BY game.id                                   ';
Example #26
0
    cookieParser = require('cookie-parser'),
    session      = require('express-session');

require('express-namespace')

var app = module.exports = express();

CoffeeScript.register();

var server = require('http').Server(app);
require('./apps/socket-io')(server)

// Configuration
app.use(stylus.middleware({
  src: __dirname + "/views",
  // It will add /stylesheets to this path.
  dest: __dirname + "/public"
}));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express);
app.set('view options', { layout: false });
app.set('port', 3001);
busboy.extend(app);
app.use(cookieParser());
app.use(session({
  secret: "KioxIqpvdyfMXOHjVkUQmGLwEAtB0SZ9cTuNgaWFJYsbzerCDn"
}));
app.use(require('connect-assets')());
app.use(express.static(__dirname + '/public'));
Example #27
0
app.set('view engine', 'pug');
//app.use(express.logger({stream: fs.createWriteStream(logHome + '/gruff.access.log', { flags: 'a' })}));
app.use(logger("combined"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//app.use(cookieParser);
app.use(session({
    secret: ':DP:DP:DP:DP',
    name: 'gruff',
    //store: sessionStore, // connect-mongo session store
    proxy: true,
    resave: false,
    saveUninitialized: true
}));
//app.use(methodOverride); -------------------- TODO: Figure out how to make this work
app.use(stylus.middleware({ src: __dirname + '/public' }));
//app.use(everyauth.middleware());
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/common'));

// Routes

app.get('/', routes.index);
app.get('/about', routes.about);
app.get('/contact', routes.contact);
app.get('/debates/new', routes.getNewDebate);
app.get('/debates/:id', routes.getDebate);
app.get('/debates/:id/titles', routes.getDebateTitle);
app.get('/debates/:id/descriptions', routes.getDebateDescription);
app.get('/feed', routes.feed);
app.get('/my/debates', routes.getMyDebates);
Example #28
0
process.env.mapEditorRoot = __dirname;
console.log('process.env.mapEditorRoot: ' + process.env.mapEditorRoot);

// mongodb
var DB = require('./datastore');
DB.startup(process.env.MONGODB_CONNSTR);

////////////////////////////////////////////////////////////////////////////
// define application
var app = express();
app.use(express.static(__dirname + '/public'))
    .use(express.favicon())
    .use(express.logger('dev'))
    .use(express.bodyParser())
    .use(express.methodOverride())
    .use(stylus.middleware(__dirname + '/public'))
    .use(express.cookieParser())
    .use(express.session({
        secret: 'heysb'
        }, function() {
        app.use(app.router);
    }))
    .use(passport.initialize())
    .use(passport.session())
    ;

app.configure( function () {
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
});
Example #29
0
    express     = require('express'),
    socket      = require('socket.io'),
    ejs         = require('ejs-locals'),
    stylus      = require('stylus'),
    uglify      = require("./uglify-middleware.js"),
    UserHandler = require("./user-handler.js").UserHandler,
    app         = express(),
    server      = http.createServer(app),
    io          = socket.listen(server);
    cht         = Date() + " [Chat] ";

// Configuration
app.engine('ejs', ejs);
app.set('view engine', 'ejs');
app.use(stylus.middleware({
  src: __dirname + "/assets",
  dest: __dirname + "/static"
}));
app.use(uglify.middleware({
  src:  __dirname + "/assets",
  dest: __dirname + "/static"
}));
app.use(express.static(__dirname + "/static"));

// Routes
app.get("*", function (req, res) {
  res.render("index");
});

// Log level
io.set('log level', 1);
module.exports = function(app, port, packagesPath, generalConfigManager) {

  //generalConfigManager.atlasboardAssetFolder and generalConfigManager.wallboardAssetFolder are injected in testing env.
  var atlasboard_assets_folder = generalConfigManager.atlasboardAssetFolder || path.join(__dirname, "../../assets");
  var wallboard_assets_folder = generalConfigManager.wallboardAssetFolder || path.join(process.cwd(), "assets");

  // -----------------------------------------
  // Web server configuration
  // -----------------------------------------
  app.configure(function() {
    app.set('port', port);
    app.use(express.logger('dev'));
    app.use(express.compress());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.errorHandler());
  });

  app.configure('development', function(){
    app.use(express.errorHandler());
  });

  var compiledAssetsFolder = path.join(wallboard_assets_folder, 'compiled');
  app.use(stylus.middleware({
    src: atlasboard_assets_folder,
    dest: compiledAssetsFolder,
    compile: function(str, path) { // optional, but recommended    
    return stylus(str)
      .set('filename', path)
      .set('warn', false)
      .set('compress', true)
      .use(nib());
    }
  }));

  // -----------------------------------------
  //  Expose both, wallboard assets and atlasboard assets.
  //  Wallboard assets take precedence
  // -----------------------------------------
  app.use(express.static(wallboard_assets_folder));
  app.use(express.static(compiledAssetsFolder));
  app.use(express.static(atlasboard_assets_folder));

  // -----------------------------------------
  //  Log
  // -----------------------------------------
  app.get("/log", function(req, res) {
    if (generalConfigManager.get("live-logging").enabled === true){
      web_logic.log(req, res);
    }
    else{
      res.end('live logging it disabled. Must be enabled in config file');
    }
  });

  // -----------------------------------------
  //  Fetch resources for specific widget
  // -----------------------------------------
  app.get("/widgets/resources", function(req, res) {
    web_logic.renderWidgetResource(path.join(process.cwd(), 'packages'), req.query.resource, req, res);
  });

  // -----------------------------------------
  //  Fetch JS for specific widget
  // -----------------------------------------
  app.get("/widgets/:widget/js", function(req, res) {
    web_logic.renderJsWidget(packagesPath, req.params.widget, req, res);
  });

  // -----------------------------------------
  //  Fetch HTML and CSS for specific widget
  // -----------------------------------------
  app.get("/widgets/:widget", function(req, res) {
    web_logic.renderHtmlWidget(packagesPath, req.params.widget, req, res);
  });


  // -----------------------------------------
  //  Entry point for a particular dashboard
  // -----------------------------------------
  app.get("/:dashboard", function(req, res) {
    web_logic.renderDashboard(packagesPath, req.params.dashboard, req, res);
  });

  // -----------------------------------------
  //  Entry point for a particular dashboard
  // -----------------------------------------
  app.get("/:dashboard/js", function(req, res) {
    web_logic.renderJsDashboard(packagesPath, wallboard_assets_folder, req.params.dashboard, req, res);
  });

  // -----------------------------------------
  // No address given - list all available dashboards
  // -----------------------------------------
  app.get("/", function(req, res) {
    web_logic.listAllDashboards(packagesPath, req, res);
  });

};