Example #1
0
/**
 * The main initializer
 */
function main(conf) {
    config = conf;

    application.setConfig(conf);
    application.initI18n();
    application.setEncryptionSalt(config[ENV].SALT);
    application.initAPNFeedbackPolling();

    mongoose    = db.connectToDatabase(mongoose, config.db[ENV].main);
    app         = express();
    server      = http.createServer(app);

    configureExpress();
    // configureSocketIO(); // muss vor den controller inits passieren!
    registerModels();

    // pass the user model to the application sandbox
    application.setUserModel(mongoose.model('User'));

    registerControllers();

    if(ENV !== 'test') { // dont listen here when testing
        var ipaddr = process.env.OPENSHIFT_NODEJS_IP   || config[ENV].HOST;
        var port   = process.env.OPENSHIFT_NODEJS_PORT || config[ENV].PORT;

        var url = (config[ENV].HTTPS ? 'https://' : 'http://') + ipaddr + ':' + port;

        logger.log('--> trying url: ' + url);

        server.listen(port, ipaddr, function () {
            app.serverUp = true;
        });

        // log a startup message...

        var msg = ('Express server listening on ' + url + ', environment: ' + ENV + ', PID: ').green;
        msg     += (process.pid + '').red;

        logger.log(msg);
        logger.log('loaded config: ' + JSON.stringify(conf[ENV]));

        // CORS OPTIONS FOR API URL
        // see
        // https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
        app.options(application.apiVersion + '/*', function opts(req, res) {
            // var method = req.method.toLowerCase(); // "options"
            return application.sendDefaultSuccess(req, res, {}, 204);
        });

        /*app.get('/api', function __apiWelcomeMessage(req, res) {
            // return res.json(req.session); // check session lifetime via cookies (not really used)

            // test an error within a request...
            // setTimeout(function() {
            //    throw new Error('HI!!!!!!!!!!!!!!!!! ERROR!!!!');
            // }, 1000);

            // etags for this response
            // res.etagify();

            // testing
            // var i18n = application.getI18nInstance();
            // i18n.setLocale('de'); // 'en'
            // return res.send(i18n.__.apply(i18n, ['listInvitationBody', 'fred', 'listeeeeeeeeeeeee']));

            var msg = 'Welcome to the AtOneGo API v' + pjson.version + '. Environment: ' + ENV;
            return res.json({message: msg}, 200); // hier kein CORS notwendig
        });*/

        // receive client logs (must be authenticated...)
        app.post('/api/v1/logs', application.checkAuth, function __receiveClientLogs(req, res) {
            var message = req.body.m;
            if(message) {
                console.log('||| CLIENT ERROR ||| ' + message);
            }
            return application.sendDefaultSuccess(req, res, {}, 204);
        });

        // endpoint for application usage statistics
        app.get('/stats', function __sendStats(req, res) {
            var mem = process.memoryUsage();
            // convert to MB
            mem.heapTotal = utils.round(mem.heapTotal / 1024.0 / 1024.0);
            mem.heapUsed  = utils.round(mem.heapUsed / 1024.0 / 1024.0);
            mem.rss       = utils.round(mem.rss / 1024.0 / 1024.0) + '(= actual physical RAM)';

            var uptimeH = utils.round(process.uptime() / 60.0 / 60.0);
            var uptimeM = utils.round(process.uptime() / 60.0);

            var json = {
                pid   : process.pid,
                memory: mem,
                uptime: uptimeH + ' hours (= ' + uptimeM + ' minutes)',
                customMsg: 'AtOneGo API v' + pjson.version + ' - Environment: ' + ENV
            };

            return res.json(json, 200);
        });

        if(ENV === 'production') {
            /**
             * The AtOneGo "Cron-Hack" - see .openshift/cron/minutely/atonego.sh
             *
             * Do some pseudo authorization here to "make sure" this request comes from
             * the cronjob shell script
             */
            app.post('/cron874693274924724798uesihrdsbhkjsbsbdsbdybsajbk', function __cronJob(req, res) {
                var KEY1  = conf[ENV].CRONJOB_KEY;
                var KEY2  = conf[ENV].CRONJOB_KEY2;
                var pass1 = req.body.my_awesome_key;
                var pass2 = req.headers['aog-ch'];

                if(KEY1 !== pass1 || KEY2 !== pass2) {
                    return res.json(500, {f**k: 'you'});
                }

                return __doCronJobOnPOST(req, res);
            });
        }
    }

    // used by server tests
    AppEmitter.on('checkApp', function () {
        AppEmitter.emit('getApp', server);
    });
}
Example #2
0
    app.use(express.logger(config.httpLogLevel))       // Add default logging
       .use(express.static(config.staticPageDir))      // serve static files
       .use(express.json())                            // parse post and put input data
       .use(express.urlencoded())
       .use(express.cookieParser(config.cookieSecret)) // parse cookies
       .use(sessions.getSession)                       // our custom session handler
       .use(app.router)                                // use routes in routes.defineRoutes
       .use(config.res.errorHandler)                   // out custom handle errors
    ;
});

log.debug('starting server',thisModule);

// Connect to Database and Start Server
db.connectToDatabase(function(){
    routes.defineRoutes(app);
    app.listen(config.listenPort,config.ipaddress);
    log.info('Listening on port ' + config.listenPort,thisModule);
});