Example #1
0
module.exports = function(app, passport, db) {
  app.set("showStackError", true);

  //Prettify HTML
  app.locals.pretty = 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
    })
  );

  //Setting the fav icon and static folder
  app.use(express.favicon());
  app.use(express.static(config.root + "/public"));

  //Don't use logger for test env
  if (process.env.NODE_ENV !== "test") {
    app.use(express.logger("dev"));
  }

  //Set views path, template engine and default layout
  app.set("views", config.root + "/app/views");
  app.set("view engine", "jade");

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

  app.configure(function() {
    //cookieParser should be above session
    app.use(express.cookieParser());

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

    //express/mongo session storage
    app.use(
      express.session({
        secret: "tenthousand",
        store: new MongoStore({
          mongooseConnection: mongoose.connection
        })
      })
    );

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

    //dynamic helpers
    app.use(helpers(config.app.name));

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

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

    //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) {
      //Treat as 404
      if (~err.message.indexOf("not found")) return next();

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

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

    //Assume 404 since no middleware responded
    app.use(function(req, res, next) {
      res.status(404).render("404", {
        url: req.originalUrl,
        error: "Not found"
      });
    });
  });
};
Example #2
0
module.exports = function (env) {
  var express = require('express');
  var i18n = require('webmaker-i18n');
  var path = require('path');
  var app = express();
  var defaultLang = 'en-US';
  var csp = require('./csp');
  var messina = require('messina')('webmaker-events-2-' + env.get('NODE_ENV'));
  var wts = require('webmaker-translation-stats');
  var WebmakerAuth = require('webmaker-auth');

  var auth = new WebmakerAuth({
    loginURL: env.get('LOGIN_URL'),
    secretKey: env.get('SESSION_SECRET'),
    forceSSL: env.get('FORCE_SSL'),
    domain: env.get('COOKIE_DOMAIN')
  });

  app.use(require('prerender-node'));
  if (env.get('ENABLE_GELF_LOGS')) {
    messina.init();
    app.use(messina.middleware());
  } else {
    app.use(express.logger('dev'));
  }
  app.use(express.compress());
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(auth.cookieParser());
  app.use(auth.cookieSession());

  // Setup locales with i18n
  app.use( i18n.middleware({
    supported_languages: env.get('SUPPORTED_LANGS') || [defaultLang],
    default_lang: defaultLang,
    mappings: require('webmaker-locale-mapping'),
    translation_directory: path.resolve(__dirname, '../locale')
  }));

  // CSP
  app.use(csp({
    reportToHost: env.get('CSP_LOGGER'),
    eventsLocation: env.get('eventsLocation') || 'http://localhost:1989'
  }));

  // Static files
  app.use(express.static(path.join(__dirname, '../app')));

  // Health check
  var healthcheck = {
    version: require('../package').version,
    http: 'okay'
  };

  app.get('/healthcheck', function (req, res) {
    wts(i18n.getSupportLanguages(), path.join(__dirname, '../locale'), function(err, data) {
      if(err) {
        healthcheck.locales = err.toString();
      } else {
        healthcheck.locales = data;
      }
      res.json(healthcheck);
    });
  });

  // Login
  app.post('/verify', auth.handlers.verify);
  app.post('/authenticate', auth.handlers.authenticate);
  app.post('/create', auth.handlers.create);
  app.post('/logout', auth.handlers.logout);
  app.post('/check-username', auth.handlers.exists);

  // Serve up virtual configuration "file"
  var config = {
    version: require('../package').version,
    eventsLocation: env.get('eventsLocation') || 'http://localhost:1989',
    accountSettingsUrl: env.get('accountSettingsUrl') || 'https://login.webmaker.org/account',
    myMakesUrl: env.get('myMakesUrl') || 'https://webmaker.org/me',
    webmakerUrl: env.get('WEBMAKER_URL') || 'https://webmaker.org',
    ga_account: env.get('GA_ACCOUNT') || 'UA-XXXXX-X',
    ga_domain: env.get('GA_DOMAIN') || 'example.com'
  };

  app.get('/config.js', function (req, res) {
    config.lang = req.localeInfo.lang;
    config.direction = req.localeInfo.direction;
    config.defaultLang = defaultLang;
    config.langmap = i18n.getAllLocaleCodes();
    config.supported_languages = i18n.getSupportLanguages();
    res.setHeader('Content-type', 'text/javascript');
    res.send('window.eventsConfig = ' + JSON.stringify(config));
  });

 // Localized Strings
 app.get('/strings/:lang?', i18n.stringsRoute('en-US'));

  return app;
};
Example #3
0
 mockson.router.configure(function() {
     mockson.router.use(domain);
     
     // Middleware which turns off connections that are
     // using the Keep-Alive header to stay on when we want to stop the server.
     mockson.router.set("exiting", false);
     mockson.router.use(function(req, res, next) {
         // Sorry Keep-Alive connections, but we need to part ways
         if (true === mockson.router.settings.exiting === true) {
           req.connection.setTimeout(1);
         }
     
         next();
     });
     
     // Middleware to serves the connect favicon, or the favicon located by the given path.
     mockson.router.use(express.favicon());
     
     // Middleware which blocks requests when we're too busy
     mockson.router.use(function(req, res, next) {
       if (mockson.options.toobusy && toobusy()) {
         res.send(503, "Opppppppppps..... I'm busy right now, sorry.");
       } 
       else {
         next();
       } 
     });
     
     // Middleware to log requests with the given options or a format string.
     mockson.router.use(express.logger("dev"));
     
     // this.router.use(express.bodyParser());
     // switched to use express.urlencoded and express.json, instead of bodyParser
     // https://github.com/senchalabs/connect/wiki/Connect-3.0
     // 
     // Middleware to parse x-ww-form-urlencoded request bodies,
     // providing the parsed object as req.body using
     mockson.router.use(express.urlencoded());
     
     // Middleware to parse JSON request bodies, providing the
     // parsed object as req.body.
     mockson.router.use(express.json());
     
     // Middleware to provides faux HTTP method support.
     mockson.router.use(express.methodOverride());
     
     // Middleware to compress response data with gzip/deflate (support content-encoding methods).
     mockson.router.use(express.compress());
     
     // Enable CORS for everything
     var corsOptions;
     if (mockson.options.allowedDomains            && 
         0 < mockson.options.allowedDomains.length &&
         -1 === mockson.options.allowedDomains.indexOf("*")) {
             corsOptions = {
               origin: function(origin, callback){
                 var originIsAllowed = (-1 !== mockson.options.allowedDomains.indexOf(origin));
                 callback(null, originIsAllowed);
               }
             };
     }
     
     mockson.router.use(cors(corsOptions));
     mockson.router.options("*", cors(corsOptions));
     
     mockson.router.use(express.static(path.resolve(__dirname, "../client")));
     
     // Set the error handler
     mockson.router.use(function errorHandler(err, req, res, next) {
       mockson.logger.error("error on request %d %s %s: %j", process.domain.id, req.method, req.url, err);
       res.send(500, "Opppppppppps..... Something bad happened, sorry. :(");
       
       if (err.domain) {
         // should think about gracefully stopping & respawning the server
         // since an unhandled error might put the application into an unknown state
       }
     });
 });
Example #4
0
var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.compress()); //Compressor GZIP
app.use(express.staticCache()); //Static CACHE
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}
// app.engine('.html', require('ejs').renderFile);
// // app.set('view engine', 'html');
// app.get("/", function (req, res) {
//     console.log("get /");
//     res.redirect("home");
// });
// app.get('/users', user.list);
Example #5
0
    app = express(),
    http = require('http'),
    server = http.createServer(app),
    io = require('socket.io').listen(server);

io.configure(function () {
    io.set('transports', ['xhr-polling']);
    io.set('polling duration', 10);
});

// https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
io.enable('browser client minification');  // send minified client
io.enable('browser client etag');          // apply etag caching logic based on version number
io.enable('browser client gzip');          // gzip the file

app.use(express.compress()); // compress files using gzip

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

server.listen(process.env.PORT || 5000);

//-------------------------------------------------------------------------------------------------------------------------------

function escapeHTML(string) {
    return string.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function blank(string) { // http://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript
    return (!string || /^\s*$/.test(string));
}
Example #6
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
    }));

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

    //Don't use logger for test env
    if (process.env.NODE_ENV !== 'test') {
        app.use(express.logger('dev'));
    }




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

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

    app.configure(function() {
        //cookieParser should be above session
        app.use(express.cookieParser());

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

        var allowCrossDomain = function(req, res, next) {
            res.header('Access-Control-Allow-Origin', config.allowedDomains);
            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
            res.header('Access-Control-Allow-Headers', 'Content-Type');

            next();
        }

        app.use(allowCrossDomain);

        app.use(function(req, res, next) {
            var oneof = false;
            if(req.headers.origin) {
                res.header('Access-Control-Allow-Origin', req.headers.origin);
                oneof = true;
            }
            if(req.headers['access-control-request-method']) {
                res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
                oneof = true;
            }
            if(req.headers['access-control-request-headers']) {
                res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
                oneof = true;
            }
            if(oneof) {
                res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
            }

            // intercept OPTIONS method
            if (oneof && req.method == 'OPTIONS') {
                res.send(200);
            }
            else {
                next();
            }
        });

        //express/mongo session storage
        app.use(express.session({
            secret: 'MEAN',
            store: new mongoStore({
                url: config.db,
                collection: 'sessions'
            })
        }));

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

        //dynamic helpers
        app.use(helpers(config.app.name));

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

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

        //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) {
            //Treat as 404
            if (~err.message.indexOf('not found')) return next();

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

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

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

    });
};
Example #7
0
/*
 * Express app
 */

var app = express();

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

/*
 * Express app - middleware
 */

app.use(express.logger());                                   // Log requests

app.use(express.compress());                                 // Set up all responses to be compressed

app.use(mediaType);                                          // Custom request method: mediaType

app.use(express.bodyParser());                               // Read POST bodies into request.body

app.use(app.router);                                         // First try to match routes
app.use(stylus.middleware({                                  // Compile styles; about to enter static
  src: __dirname + '/styles',
  dest: __dirname,
  compile: function(string, filePath) {
    return stylus(string)
      .set('filename', filePath)
      .use(nib())
      ;
  }
Example #8
0
        app.configure(function() {

            var serverVersion = 'pump.io/'+version + ' express/'+express.version + ' node.js/'+process.version,
                versionStamp = function(req, res, next) {
                    res.setHeader('Server', serverVersion);
                    next();
                },
                canonicalHost = function(req, res, next) {
                    var host = req.header('Host'),
                        urlHost,
                        addressHost;

                    if (!config.redirectToCanonical || !host) {
                        next();
                        return;
                    }

                    urlHost = URLMaker.makeHost();

                    if (host == urlHost) {
                        next();
                        return;
                    }

                    if (!config.redirectAddressToCanonical) {

                        addressHost = URLMaker.makeHost(address, port);

                        if (host == addressHost) {
                            next();
                            return;
                        }
                    }

                    res.redirect(URLMaker.makeURL(req.url), 301);
                };

            // Templates are in public
            app.set("views", __dirname + "/../public/template");
            app.set("view engine", "utml");

            app.use(requestLogger(log));

            if (config.redirectToCanonical) {
                app.use(canonicalHost);
            }

            app.use(rawBody);

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

            if (config.compress) {
                app.use(express.compress());
            }

            app.use(versionStamp);

            app.provider = new Provider(log, config.clients);

            // Initialize scripts

            _.each(config.plugins, function(pluginName) {
                var script;
                if (_.isFunction(plugins[pluginName].getScript)) {
                    script = plugins[pluginName].getScript();
                    log.info({plugin: pluginName, script: script}, "Adding script");
                    config.scripts.push(script);
                }
            });

            app.use(function(req, res, next) {
                res.local("config", config);
                res.local("data", {});
                res.local("page", {url: req.originalUrl});
                res.local("template", {});
                // Initialize null
                res.local("principalUser", null);
                res.local("principal", null);
                res.local("user", null);
                res.local("client", null);
                res.local("nologin", false);
                res.local("version", version);
                res.local("messages", {items: []});
                res.local("notifications", {items: []});
                next();
            });

            app.use(auth([auth.Oauth({name: "client",
                                      realm: "OAuth",
                                      oauth_provider: app.provider,
                                      oauth_protocol: (useHTTPS) ? 'https' : 'http',
                                      authenticate_provider: null,
                                      authorize_provider: null,
                                      authorization_finished_provider: null
                                     }),
                          auth.Oauth({name: "user",
                                      realm: "OAuth",
                                      oauth_provider: app.provider,
                                      oauth_protocol: (useHTTPS) ? 'https' : 'http',
                                      authenticate_provider: oauth.authenticate,
                                      authorize_provider: oauth.authorize,
                                      authorization_finished_provider: oauth.authorizationFinished
                                     })
                         ]));

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

            app.use(app.router);

        });
Example #9
0
module.exports = function(app, passport, db) {
    app.set('showStackError', true);

    // Prettify HTML
    app.locals.pretty = true;
    // cache=memory or swig dies in NODE_ENV=production
    app.locals.cache = 'memory';

    // Should be placed before express.static
    // To ensure that all assets and data are compressed (utilize bandwidth)
    app.use(express.compress({
        filter: function(req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        // Levels are specified in a range of 0 to 9, where-as 0 is
        // no compression and 9 is best compression, but slowest
        level: 9
    }));

    // Only use logger for development environment
    if (process.env.NODE_ENV === 'development') {
        app.use(express.logger('dev'));
    }

    // assign the template engine to .html files
    app.engine('html', consolidate[config.templateEngine]);

    // set .html as the default extension
    app.set('view engine', 'html');

    // Set views path, template engine and default layout
    app.set('views', config.root + '/app/views');

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

    app.configure(function() {
        // The cookieParser should be above session
        app.use(express.cookieParser());

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

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

        // Dynamic helpers
        app.use(helpers(config.app.name));

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

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

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

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

        // 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) {
            // Treat as 404
            if (~err.message.indexOf('not found')) return next();

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

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

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

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

  app.set('showStackError', true)
  app.set('port', process.env.PORT || 8080)
  // 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(express.static(config.root + '/public'))
  app.use(express.logger('dev'))

  // set views path, template engine and default layout
  app.set('views', config.root + '/app/views')
  app.set('view engine', 'jade')

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

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

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

    // express/mongo session storage
    app.use(express.session({
      secret: 'obiwankanobi',
      store: new mongoStore({
        url: config.db,
        collection : 'sessions'
      })
    }))

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

    // use passport session
    app.use(passport.initialize())
    app.use(passport.session())
    
    app.use(express.favicon())

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

    //Error Messages
    app.use(function(err, req, res, next){
      // treat as 404
      if (~err.message.indexOf('not found')) return next()

      // log it
      console.error(err.stack)

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

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

  })
}
Example #11
0
extend.console.register('server', 'Run server', function(args){
  var app = express(),
    //admin = args.a || args.admin ? true : false,
    admin = false,
    statics = args.s || args.static ? true : false,
    log = args.l || args.log,
    port = args.p || args.port || config.port,
    generate = require('../../generate');

  app.set('views', hexo.core_dir + 'views');
  app.set('view engine', 'ejs');
  app.locals.config = config;
  app.locals.version = hexo.version;
  //app.locals.layout = 'layout';
  //app.locals.cache = true;
  app.engine('ejs', require('../../render').renderFile);

  app.resource = function(){
    var args = _.toArray(arguments),
      path = args.shift(),
      obj = args.pop();

    if (obj.index) app.get.apply(app, [].concat(path, args, obj.index));
    if (obj.new) app.get.apply(app, [].concat(path + '/new', args, obj.new));
    if (obj.create) app.post.apply(app, [].concat(path, args, obj.create));
    if (obj.show) app.get.apply(app, [].concat(path + '/:id', args, obj.show));
    if (obj.edit) app.get.apply(app, [].concat(path + '/:id/edit', args, obj.edit));
    if (obj.update) app.put.apply(app, [].concat(path + '/:id', args, obj.update));
    if (obj.destroy) app.del.apply(app, [].concat(path + '/:id', args, obj.destroy));

    return this;
  };

  if (log){
    app.use(express.logger(log));
  } else if (config.logger){
    if (config.logger_format) app.use(express.logger(config.logger_format));
    else app.use(express.logger());
  } else if (hexo.debug){
    app.use(express.logger());
  }

  var startServer = function(){
    app.use(config.root, express.static(publicDir));

    if (config.root !== '/'){
      app.get('/', function(req, res){
        res.redirect(config.root);
      });
    }

    app.use(function(req, res){
      res.status(404).end('404 Not Found');
    });

    app.listen(port, function(){
      console.log('Hexo is running at %s. Press Ctrl+C to stop.', ('http://localhost:' + port + config.root).bold);
      if (admin && !statics) console.log('Admin password: %s', adminPass.bold);
      hexo.emit('server');
    });
  };

  if (statics){
    app.use(express.compress());

    async.waterfall([
      function(next){
        if (args.g || args.generate) return next(null, true);
        fs.exists(publicDir, function(exist){
          next(null, !exist);
        });
      },
      function(generate, next){
        if (!generate) return next();
        hexo.call('generate', next);
      }
    ], startServer);

    return;
  }

  if (admin){
    var adminPass = config.admin_pass || randomPass(8);

    app.use(express.bodyParser());
    app.use(express.cookieParser('nAL1o1D5wlBn96T'));
    app.use(express.session());

    app.get('/admin/auth', function(req, res, next){
      if (req.session.authed){
        next();
      } else {
        res.render('auth', {error: req.query.error});
      }
    });

    app.post('/admin/auth', function(req, res, next){
      var pass = req.body.pass;
      if (pass === adminPass){
        req.session.authed = true;
        res.redirect('/admin');
      } else {
        res.redirect('/admin/auth?error=1');
      }
    });

    var auth = function(req, res, next){
      if (req.session.authed) return next();
      res.redirect('/admin/auth');
    };

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

    app.use('/admin', express.static(hexo.core_dir + 'public'));
  }

  app.get(config.root + '*', function(req, res, next){
    var uri = route.format(req.params[0]),
      target = route.get(uri);

    if (!target){
      if (uri.substr(uri.length - 1, 1) === '/') return next();
      res.redirect(req.url + '/');
      return;
    }

    target(function(err, result){
      if (err) throw new Error('Route Error: ' + uri);

      res.type(path.extname(uri));

      if (result.readable){
        result.pipe(res).on('error', function(err){
          if (err) next();
        });
      } else {
        res.end(result);
      }
    });
  });

  console.log('Loading.');
  generate({watch: true}, startServer);
});
Example #12
0
app.configure(function () {
	app.use(express.compress()); // Compress the data send by "req.send"
	app.use(express.methodOverride()); // Allow to use the PUT and DELETE method
	app.use(express.bodyParser()); // Allow the body parsing
	app.use(express.static(__dirname + '/public')); // Specify the location of our web application (it's like the folder "www" with Apache HTTP Server)
});
Example #13
0
module.exports = function (app, config, passport) {

    /* all environments */
    
    // 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
    }))

    // Nunjucks template engine
    nunEnv = new nunjucks.Environment(new nunjucks.FileSystemLoader(config.root + '/app/views'))
    // nunEnv = new nunjucks.Environment()
    // nunjucks.precompile(config.root + '/app/views', { env: nunEnv })
    nunEnv.express(app)

    app.use(express.favicon())
    // app.use(express.favicon(config.root + '/public/img/favicon-30.png')); 

    if (env == 'development') 
        app.use(express.logger('dev'))

    // cookieParser debe estar sobre el manejo de sesiones
    app.use(express.cookieParser())

    // Manejo de formularios
    app.use(express.bodyParser())
    app.use(express.methodOverride())
    
    // Use less middleware
    lessOptions.src = config.root + '/public'
    if (env == 'production') {
        lessOptions.compress = true
        lessOptions.yuicompress = true
        lessOptions.once = true
    }

    app.use(lessMiddleware(lessOptions))
    app.use(express.static(path.join(config.root, 'public')))
    
    // express/mongo session storage
    app.use(express.session({
        secret: 'boilerplatejs',
        store: new mongoStore({
            url: config.db
            , collection : 'sessions'
        })
    }))

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

    // use passport session
    app.use(passport.initialize())
    app.use(passport.session())
    
    // adds CSRF support
    // TODO: agregar soporte csrf con ajax
    app.use(express.csrf())

    // View-Helpers
    app.use(require('./middlewares/view-helpers'))

    app.use(app.router)

    // 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){
        // treat as 404
        if (~err.message.indexOf('not found')) 
            return next()
        
        // log it
        console.error(err)

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

    // Assume 404 since no middleware responded
    app.use(function(req, res, next){
        res.status(404).render('404.html', { url: req.originalUrl, error: 'Not found' })
    })
}
Example #14
0
    console.log('!! DEVELOPMENT MODE !!');
    app.use(express.logger('dev'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function() {
    console.log('!! PRODUCTION MODE !!');
    app.use(express.logger());
    app.use(express.errorHandler());
});

//================================================================================
// Middleware
//================================================================================
// app.use(cors());                                            //CORS implementation
app.use(express.compress());                                //Compress response data with gzip / deflate. This middleware should be placed "high" within the stack to ensure all responses may be compressed.
app.use(express.bodyParser());                              //Request body parsing middleware supporting JSON, urlencoded, and multipart requests. This middleware is simply a wrapper for the json(), urlencoded(), and multipart() middleware.
app.use(express.methodOverride());                          //Faux HTTP method support. Use if you want to simulate DELETE/PUT
app.use(express.static(path.join(__dirname, 'client')));    //serve up static files (html, js, css, etc.)
app.use(passport.initialize());                             //initializes passport
app.use(app.router);                                        //application routes
app.use(globalErrorHandler);                                //handles all unresolved errors from the next() method

//================================================================================
// Initialization
//================================================================================
db.startup();   //initializes our database
routes(app);    //wires up all our routes

app.listen(port, function() {
  console.log('Listening on ' + port);
Example #15
0
        res.setHeader("Cache-Control", "public, max-age=300");
        return next();
    };
}

function logger() {
    express.logger.token("date", function() {
        return new Date().toISOString();
    });
    express.logger.token("response-all", function(req, res) {
        return (res._header ? res._header : "").trim();
    });
    express.logger.token("request-all", function(req, res) {
        return util.inspect(req.headers);
    });
    return express.logger(
        ':date - info: :remote-addr :req[cf-connecting-ip] :req[cf-ipcountry] :method :url HTTP/:http-version ' +
        '":user-agent" :referrer :req[cf-ray] :req[accept-encoding]\\n:request-all\\n\\n:response-all\\n');
}

var port = process.argv[2];
var express = require("express");
var app = express();

app.use(cacheControl());
app.use(express.compress({filter: compressionFilter}));
app.use(logger());
app.use(express.static("src"));

app.listen(port);
console.log("Listening on port " + port + "...");
Example #16
0
Keystone.prototype.start = function(onStart) {
	
	if (!this.app) {
		throw new Error("Keystone app must be initialised first.");
	}
		
	this.nativeApp = true;
	
	var keystone = this,
		app = this.app;
	
	// Setup

  var custom_engine = this.get('custom engine');
  if (custom_engine){
   app.engine(this.get('view engine'), custom_engine);
  }
	app.set('port', this.get('port') || process.env.PORT || 3000);
	app.set('host', this.get('host') || process.env.IP || '127.0.0.1');
	app.set('views', this.getPath('views') || '/views');
	app.set('view engine', this.get('view engine'));
	
	// Apply locals
	
	if (utils.isObject(this.get('locals'))) {
		_.extend(app.locals, this.get('locals'));
	}
	
	if (this.get('env') != 'production') {
		app.locals.pretty = true;
	}
	
	// Serve static assets
	
	if (this.get('compress')) {
		app.use(express.compress());
	}
	
	if (this.get('favico')) {
		app.use(express.favicon(this.getPath('favico')));
	}
	
	if (this.get('less')) {
		app.use(require('less-middleware')({ src: this.getPath('less') }));
	}
	
	if (this.get('static')) {
		app.use(express.static(this.getPath('static')));
	}
	
	if (!this.get('headless')) {
		keystone.static(app);
	}
	
	// Handle dynamic requests
	
	if (this.get('logger'))
		app.use(express.logger(this.get('logger')));
	
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	
	if (this.get('cookie secret')) {
		app.use(express.cookieParser(this.get('cookie secret')));
	}
	app.use(express.session());
	app.use(require('connect-flash')());
	
	if (this.get('session') === true) {
		app.use(this.session.persist);
	} else if ('function' == typeof this.get('session')) {
		app.use(this.get('session'));
	}
	
	// Pre-route middleware
	
	this._pre.routes.forEach(function(fn) {
		try {
			app.use(fn);	
		}
		catch(e) {
			console.log('Pre-route middleware (not found):');
			console.log(e);
		}
	});
	
	// Route requests
	
	app.use(app.router);
	
	// Headless mode means don't bind the Keystone routes
	
	if (!this.get('headless')) {
		this.routes(app);
	}
	
	// Handle 404 (no route matched) errors
	
	var default404Handler = function(req, res, next) {
		res.status(404).send("Sorry, no page could be found at this address (404)");
	}
	
	app.use(function(req, res, next) {
		
		var err404 = keystone.get('404');
		
		if (err404) {
			try {
				if ('function' == typeof err404) {
                    err404(req, res, next);
				} else if ('string' == typeof err404) {
                    res.status(404).render(err404);
				} else {
					console.log('Error handling 404 (not found): Invalid type (' + (typeof err404) + ') for 404 setting.');
					default404Handler(req, res, next);
				}
			} catch(e) {
				console.log('Error handling 404 (not found):');
				console.log(e);
				default404Handler(req, res, next);
			}
		} else {
			default404Handler(req, res, next);
		}
		
	});
	
	// Handle other errors
	
	var default500Handler = (this.get('env') == 'development') ? express.errorHandler() : function(err, req, res, next) {
		console.log('Error thrown for request: ' + req.url);
		console.log(err);
		res.status(500).send("Sorry, an error occurred loading the page (500)");
	}
	
	app.use(function(err, req, res, next) {
		
		var err500 = keystone.get('500');
		
		if (err500) {
			try {
				if ('function' == typeof err500) {
					err500(err, req, res, next);
				} else if ('string' == typeof err500) {
					res.locals.err = err;
					res.status(500).render(err500);
				} else {
					console.log('Error handling 500 (error): Invalid type (' + (typeof err500) + ') for 500 setting.');
					default500Handler(err, req, res, next);
				}
			} catch(e) {
				console.log('Error handling 500 (error):');
				console.log(e);
				default500Handler(err, req, res, next);
			}
		} else {
			default500Handler(err, req, res, next);
		}
		
	});
	
	// Configure application routes
	if ('function' == typeof this.get('routes')) {
		this.get('routes')(app);
	}

	// Connect to database
	
	var mongooseArgs = this.get('mongo'),
		mongoConnectionOpen = false;
	
	if (!mongooseArgs) {
		mongooseArgs = process.env.MONGO_URI || process.env.MONGO_URL || process.env.MONGOLAB_URI || process.env.MONGOLAB_URL || ['localhost', utils.slug(this.get('name'))];
	}
	
	this.mongoose.connect.apply(this.mongoose, Array.isArray(mongooseArgs) ? mongooseArgs : [mongooseArgs]);
	
	this.mongoose.connection.on('error', function() {
		
		if (mongoConnectionOpen) {
			console.error(keystone.get('name') + ': mongo connection error', arguments);
			// TODO: should probably implement something here to serve an error page, as the next attempt to use the database will fail and (probably) crash the server
		} else {
			console.error(keystone.get('name') + ' failed to start: mongo connection error', arguments);
		}
		
	}).on('open', function() {
		
		mongoConnectionOpen = true;
		
		// Create the http server
		var listen = function() {
			keystone.httpServer = http.createServer(app);
			keystone.httpServer.listen(app.get('port'), app.get('host'), function() {
				console.log(keystone.get('name') + ' is ready on port ' + app.get('port'));
				if ('function' == typeof onStart)
					onStart();
			});
		}
		
		// Apply updates?
		if (keystone.get('auto update')) {
			keystone.applyUpdates(listen);
		} else {
			listen();
		}
		
	});
	
}
Example #17
0
module.exports = function(config_hash) {
	var config = new Config(config_hash)
	  , storage = new Storage(config);

	search.configureStorage(storage);

	var can = function(action) {
		return function(req, res, next) {
			if (config['allow_'+action](req.params.package, req.remoteUser)) {
				next()
			} else {
				if (!req.remoteUser) {
					if (req.remoteUserError) {
						var message = "can't "+action+' restricted package, ' + req.remoteUserError
					} else {
						var message = "can't "+action+" restricted package without auth, did you forget 'npm set always-auth true'?"
					}
					next(new UError({
						status: 403,
						message: message,
					}))
				} else {
					next(new UError({
						status: 403,
						message: 'user '+req.remoteUser+' not allowed to '+action+' it'
					}))
				}
			}
		}
	}

	var app = express()

	// run in production mode by default, just in case
	// it shouldn't make any difference anyway
	app.set('env', process.env.NODE_ENV || 'production')

	function error_reporting_middleware(req, res, next) {
		res.report_error = res.report_error || function(err) {
			if (err.status && err.status >= 400 && err.status < 600) {
				if (!res.headersSent) {
					res.status(err.status)
					res.send({error: err.message || 'unknown error'})
				}
			} else {
				Logger.logger.error({err: err}, 'unexpected error: @{!err.message}\n@{err.stack}')
				if (!res.status || !res.send) {
					Logger.logger.error('this is an error in express.js, please report this')
					res.destroy()
				} else if (!res.headersSent) {
					res.status(500)
					res.send({error: 'internal server error'})
				} else {
					// socket should be already closed
				}
			}
		}
		next()
	}

	app.use(error_reporting_middleware)
	app.use(Middleware.log_and_etagify)
	app.use(function(req, res, next) {
		res.setHeader('X-Powered-By', config.user_agent)
		next()
	})
	app.use(Cats.middleware)
	app.use(basic_auth(function(user, pass, cb) {
		config.authenticate(user, pass, cb)
	}))
	app.use(express.json({strict: false, limit: config.max_body_size || '10mb'}))
	app.use(express.compress())
	app.use(Middleware.anti_loop(config))

	// validate all of these params as a package name
	// this might be too harsh, so ask if it causes trouble
	app.param('package', validate_name)
	app.param('filename', validate_name)
	app.param('tag', validate_name)
	app.param('version', validate_name)
	app.param('revision', validate_name)

	// these can't be safely put into express url for some reason
	app.param('_rev', match(/^-rev$/))
	app.param('org_couchdb_user', match(/^org\.couchdb\.user:/))
	app.param('anything', match(/.*/))

/*  app.get('/-/all', function(req, res) {
		var https = require('https')
		var JSONStream = require('JSONStream')
		var request = require('request')({
			url: 'https://registry.npmjs.org/-/all',
		})
		.pipe(JSONStream.parse('*'))
		.on('data', function(d) {
			console.log(d)
		})
	})*/

	app.get('/-/count', can('access'), function(req, res, next){
		res.setHeader('Content-Type', 'application/json');
		storage.get_local(function(err, packages){
			console.log(packages);
			res.send({
				'packages': packages.length
			})
		});
	});
	
	Handlebars.registerPartial('entry', fs.readFileSync(require.resolve('./GUI/entry.hbs'), 'utf8'));
	var template = Handlebars.compile(fs.readFileSync(require.resolve('./GUI/index.hbs'), 'utf8'));

	app.get('/', can('access'), function(req, res, next) {
		res.setHeader('Content-Type', 'text/html');

		storage.get_local(function(err, packages) {
			res.send(template({
				name:       config.title || "Sinopia",
				packages:   packages,
				baseUrl:    config.url_prefix || req.protocol + '://' + req.get('host') + '/'
			}));
		});
	});

	// TODO: anonymous user?
	app.get('/:package/:version?', can('access'), function(req, res, next) {
		storage.get_package(req.params.package, {req: req}, function(err, info) {
			if (err) return next(err)
			info = utils.filter_tarball_urls(info, req, config)

			var version = req.params.version
			  , t
			if (!version) {
				return res.send(info)
			}

			if ((t = utils.get_version(info, version)) != null) {
				return res.send(t)
			}

			if (info['dist-tags'] != null) {
				if (info['dist-tags'][version] != null) {
					version = info['dist-tags'][version]
					if ((t = utils.get_version(info, version)) != null) {
						return res.send(t)
					}
				}
			}

			return next(new UError({
				status: 404,
				message: 'version not found: ' + req.params.version
			}))
		})
	})

	app.get('/:package/-/:filename', can('access'), function(req, res, next) {
		var stream = storage.get_tarball(req.params.package, req.params.filename)
		stream.on('content-length', function(v) {
			res.header('Content-Length', v)
		})
		stream.on('error', function(err) {
			return res.report_error(err)
		})
		res.header('Content-Type', 'application/octet-stream')
		stream.pipe(res)
	})

	// searching packages
	app.get('/-/all/:anything?', function(req, res, next) {
		storage.search(req.param.startkey || 0, {req: req}, function(err, result) {
			if (err) return next(err)
			for (var pkg in result) {
				if (!config.allow_access(pkg, req.remoteUser)) {
					delete result[pkg]
				}
			}
			return res.send(result)
		})
	})

	//app.get('/*', function(req, res) {
	//  proxy.request(req, res)
	//})

	// placeholder 'cause npm require to be authenticated to publish
	// we do not do any real authentication yet
	app.post('/_session', cookies.express(), function(req, res) {
		res.cookies.set('AuthSession', String(Math.random()), {
			// npmjs.org sets 10h expire
			expires: new Date(Date.now() + 10*60*60*1000)
		})
		res.send({'ok':true,'name':'somebody','roles':[]})
	})

	app.get('/-/user/:org_couchdb_user', function(req, res, next) {
		res.status(200)
		return res.send({
			ok: 'you are authenticated as "' + req.remoteUser + '"',
		})
	})

	app.put('/-/user/:org_couchdb_user/:_rev?/:revision?', function(req, res, next) {
		if (req.remoteUser != null) {
			res.status(201)
			return res.send({
				ok: 'you are authenticated as "' + req.remoteUser + '"',
			})
		} else {
			if (typeof(req.body.name) !== 'string' || typeof(req.body.password) !== 'string') {
				return next(new UError({
					status: 400,
					message: 'user/password is not found in request (npm issue?)',
				}))
			}
			config.add_user(req.body.name, req.body.password, function(err) {
				if (err) {
					if (err.status < 500 && err.message === 'this user already exists') {
						// with npm registering is the same as logging in
						// so we replace message in case of conflict
						return next(new UError({
							status: 409,
							message: 'bad username/password, access denied'
						}))
					}
					return next(err)
				}

				res.status(201)
				return res.send({
					ok: 'user "' + req.body.name + '" created',
				})
			})
		}
	})

	// Static
	app.get('/-/static/:filename', function(req, res, next) {
		var file = __dirname + '/static/' + req.params.filename
		fs.exists(file, function(exists) {
			if(exists) {
				res.sendfile(file);
			}
			else {
				res.status(404);
				res.send("File Not Found");
			}
		});
	});

	app.get('/-/logo', function(req, res, next) {
		res.sendfile(config.logo ? config.logo : __dirname + "/static/logo.png");
	});

	// Search
	app.get('/-/search/:anything', function(req, res, next) {
		var results = search.query(req.params.anything),
			packages = [];

		var getData = function(i) {
			storage.get_package(results[i].ref, function(err, entry) {
				if(entry) {
					packages.push(entry.versions[entry['dist-tags'].latest]);
				}

				if(i >= results.length - 1) {
					res.send(packages);
				}
				else {
					getData(i + 1);
				}
			});
		};

		if(results.length) {
			getData(0);
		}
		else {
			res.send([]);
		}
	});

	// Readme
	marked.setOptions({
	  highlight: function (code) {
		return require('highlight.js').highlightAuto(code).value;
	  }
	});

	app.get('/-/readme/:package/:version', function(req, res, next) {
		storage.get_readme(req.params.package, req.params.version, function(readme) {
			var file = 'README.md not found for package';
			if (!readme.errno){
				file = marked(readme);
			}
			res.send(file);
		});
	});

	// tagging a package
	app.put('/:package/:tag', can('publish'), media('application/json'), function(req, res, next) {
		if (typeof(req.body) !== 'string') return next('route')

		var tags = {}
		tags[req.params.tag] = req.body
		storage.add_tags(req.params.package, tags, function(err) {
			if (err) return next(err)
			res.status(201)
			return res.send({
				ok: 'package tagged'
			})
		})
	})

	// publishing a package
	app.put('/:package/:_rev?/:revision?', can('publish'), media('application/json'), expect_json, function(req, res, next) {
		var name = req.params.package

		if (Object.keys(req.body).length == 1 && utils.is_object(req.body.users)) {
			return next(new UError({
				// 501 status is more meaningful, but npm doesn't show error message for 5xx
				status: 404,
				message: 'npm star|unstar calls are not implemented',
			}))
		}

		try {
			var metadata = utils.validate_metadata(req.body, name)
		} catch(err) {
			return next(new UError({
				status: 422,
				message: 'bad incoming package data',
			}))
		}

		if (req.params._rev) {
			storage.change_package(name, metadata, req.params.revision, function(err) {
				after_change(err, 'package changed')
			})
		} else {
			storage.add_package(name, metadata, function(err) {
				after_change(err, 'created new package')
			})
		}

		function after_change(err, ok_message) {
			// old npm behaviour
			if (metadata._attachments == null) {
				if (err) return next(err)
				res.status(201)
				return res.send({
					ok: ok_message
				})
			}

			// npm-registry-client 0.3+ embeds tarball into the json upload
			// https://github.com/isaacs/npm-registry-client/commit/e9fbeb8b67f249394f735c74ef11fe4720d46ca0
			// issue #31, dealing with it here:

			if (typeof(metadata._attachments) != 'object'
			||  Object.keys(metadata._attachments).length != 1
			||  typeof(metadata.versions) != 'object'
			||  Object.keys(metadata.versions).length != 1) {

				// npm is doing something strange again
				// if this happens in normal circumstances, report it as a bug
				return next(new UError({
					status: 400,
					message: 'unsupported registry call',
				}))
			}

			if (err && err.status != 409) return next(err)

			// at this point document is either created or existed before
			var t1 = Object.keys(metadata._attachments)[0]
			create_tarball(t1, metadata._attachments[t1], function(err) {
				if (err) return next(err)

				var t2 = Object.keys(metadata.versions)[0]
				create_version(t2, metadata.versions[t2], function(err) {
					if (err) return next(err)

					add_tags(metadata['dist-tags'], function(err) {
						if (err) return next(err)

						res.status(201)
						return res.send({
							ok: ok_message
						})
					})
				})
			})
		}

		function create_tarball(filename, data, cb) {
			var stream = storage.add_tarball(name, filename)
			stream.on('error', function(err) {
				cb(err)
			})
			stream.on('success', function() {
				cb()
			})

			// this is dumb and memory-consuming, but what choices do we have?
			stream.end(new Buffer(data.data, 'base64'))
			stream.done()
		}

		function create_version(version, data, cb) {
			storage.add_version(name, version, data, null, cb)
		}

		function add_tags(tags, cb) {
			storage.add_tags(name, tags, cb)
		}
	})

	// unpublishing an entire package
	app.delete('/:package/-rev/*', can('publish'), function(req, res, next) {
		storage.remove_package(req.params.package, function(err) {
			if (err) return next(err)
			res.status(201)
			return res.send({
				ok: 'package removed'
			})
		})
	})

	// removing a tarball
	app.delete('/:package/-/:filename/-rev/:revision', can('publish'), function(req, res, next) {
		storage.remove_tarball(req.params.package, req.params.filename, req.params.revision, function(err) {
			if (err) return next(err)
			res.status(201)
			return res.send({
				ok: 'tarball removed'
			})
		})
	})

	// uploading package tarball
	app.put('/:package/-/:filename/*', can('publish'), media('application/octet-stream'), function(req, res, next) {
		var name = req.params.package

		var stream = storage.add_tarball(name, req.params.filename)
		req.pipe(stream)

		// checking if end event came before closing
		var complete = false
		req.on('end', function() {
			complete = true
			stream.done()
		})
		req.on('close', function() {
			if (!complete) {
				stream.abort()
			}
		})

		stream.on('error', function(err) {
			return res.report_error(err)
		})
		stream.on('success', function() {
			res.status(201)
			return res.send({
				ok: 'tarball uploaded successfully'
			})
		})
	})

	// adding a version
	app.put('/:package/:version/-tag/:tag', can('publish'), media('application/json'), expect_json, function(req, res, next) {
		var name = req.params.package
		  , version = req.params.version
		  , tag = req.params.tag

		storage.add_version(name, version, req.body, tag, function(err) {
			if (err) return next(err)
			res.status(201)
			return res.send({
				ok: 'package published'
			})
		})
	})

	// hook for tests only
	if (config._debug) {
		app.get('/-/_debug', function(req, res) {
			var do_gc = typeof(global.gc) !== 'undefined'
			if (do_gc) global.gc()
			res.send({
				pid: process.pid,
				main: process.mainModule.filename,
				conf: config.self_path,
				mem: process.memoryUsage(),
				gc: do_gc,
			})
		})
	}

	app.use(app.router)
	app.use(function(err, req, res, next) {
		if (typeof(res.report_error) !== 'function') {
			// in case of very early error this middleware may not be loaded before error is generated
			// fixing that
			error_reporting_middleware(req, res, function(){})
		}
		res.report_error(err)
	})

	return app
}
Example #18
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(express.favicon());
  app.use(express.static(config.root + '/public'));

  // don't use logger for test env
  if (process.env.NODE_ENV !== 'test') {
    app.use(express.logger('dev'));
  }

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

  app.configure(function () {
    // expose package.json to views
    app.use(function (req, res, next) {
      res.locals.pkg = pkg;
      next();
    });

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

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

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

    // 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){
      // treat as 404
      if (err.message && (~err.message.indexOf('not found') ||
          (~err.message.indexOf('Cast to ObjectId failed')))) {
        return next();
      }

      // log it
      // send emails if you want
      console.error(err.stack);

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

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

  // development env config
  app.configure('development', function () {
    app.locals.pretty = true;
  });
};
Example #19
0
// Redis client for publishing url status changes.
var pclient = redis.createClient();

// Grab secret from environment variable.
var hashSecret = process.env.CONTROLLER_SECRET;
// Error if there is no secret.
if (!hashSecret)
  throw "ERROR: No secret key found in env variable CONTROLLER_SECRET.";

// Create http service.
// Configure / set up http service.
var http = express().
  use(express.bodyParser()).
  use(express.logger("dev")).
  use(express.compress()).
  use(express.static("./controller/")).
  use(express.cookieParser(hashSecret)).
  use(express.session({ secret: hashSecret, key: "controller.sess", cookie: { path: "/", httpOnly: true, maxAge: null }}));

//
// Export the http server. The calling module can be responsible for starting it up as needed.
module.exports = http;

http.use(function(req, res, next)
{
  log(req);
  next();
});

//
Example #20
0
// Cloud9 IDE provides an environment variable called PORT
var port = process.env.PORT || 8125;
// Valid values are 'development' and 'production'
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

// Let's use Express.js, because everyone else does.
var express = require('express')
    , compiler = require('connect-compiler')
    ;

var app = express();
app.use(express.compress()); // Apply gzip compression
app.use(express.bodyParser()); // Automatically parse data in http POST etc
app.use(express.methodOverride()); // Provides faux support for http PUT and http DELETE methods
app.use(app.router); // Lets us add code for handling specific paths
app.use(express.directory('public')); // Provides cool directory indexes!

// I have a simple strategy: each HTML page comes from a Jade page of the same name.
// Using this connector is much easier than writing repetitive code to render 'views'.
app.use(compiler(
    { enabled : [ 'coffee'
                , 'jade'
                , 'stylus'
                ]
    , src     : 'views'
    , dest    : 'public'
    , options :
        { coffee: { header: true
                  }
        }
    }
Example #21
0
function configureExpress (app) {
    app.disable('x-powered-by');
    app.use(express.compress());
    app.use(express.bodyParser());
}
app.configure( function() {
  var tmpDir = path.normalize( require( "os" ).tmpDir() + "/mozilla.butter/" );

  if ( config.ENABLE_GELF_LOGS ) {
    messina = require( "messina" );
    logger = messina( "popcorn.webmaker.org-" + config.NODE_ENV || "development" );
    logger.init();
    app.use( logger.middleware() );
  } else {
    app.use( express.logger( config.logger ) );
  }

  app.use( "/static/bower", express.static( path.join( __dirname, "/bower_components" ), {
    maxAge: "31556952000" // one year
  }));
  app.use(helmet.iexss());
  app.use(helmet.contentTypeOptions());
  if ( !!config.FORCE_SSL ) {
    app.use( helmet.hsts() );
    app.enable( "trust proxy" );
  }
  app.use( express.compress() )
    .use( lessMiddleware({
      once: config.OPTIMIZE_CSS,
      dest: tmpDir,
      src: WWW_ROOT,
      compress: config.OPTIMIZE_CSS,
      yuicompress: config.OPTIMIZE_CSS,
      optimization: config.OPTIMIZE_CSS ? 0 : 2
    }))
    .use( requirejsMiddleware({
      src: WWW_ROOT,
      dest: tmpDir,
      debug: config.DEBUG,
      once: config.OPTIMIZE_JS,
      modules: {
        "/src/butter.js": {
          include: [ "butter" ],
          mainConfigFile: WWW_ROOT + "/src/popcorn.js",
          paths: {
            "make-api": path.resolve( __dirname, "node_modules/makeapi-client/src/make-api" ),
            "sso-include": path.resolve( __dirname, "node_modules/webmaker-sso/include" )
          }
        },
        "/src/embed.js": {
          include: [ "embed" ],
          mainConfigFile: WWW_ROOT + "/src/popcorn.js"
        }
      },
      defaults: {
        name: "../external/require/require",
        baseUrl: WWW_ROOT + "/src/",
        findNestedDependencies: true,
        optimize: "none",
        preserveLicenseComments: false,
        paths: {
          "localized": path.resolve( __dirname, "bower_components/webmaker-i18n/localized" ),
          "jquery": path.resolve( __dirname, "bower_components/jquery/jquery.min" ),
          "jquery-ui": path.resolve( __dirname, "bower_components/jquery-ui/ui/jquery-ui" ),
          "farbtastic": path.resolve( __dirname, "bower_components/farbtastic/farbtastic" ),
          "WebmakerUI": path.resolve( __dirname, "bower_components/webmaker-ui/ui" ),
          "webmaker-ui-fragments": path.resolve( __dirname, "bower_components/webmaker-ui/webmaker-ui-fragments" )
        },
        wrap: {
          startFile: __dirname + "/tools/wrap.start",
          endFile: __dirname + "/tools/wrap.end"
        }
      }
    }))
    .use( express.static( tmpDir, JSON.parse( JSON.stringify( config.staticMiddleware ) ) ) )
    .use( express.static( WWW_ROOT, JSON.parse( JSON.stringify( config.staticMiddleware ) ) ) );

  // Setup locales with i18n
  app.use( i18n.middleware({
    supported_languages: config.SUPPORTED_LANGS,
    default_lang: "en-US",
    mappings: require("webmaker-locale-mapping"),
    translation_directory: path.resolve( __dirname, "locale" )
  }));

  app.locals({
    config: {
      app_hostname: APP_HOSTNAME,
      audience: config.AUDIENCE,
      ga_account: config.GA_ACCOUNT,
      ga_domain: config.GA_DOMAIN,
      jwplayer_key: config.JWPLAYER_KEY,
      make_endpoint: config.MAKE_ENDPOINT,
      node_hubble_endpoint: config.NODE_HUBBLE_ENDPOINT,
      user_bar: config.USER_BAR,
      sync_limit: config.SYNC_LIMIT
    },
    supportedLanguages: i18n.getLanguages(),
    listDropdownLang: i18n.getSupportLanguages()
  });

  app.use( express.json() )
    .use( express.urlencoded() )
    .use( express.cookieParser() )
    .use( express.cookieSession( config.session ) )
    .use( express.csrf() )
    .use( helmet.xframe() )
    /* Show Zeus who's boss
     * This only affects requests under /api and /persona, not static files
     * because the static file writes the response header before we hit this middleware
     */
    .use( function( req, res, next ) {
      res.header( "Cache-Control", "no-store" );
      return next();
    })
    .use( app.router )
    /*jslint unused: false */
    .use( function( err, req, res, next ) {
      if ( !err.status ) {
        err.status = 500;
      }

      middleware.errorHandler( err, req, res );
    })
    /*jslint unused: false */
    .use( function( req, res, next ) {
      var err = {
        message: req.gettext( "This page doesn't exist" ),
        status: 404
      };

      middleware.errorHandler( err, req, res );
    });

  Project = require( "./lib/project" )( config.database );
  filter = require( "./lib/filter" )( Project.isDBOnline );
});
Example #23
0
Keystone.prototype.start = function(onStart) {
	
	if (!this.app) {
		throw new Error("Keystone app must be initialised first.");
	}
		
	this.nativeApp = true;
	
	var keystone = this,
		app = this.app;
	
	// Setup

  var custom_engine = this.get('custom engine');
  if (custom_engine){
   app.engine(this.get('view engine'), custom_engine);
  }
	app.set('port', this.get('port') || process.env.PORT || 3000);
	app.set('views', this.getPath('views') || '/views');
	app.set('view engine', this.get('view engine'));
	
	// Apply locals
	
	if (utils.isObject(this.get('locals'))) {
		_.extend(app.locals, this.get('locals'));
	}
	
	if (this.get('env') != 'production') {
		app.locals.pretty = true;
	}
	
	// Serve static assets
	
	if (this.get('compress')) {
		app.use(express.compress());
	}
	
	if (this.get('favico')) {
		app.use(express.favicon(this.getPath('favico')));
	}
	
	if (this.get('less')) {
		app.use(require('less-middleware')({ src: this.getPath('less') }));
	}
	
	if (this.get('static')) {
		app.use(express.static(this.getPath('static')));
	}
	
	if (!this.get('headless')) {
		keystone.static(app);
	}
	
	// Handle dynamic requests
	
	if (this.get('logger'))
		app.use(express.logger(this.get('logger')));
	
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	
	if (this.get('cookie secret')) {
		app.use(express.cookieParser(this.get('cookie secret')));
	}
	app.use(express.session());
	app.use(require('connect-flash')());
	
	if (this.get('session') === true) {
		app.use(this.session.persist);
	} else if ('function' == typeof this.get('session')) {
		app.use(this.get('session'));
	}
	
	// Pre-route middleware
	
	this._pre.routes.forEach(function(fn) {
		app.use(fn);
	});
	
	// Route requests
	
	app.use(app.router);
	
	// Headless mode means don't bind the Keystone routes
	
	if (!this.get('headless')) {
		this.routes(app);
	}
	
	// Handle 404 (no route matched) errors
	
	var err404 = this.get('404');
	
	if ('function' == typeof err404) {
		app.use(err404);
	} else if ('string' == typeof err404) {
		app.use(function(req, res, next) {
			res.status(404).render(err404);
		});
	} else {
		app.use(function(req, res, next) {
			res.status(404).send("Sorry, no page could be found at this address (404)");
		});
	}
	
	// Handle other errors
	
	var err500 = this.get('500');
	
	if ('function' == typeof err500) {
		app.use(err500);
	} else if (this.get('env') == 'development') {
		// Default to Express error handler in development environment
		app.use(express.errorHandler());
	} else {
		app.use(function(err, req, res, next) {
			res.status(500).send("Sorry, an error occurred loading the page (500)");
		});
	}
	
	// Configure application routes
	if ('function' == typeof this.get('routes')) {
		this.get('routes')(app);
	}

	// Connect to database
	
	var mongooseArgs = this.get('mongo');
	
	this.mongoose.connect.apply(this.mongoose, Array.isArray(mongooseArgs) ? mongooseArgs : [mongooseArgs]);
	
	this.mongoose.connection.on('error', function() {
		console.error(keystone.get('name') + ' failed to launch: mongo connection error', arguments);
	}).on('open', function() {
		
		// Create the http server
		var listen = function() {
			http.createServer(app).listen(app.get('port'), function() {
				console.log(keystone.get('name') + ' is ready on port ' + app.get('port'));
				if ('function' == typeof onStart)
					onStart();
			});
		}
		
		// Apply updates?
		if (keystone.get('auto update')) {
			keystone.applyUpdates(listen);
		} else {
			listen();
		}
		
	});
	
}
Example #24
0
        app.configure(function() {

            var serverVersion = "pump.io/"+version + " express/"+express.version + " node.js/"+process.version,
                versionStamp = function(req, res, next) {
                    res.setHeader("Server", serverVersion);
                    next();
                },
                canonicalHost = function(req, res, next) {
                    var host = req.header("Host"),
                        urlHost,
                        addressHost;

                    if (!config.redirectToCanonical || !host) {
                        next();
                        return;
                    }

                    urlHost = URLMaker.makeHost();

                    if (host == urlHost) {
                        next();
                        return;
                    }

                    if (!config.redirectAddressToCanonical) {

                        addressHost = URLMaker.makeHost(address, port);

                        if (host == addressHost) {
                            next();
                            return;
                        }
                    }

                    res.redirect(URLMaker.makeURL(req.url), 301);
                };

            // Templates are in public
            app.set("views", path.resolve(__dirname, "../public/template"));
            app.set("view engine", "utml");

            app.use(requestLogger(log));

            if (config.redirectToCanonical) {
                app.use(canonicalHost);
            }

            app.use(rawBody);

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

            // ^ INPUTTY
            // v OUTPUTTY

            if (config.compress) {
                app.use(express.compress());
            }

            app.use(versionStamp);

            app.use(express["static"](path.resolve(__dirname, "../public")));

            // Default is in public/images/favicon.ico
            // Can be overridden by a config setting

            app.use(express.favicon(config.favicon));

            app.provider = new Provider(log, config.clients);

            // Initialize scripts

            _.each(config.plugins, function(pluginName) {
                var script;
                if (_.isFunction(plugins[pluginName].getScript)) {
                    script = plugins[pluginName].getScript();
                    log.debug({plugin: pluginName, script: script}, "Adding script");
                    config.scripts.push(script);
                }
            });

            // defangs interpolated data objects

            var defang = function(obj) {
                var dup = _.clone(obj);
                _.each(dup, function(value, name) {
                    if (name == "displayName" && _.isString(value)) {
                        dup[name] = sanitize(value).escape();
                    } else if (_.isFunction(value)) {
                        delete dup[name];
                    } else if (_.isObject(value)) {
                        dup[name] = defang(value);
                    }
                });
                return dup;
            };

            app.use(function(req, res, next) {
                res.local("config", config);
                res.local("data", {});
                res.local("page", {url: req.originalUrl});
                res.local("template", {});
                // Initialize null
                res.local("principalUser", null);
                res.local("principal", null);
                res.local("user", null);
                res.local("client", null);
                res.local("nologin", false);
                res.local("version", version);
                res.local("messages", {items: []});
                res.local("notifications", {items: []});
                res.local("defang", defang);
                next();
            });

            app.use(auth([auth.Oauth({name: "client",
                                      realm: "OAuth",
                                      oauth_provider: app.provider,
                                      oauth_protocol: (useHTTPS) ? "https" : "http",
                                      authenticate_provider: null,
                                      authorize_provider: null,
                                      authorization_finished_provider: null
                                     }),
                          auth.Oauth({name: "user",
                                      realm: "OAuth",
                                      oauth_provider: app.provider,
                                      oauth_protocol: (useHTTPS) ? "https" : "http",
                                      authenticate_provider: oauth.authenticate,
                                      authorize_provider: oauth.authorize,
                                      authorization_finished_provider: oauth.authorizationFinished
                                     })
                         ]));

            app.use(app.router);

        });
Example #25
0
module.exports = function(app) {
  app.set('showStackError', true);

  //Prettify HTML
  app.locals.pretty = 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
  }));

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

  //Don't use logger for test env
  if (process.env.NODE_ENV !== 'test') {
    app.use(express.logger('dev'));
  }

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

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

  app.configure(function() {
    app.use(express.cookieParser());
    app.use(bodyParser());
    app.use(express.urlencoded());
    app.use(express.json());
    app.use(express.methodOverride());


    // Express Mongo Session Store
    app.use(express.session(
        {secret: 'GSF-Hacks'}
    ));

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

    //dynamic helpers
    app.use(helpers(config.app.name));

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

    //Assume "not found" in the error msgs is a 404.
    app.use(function(err, req, res, next) {
      //Treat as 404
      if (~err.message.indexOf('not found')) return next();

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

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

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

  });
};
Example #26
0
module.exports = function(app, passport, db) {
    app.set('showStackError', true);    
    
    //Prettify HTML
    app.locals.pretty = 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
    }));

    //Setting the fav icon and static folder
    app.use(express.favicon());
    app.use(express.static(config.root + '/public'));
    app.use(express.static(config.root + '/.tmp'));

    //Don't use logger for test env
    if (process.env.NODE_ENV !== 'test') {
        app.use(express.logger('dev'));
    }

    //Set views path, template engine and default layout
    app.set('views', config.root + '/server/views');
    app.engine('html', require('hbs').__express);
    app.set('view engine', 'html');


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

    app.configure(function() {
        //cookieParser should be above session
        app.use(express.cookieParser());

        //bodyParser should be above methodOverride
        app.use(express.bodyParser({uploadDir: root + '/uploads'}));
        app.use(express.methodOverride());

        //express/mongo session storage
        app.use(express.session({
            secret: 'nodember',
            store: new mongoStore({
                db: db.connection.db,
                collection: 'sessions'
            })
        }));



        //dynamic helpers
        app.use(helpers(config.app.name));

        //use passport session
        app.use(passport.initialize());
        app.use(passport.session());
        
        //connect flash for flash messages
        app.use(flash());
        //routes should be at the last
        app.use(app.router);

        //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) {
            //Treat as 404
            if (~err.message.indexOf('not found')) return next();

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

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

        //Assume 404 since no middleware responded
       //Here Express captures 404s and sends the url to Ember to look for articles        
        app.use(function(req, res) {
            res.status(404).redirect('/#' + req.originalUrl);
        });
    });
};
Example #27
0
app.configure(function() {
	app.use(express.compress());
	app.use(config.staticDirectory, express.static(config.staticPath));
	app.use(express.methodOverride());
	app.use(app.router);
});
Example #28
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(express.favicon(__dirname + '/public/img/favicon.ico'))
  app.use(express.static(config.root + '/public'))

  // don't use logger for test env
  if (process.env.NODE_ENV !== 'test') {
    app.use(express.logger('dev'))
  }

  // set views path, template engine and default layout
  app.set('views', config.root + '/app/views')
  app.set('view engine', 'jade')

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

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

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

    // express/mongo session storage
    app.use(express.session({
      secret: 'siddb',
      store: new mongoStore({
        url: config.db,
        collection : 'sessions'
      })
    }))

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

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

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

    // 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){
      // treat as 404
      if (~err.message.indexOf('not found')) return next()

      // log it
      console.error(err.stack)

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

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

  })
}
Example #29
0
File: app.js Project: leci/vp
var app = module.exports = express();

//some common configuration
app.enable('trust proxy');

// all environments
app.locals(settings.resources);
app.set('port', process.env.PORT || settings.app.port);
app.set('views', __dirname + '/source/views');
app.set('view engine', 'ejs');
app.engine('ejs', engine);

var logging = require('./source/commons/logging');
var logger = logging.logger;
app.use(logging.applogger);
app.use(express.compress());
app.use(express.query());
app.use(express.bodyParser({ uploadDir: './'+settings.file.upload }));
app.use(express.methodOverride());
app.use(express.cookieParser(settings.secretKey));
app.use(require('./source/middlewares/session')(express)); //set session middle-ware

var mode = app.get('env') || 'development';
if ('development' == mode) {
    app.use('/public', express.static(path.join(__dirname, 'public')));
    app.use('/web', express.static(path.join(__dirname, 'web')));
}
require('./source/routes')(app);
require('./source/middlewares/errorhandling')(app);

var server = http.createServer(app).listen(app.get('port'), function(){
Example #30
0
(function(app) {
	var templates = null;
	
	app.build_header = function(res) {
		return templates['header'].parse({
			cssSrc: global.config['theme:src'] || '/vendor/bootstrap/css/bootstrap.min.css',
			title: global.config['title'] || 'NodeBB',
			csrf:res.locals.csrf_token
		});
	};

	// Middlewares
	app.use(express.favicon(path.join(__dirname, '../', 'public', 'favicon.ico')));
	app.use(require('less-middleware')({ src: path.join(__dirname, '../', 'public') }));
	app.use(express.static(path.join(__dirname, '../', 'public')));
	app.use(express.bodyParser());	// Puts POST vars in request.body
	app.use(express.cookieParser());	// If you want to parse cookies (res.cookies)
	app.use(express.compress());
	app.use(express.session({
		store: new RedisStore({
			client: redisServer,
			ttl: 60*60*24*14
		}),
		secret: global.config.secret,
		key: 'express.sid'
	}));
	app.use(express.csrf());
	app.use(function(req, res, next) {
		res.locals.csrf_token = req.session._csrf;
		next();
	});

	module.exports.init = function() {
		templates = global.templates;
	}

	auth.initialize(app);

	app.use(function(req, res, next) {
		// Don't bother with session handling for API requests
		if (/^\/api\//.test(req.url)) return next();

		if (req.user && req.user.uid) {
			user.session_ping(req.sessionID, req.user.uid);
		}

		// (Re-)register the session as active
		user.active.register(req.sessionID);

		next();
	});
	
	auth.create_routes(app);
	admin.create_routes(app);
	userRoute.create_routes(app);
	installRoute.create_routes(app);


	app.create_route = function(url, tpl) { // to remove
		return '<script>templates.ready(function(){ajaxify.go("' + url + '", null, "' + tpl + '");});</script>';
	};

	// Basic Routes (entirely client-side parsed, goal is to move the rest of the crap in this file into this one section)
	(function() {
		var routes = ['login', 'register', 'account', 'recent', 'popular', 'active', '403', '404'];

		for (var i=0, ii=routes.length; i<ii; i++) {
			(function(route) {
				
				app.get('/' + route, function(req, res) {
					if ((route === 'login' || route ==='register') && (req.user && req.user.uid > 0)) {
						
						user.getUserField(req.user.uid, 'userslug', function(userslug) {
							res.redirect('/users/'+userslug);							
						});
						return;
					}
					
					res.send(app.build_header(res) + app.create_route(route) + templates['footer']);
				});
			}(routes[i]));
		}
	}());
	
	// Complex Routes
	app.get('/', function(req, res) {
		categories.getAllCategories(function(returnData) {
			res.send(
				app.build_header(res) +
				'\n\t<noscript>\n' + templates['noscript/header'] + templates['noscript/home'].parse(returnData) + '\n\t</noscript>' +
				app.create_route('') +
				templates['footer']
			);
		}, 0);
	});

	app.get('/topic/:topic_id/:slug?', function(req, res) {
		var tid = req.params.topic_id;
		if (tid.match('.rss')) {
			fs.readFile('feeds/topics/' + tid, function (err, data) {
				if (err) {
					res.send("Unable to locate an rss feed at this location.");
					return;
				}
				
				res.setHeader('Content-Type', 'application/xml');
				res.setHeader('Content-Length', data.length);
				res.end(data);
			});
			return;
		}


		var topic_url = tid + (req.params.slug ? '/' + req.params.slug : '');
		topics.getTopicWithPosts(tid, ((req.user) ? req.user.uid : 0), function(topic) {
			res.send(
				app.build_header(res) +
				'\n\t<noscript>\n' + templates['noscript/header'] + templates['noscript/topic'].parse(topic) + '\n\t</noscript>' +
				'\n\t<script>templates.ready(function(){ajaxify.go("topic/' + topic_url + '");});</script>' +
				templates['footer']
			);
		});
	});

	app.get('/category/:category_id/:slug?', function(req, res) {
		var cid = req.params.category_id;
		if (cid.match('.rss')) {
			fs.readFile('feeds/categories/' + cid, function (err, data) {
				if (err) {
					res.send("Unable to locate an rss feed at this location.");
					return;
				}

				res.setHeader('Content-Type', 'application/xml');
				res.setHeader('Content-Length', data.length);
				res.end(data);
			});
			return;
		}

		var category_url = cid + (req.params.slug ? '/' + req.params.slug : '');
		categories.getCategoryById(cid, 0, function(returnData) {

			res.send(
				app.build_header(res) +
				'\n\t<noscript>\n' + templates['noscript/header'] + templates['noscript/category'].parse(returnData) + '\n\t</noscript>' +
				'\n\t<script>templates.ready(function(){ajaxify.go("category/' + category_url + '");});</script>' +
				templates['footer']
			);
		});
	});

	app.get('/confirm/:code', function(req, res) {
		res.send(app.build_header(res) + '<script>templates.ready(function(){ajaxify.go("confirm/' + req.params.code + '");});</script>' + templates['footer']);
	});
	
	// These functions are called via ajax once the initial page is loaded to populate templates with data
	function api_method(req, res) {
		var uid = (req.user) ? req.user.uid : 0;
		
		switch(req.params.method) {
			case 'get_templates_listing' :
					utils.walk(global.configuration.ROOT_DIRECTORY + '/public/templates', function(err, data) {
						res.json(data);
					});
				break;
			case 'home' :
					categories.getAllCategories(function(data) {
						data.motd_class = (config.show_motd === '1' || config.show_motd === undefined) ? '' : 'none';
						data.motd = marked(config.motd || "# NodeBB v0.1\nWelcome to NodeBB, the discussion platform of the future.\n\n<a target=\"_blank\" href=\"http://www.nodebb.org\" class=\"btn btn-large\"><i class=\"icon-comment\"></i> Get NodeBB</a> <a target=\"_blank\" href=\"https://github.com/designcreateplay/NodeBB\" class=\"btn btn-large\"><i class=\"icon-github-alt\"></i> Fork us on Github</a> <a target=\"_blank\" href=\"https://twitter.com/dcplabs\" class=\"btn btn-large\"><i class=\"icon-twitter\"></i> @dcplabs</a>");
						res.json(data);
					}, uid);
				break;
			case 'login' :
					var data = {},
						login_strategies = auth.get_login_strategies(),
						num_strategies = login_strategies.length;

					if (num_strategies == 0) {
						data = {
							'login_window:spansize': 'span12',
							'alternate_logins:display': 'none'
						};	
					} else {
						data = {
							'login_window:spansize': 'span6',
							'alternate_logins:display': 'block'
						}
						for (var i=0, ii=num_strategies; i<ii; i++) {
							data[login_strategies[i] + ':display'] = 'active';
						}
					}

					data.token = res.locals.csrf_token;

					res.json(data);
				break;
			case 'register' :
					var data = {},
						login_strategies = auth.get_login_strategies(),
						num_strategies = login_strategies.length;

					if (num_strategies == 0) {
						data = {
							'register_window:spansize': 'span12',
							'alternate_logins:display': 'none'
						};	
					} else {
						data = {
							'register_window:spansize': 'span6',
							'alternate_logins:display': 'block'
						}
						for (var i=0, ii=num_strategies; i<ii; i++) {
							data[login_strategies[i] + ':display'] = 'active';
						}
					}

					data.token = res.locals.csrf_token;

					res.json(data);
				break;
			case 'topic' :
					topics.getTopicWithPosts(req.params.id, uid, function(data) {
						res.json(data);
					});
				break;
			case 'category' :
					categories.getCategoryById(req.params.id, uid, function(data) {
						res.json(data);
					}, req.params.id, uid);
				break;
			case 'recent' :
					categories.getLatestTopics(uid, 0, 9, function(data) {
						res.json(data);
					});
				break;
			case 'popular' :
					categories.getLatestTopics(uid, 0, 9, function(data) {
						res.json(data);
					});
				break;
			case 'active' :
					categories.getLatestTopics(uid, 0, 9, function(data) {
						res.json(data);
					});
				break;
			case 'confirm':
					user.email.confirm(req.params.id, function(data) {
						if (data.status === 'ok') {
							res.json({
								'alert-class': 'alert-success',
								title: 'Email Confirmed',
								text: 'Thank you for vaidating your email. Your account is now fully activated.'
							});
						} else {
							res.json({
								'alert-class': 'alert-error',
								title: 'An error occurred...',
								text: 'There was a problem validating your email address. Perhaps the code was invalid or has expired.'
							});
						}
					});
				break;
			default :
				res.json({});
			break;
		}
	}

	app.get('/api/:method', api_method);
	app.get('/api/:method/:id', api_method);
	// ok fine MUST ADD RECURSION style. I'll look for a better fix in future but unblocking baris for this:
	app.get('/api/:method/:id/:section?', api_method);
	app.get('/api/:method/:id*', api_method);

	app.get('/cid/:cid', function(req, res) {
		categories.getCategoryData(req.params.cid, function(data){
			if(data)
				res.send(data);
			else
				res.send("Category doesn't exist!");
		});
	});

	app.get('/tid/:tid', function(req, res) {
		topics.getTopicData(req.params.tid, function(data){
			if(data)
				res.send(data);
			else
				res.send("Topic doesn't exist!");
		});
	});

	app.get('/pid/:pid', function(req, res) {
		posts.getPostData(req.params.pid, function(data){
			if(data)
				res.send(data);
			else
				res.send("Post doesn't exist!");
		});
	});

	app.all('/test', function(req, res) {
		
		categories.getCategoryById(1,1, function(data) {
			res.send(data);
		},1);
		
	});

	//START TODO: MOVE TO GRAPH.JS 

	app.get('/graph/users/:username/picture', function(req, res) {
		user.get_uid_by_username(req.params.username, function(uid) {
			if (uid == null) {
				res.json({
					status: 0
				});
				return;
			}
			user.getUserField(uid, 'picture', function(picture) {
				if (picture == null) res.redirect('http://www.gravatar.com/avatar/a938b82215dfc96c4cabeb6906e5f953&default=identicon');
				res.redirect(picture);
			});
		});
		
	});

	//END TODO: MOVE TO GRAPH.JS
}(WebServer));