Ejemplo n.º 1
0
server.listen(80, function() {
	log.info("snmp-stich listening on 0.0.0.0:80");
});
Ejemplo n.º 2
0
		worker.aspawn([ 'sleep', '10' ], function (err3) {
			mod_assert.ok(err3);
			mod_assert.equal(err3.message,
			    'worker process was destroyed');
			log.info('TEST PASSED');
		});
Ejemplo n.º 3
0
 function(callback) {
     log.info({driver: config.driver, params: config.params}, "Connecting to DB");
     db.connect({}, callback);
 },
Ejemplo n.º 4
0
Archivo: app.js Proyecto: obra/pump.io
 setInterval(function() {
     log.info("Cleaning up old OAuth nonces");
     Nonce.cleanup();
 }, cleanupTime);
Ejemplo n.º 5
0
var makeApp = function(config, callback) {

    var params,
        defaults = {port: 31337,
                    hostname: "127.0.0.1",
                    site: "pump.io",
                    sockjs: true,
                    debugClient: false,
                    firehose: "ofirehose.com",
                    requireEmail: false,
                    userDefaults: {lists: ["Friends", "Family", "Acquaintances", "Coworkers"]},
                    disableRegistration: false},
        port,
        hostname,
        address,
        log,
        db,
        logParams = {
            name: "pump.io",
            serializers: {
                req: Logger.stdSerializers.req,
                res: Logger.stdSerializers.res,
                principal: function(principal) {
                    if (principal) {
                        return {id: principal.id, type: principal.objectType};
                    } else {
                        return {id: "<none>"};
                    }
                },
                client: function(client) {
                    if (client) {
                        return {key: client.consumer_key, title: client.title || "<none>"};
                    } else {
                        return {key: "<none>", title: "<none>"};
                    }
                }
            }
        };

    // Fill in defaults if they're not there

    config = _.defaults(config, defaults);

    port     = config.port;
    hostname = config.hostname;
    address  = config.address || config.hostname;

    if (config.logfile) {
        logParams.streams = [{path: config.logfile}];
    } else if (config.nologger) {
        logParams.streams = [{path: "/dev/null"}];
    } else {
        logParams.streams = [{stream: process.stderr}];
    }

    log = new Logger(logParams);

    log.info("Initializing pump.io");

    // Initiate the DB

    if (_(config).has("params")) {
        params = config.params;
    } else {
        params = {};
    }

    if (_(params).has("schema")) {
        _.extend(params.schema, schema);
    } else {
        params.schema = schema;
    }

    db = Databank.get(config.driver, params);

    // Connect...

    log.info("Connecting to databank with driver '"+config.driver+"'");

    db.connect({}, function(err) {

        var useHTTPS = _(config).has('key'),
            useBounce = _(config).has('bounce') && config.bounce,
            app,
            io,
            bounce,
            dialbackClient,
            requestLogger = function(log) {
                return function(req, res, next) {
                    var weblog = log.child({"req_id": uuid.v4(), component: "web"});
                    var end = res.end;
                    req.log = weblog;
                    res.end = function(chunk, encoding) {
                        var rec;
                        res.end = end;
                        res.end(chunk, encoding);
                        rec = {req: req, res: res};
                        if (_(req).has("principal")) {
                            rec.principal = req.principal;
                        }
                        if (_(req).has("client")) {
                            rec.client = req.client;
                        }
                        weblog.info(rec);
                    };
                    next();
                };
            };

        if (err) {
            log.error(err);
            callback(err, null);
            return;
        }

        if (useHTTPS) {
            log.info("Setting up HTTPS server.");
            app = express.createServer({key: fs.readFileSync(config.key),
                                        cert: fs.readFileSync(config.cert)});

            if (useBounce) {
                log.info("Setting up micro-HTTP server to bounce to HTTPS.");
                bounce = express.createServer(function(req, res, next) {
                    var host = req.header('Host');
                    res.redirect('https://'+host+req.url, 301);
                });
            }

        } else {
            log.info("Setting up HTTP server.");
            app = express.createServer();
        }

        app.config = config;

        if (config.smtpserver) {
            Mailer.setup(config, log);
        }

        var cleanup = config.cleanup || 600000;
        var dbstore = new DatabankStore(db, log, cleanup);

        if (!_(config).has("noweb") || !config.noweb) {
            app.session = express.session({secret: (_(config).has('sessionSecret')) ? config.sessionSecret : "insecure",
                                           store: dbstore});
        }

        // Configuration

        app.configure(function() {

            // Templates are in public
            app.set("views", __dirname + "/../public/template");
            app.set("view engine", "utml");
            app.use(requestLogger(log));
            app.use(rawBody);
            app.use(express.bodyParser());
            app.use(express.cookieParser());
            app.use(express.query());
            app.use(express.methodOverride());
            app.use(express.favicon());

            app.provider = new Provider(log);

            app.use(function(req, res, next) { 
                res.local("config", config);
                res.local("data", {});
                res.local("page", {});
                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);
                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);

        });

        app.error(function(err, req, res, next) {
            log.error(err);
            if (err instanceof HTTPError) {
                if (req.xhr || req.originalUrl.substr(0, 5) === '/api/') {
                    res.json({error: err.message}, err.code);
                } else if (req.accepts("html")) {
                    res.status(err.code);
                    res.render("error", {page: {title: "Error"},
                                         error: err});
                } else {
                    res.writeHead(err.code, {"Content-Type": "text/plain"});
                    res.end(err.message);
                }
            } else {
                next(err);
            }
        });

        // Routes

        api.addRoutes(app);
        webfinger.addRoutes(app);
        clientreg.addRoutes(app);

        if (_.has(config, "uploaddir")) {
            // Simple boolean flag
            config.canUpload = true;
            uploads.addRoutes(app);
        }

        if (config.requireEmail) {
            confirm.addRoutes(app);
        }

        // Use "noweb" to disable Web site (API engine only)

        if (!_(config).has("noweb") || !config.noweb) {
            web.addRoutes(app);
        } else {
            // A route to show the API doc at root
            app.get("/", function(req, res, next) {

                var Showdown = require("showdown"),
                    converter = new Showdown.converter();

                Step(
                    function() {
                        fs.readFile(path.join(__dirname, "..", "API.md"), this);
                    },
                    function (err, data) {
                        var html, markdown;
                        if (err) {
                            next(err);
                        } else {
                            markdown = data.toString();
                            html = converter.makeHtml(markdown);
                            res.render("doc", {page: {title: "API"},
                                               html: html});
                        }
                    }
                );
            });
        }

        DatabankObject.bank = db;

        URLMaker.hostname = hostname;
        URLMaker.port = port;

        if (_(config).has('serverUser')) {
            app.on('listening', function() {
                process.setuid(config.serverUser);
            });
        }

        if (config.sockjs) {
            pumpsocket.connect(app, log);
        }

        if (config.firehose) {
            log.info({firehose: config.firehose}, "Setting up firehose");
            Firehose.setup(config.firehose, log);
        }

        if (config.spamhost) {
            if (!config.spamclientid ||
                !config.spamclientsecret) {
                throw new Error("Need client ID and secret for spam host");
            }
            log.info({spamhost: config.spamhost}, "Configuring spam host");
            ActivitySpam.init({
                host: config.spamhost,
                clientID: config.spamclientid,
                clientSecret: config.spamclientsecret,
                logger: log
            });
        }

        dialbackClient = new DialbackClient({
            hostname: hostname,
            bank: db,
            app: app,
            url: "/api/dialback"
        });

        Credentials.dialbackClient = dialbackClient;

        app.run = function(callback) {
            var self = this,
                removeListeners = function() {
                    self.removeListener("listening", listenSuccessHandler);
                    self.removeListener("err", listenErrorHandler);
                },
                listenErrorHandler = function(err) {
                    removeListeners();
                    log.error(err);
                    callback(err);
                },
                listenSuccessHandler = function() {
                    var removeBounceListeners = function() {
                        bounce.removeListener("listening", bounceSuccess);
                        bounce.removeListener("err", bounceError);
                    },
                        bounceError = function(err) {
                            removeBounceListeners();
                            log.error(err);
                            callback(err);
                        },
                        bounceSuccess = function() {
                            log.info("Finished setting up bounce server.");
                            removeBounceListeners();
                            callback(null);
                        };
                    
                    log.info("Finished setting up main server.");

                    removeListeners();
                    if (useBounce) {
                        bounce.on("error", bounceError);
                        bounce.on("listening", bounceSuccess);
                        bounce.listen(80, address);
                    } else {
                        callback(null);
                    }
                };
            this.on("error", listenErrorHandler);
            this.on("listening", listenSuccessHandler);
            log.info("Listening on "+port+" for host " + address);
            this.listen(port, address);
        };

        callback(null, app);
    });
};
Ejemplo n.º 6
0
Archivo: app.js Proyecto: e14n/ih8.it
    function(callback) {

        var app,
            bounce,
            client,
            requestLogger = function(log) {
                return function(req, res, next) {
                    var weblog = log.child({"req_id": uuid.v4(), component: "web"});
                    var end = res.end;
                    req.log = weblog;
                    res.end = function(chunk, encoding) {
                        var rec;
                        res.end = end;
                        res.end(chunk, encoding);
                        rec = {req: req, res: res};
                        weblog.info(rec);
                    };
                    next();
                };
            };

        // Set global databank info

        DatabankObject.bank = db;

        if (_.has(config, "key")) {

            log.info("Using SSL");

            app = express.createServer({key: fs.readFileSync(config.key),
                                        cert: fs.readFileSync(config.cert)});
            bounce = express.createServer(function(req, res, next) {
                var host = req.header('Host');
                res.redirect('https://'+host+req.url, 301);
            });

        } else {

            log.info("Not using SSL");

            app = express.createServer();
        }

        // Configuration

        var dbstore = new DatabankStore(db, log, 60000);

        log.info("Configuring app");

        app.configure(function(){
            var serverVersion = 'ih8.it/'+ih8it.version + ' express/'+express.version + ' node.js/'+process.version,
                versionStamp = function(req, res, next) {
                    res.setHeader('Server', serverVersion);
                    next();
                },
                appObject = function(req, res, next) {
                    req.ih8it = ih8it;
                    res.local("ih8it", ih8it);
                    next();
                };

            app.set('views', __dirname + '/views');
            app.set('view engine', 'utml');
            app.use(requestLogger(log));
            app.use(versionStamp);
            app.use(appObject);
            app.use(express.bodyParser());
            app.use(express.cookieParser());
            app.use(express.methodOverride());
            app.use(express.session({secret: (_(config).has('sessionSecret')) ? config.sessionSecret : "insecure",
                                     cookie: {path: '/', httpOnly: true},
                                     store: dbstore}));
            app.use(app.router);
            app.use(express.static(__dirname + '/public'));
        });

        app.configure('development', function(){
            app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
        });

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

        // Auth middleware

        var userAuth = function(req, res, next) {

            req.user = null;
            res.local("user", null);

            if (req.session.userID) {
                req.log.info({userID: req.session.userID}, "Logging in with session-stored user ID");
                User.get(req.session.userID, function(err, user) {
                    if (err) {
                        next(err);
                    } else {
                        req.log.info({userID: user.id}, "Logged in");
                        req.user = user;
                        res.local("user", user);
                        next();
                    }
                });
            } else if (req.cookies.rememberme) {
                req.log.info({rememberme: req.cookies.rememberme}, "Logging in with rememberme cookie");
                async.waterfall([
                    function(callback) {
                        RememberMe.get(req.cookies.rememberme, callback);
                    },
                    function(rm, callback) {
                        var id = rm.user;
                        req.log.info({rememberme: req.cookies.rememberme, userID: id}, "Found rememberme cookie");
                        async.parallel([
                            function(callback) {
                                rm.del(callback);
                            },
                            function(callback) {
                                User.get(id, callback);
                            },
                            function(callback) {
                                RememberMe.create({user: id}, callback);
                            }
                        ], callback);
                    }
                ], function(err, results) {
                    var rm, user;
                    if (err && err.name == "NoSuchThingError") {
                        // Clear the cookie and continue
                        res.clearCookie("rememberme", {path: "/"});
                        next();
                    } else if (err) {
                        next(err);
                    } else {

                        user = results[1];
                        rm = results[2];

                        req.user = user;
                        res.local("user", req.user);
                        req.session.userID = req.user.id;
                        req.log.info({userID: req.user.id}, "Set user");

                        res.cookie("rememberme", rm.uuid, {path: "/", expires: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000), httpOnly: true});
                        req.log.info({rememberme: rm.uuid, userID: req.user.id}, "Set rememberme cookie");

                        next();
                    }
                });
            } else {
                next();
            }
        };

        var userOptional = function(req, res, next) {
            next();
        };

        var userRequired = function(req, res, next) {
            if (!req.user) {
                next(new Error("User is required"));
            } else {
                next();
            }
        };

        var noUser = function(req, res, next) {
            if (req.user) {
                next(new Error("Already logged in"));
            } else {
                next();
            }
        };

        var userIsUser = function(req, res, next) {
            if (req.params.webfinger && req.user.id == req.params.webfinger) {
                next();
            } else {
                next(new Error("Must be the same user"));
            }
        };

        // Routes

        log.info("Initializing routes");

        app.get('/', userAuth, userOptional, routes.index);
        app.get('/login', userAuth, noUser, routes.login);
        app.post('/login', userAuth, noUser, routes.handleLogin);
        app.post('/logout', userAuth, userRequired, routes.handleLogout);
        app.get('/about', userAuth, userOptional, routes.about);
        app.get('/h8', userAuth, userRequired, routes.showH8);
        app.post('/h8', userAuth, userRequired, routes.doH8);
        app.get('/authorized/:hostname', routes.authorized);
        app.get('/.well-known/host-meta.json', routes.hostmeta);

        // Create a dialback client

        log.info("Initializing dialback client");

        client = new DialbackClient({
            hostname: config.hostname,
            app: app,
            bank: db,
            userAgent: ih8it.userAgent()
        });

        // Configure this global object

        Host.dialbackClient = client;

        // Let Web stuff get to config

        app.config = config;

        // For handling errors

        app.log = function(obj) {
            if (obj instanceof Error) {
                log.error(obj);
            } else {
                log.info(obj);
            }
        };

        // Start the app

        log.info({port: config.port, address: config.address}, "Starting app listener");

        app.listen(config.port, config.address, callback);

        // Start the bouncer

        if (bounce) {
            log.info({port: 80, address: config.address}, "Starting bounce listener");
            bounce.listen(80, config.address);
        }

    }], function(err) {
function onConnect() {
    morayClient.removeListener('error', onError);
    log.info('moray: connected %s', morayClient.toString());
    updateBucket(onBucket);
}
Ejemplo n.º 8
0
Archivo: app.js Proyecto: Qray/pump.io
    db.connect({}, function(err) {

        var useHTTPS = _(config).has('key'),
            useBounce = _(config).has('bounce') && config.bounce,
            app,
            io,
            bounce,
            maillog,
            smtp,
            from,
            requestLogger = function(log) {
                return function(req, res, next) {
                    var weblog = log.child({"req_id": uuid.v4(), component: "web"});
                    var end = res.end;
                    req.log = weblog;
                    res.end = function(chunk, encoding) {
                        var rec;
                        res.end = end;
                        res.end(chunk, encoding);
                        rec = {req: req, res: res};
                        if (_(req).has("remoteUser")) {
                            rec.user = req.remoteUser;
                        }
                        if (_(req).has("client")) {
                            rec.client = req.client;
                        }
                        weblog.info(rec);
                    };
                    next();
                };
            };

        if (err) {
            log.error(err);
            callback(err, null);
            return;
        }

        if (useHTTPS) {
            log.info("Setting up HTTPS server.");
            app = express.createServer({key: fs.readFileSync(config.key),
                                        cert: fs.readFileSync(config.cert)});

            if (useBounce) {
                log.info("Setting up micro-HTTP server to bounce to HTTPS.");
                bounce = express.createServer(function(req, res, next) {
                    var host = req.header('Host');
                    res.redirect('https://'+host+req.url, 301);
                });
            }

        } else {
            log.info("Setting up HTTP server.");
            app = express.createServer();
        }

        app.config = config;

        if (config.smtpserver) {

            maillog = log.child({component: "mail"});

            maillog.info("Connecting to SMTP server " + config.smtpserver);

            smtp = email.server.connect({
                user: config.smtpuser || null,
                password: config.smtppass || null,
                host: config.smtpserver,
                port: config.smtpport || null,
                ssl: config.smtpusessl || false
            });

            from = config.smtpfrom || "no-reply@"+hostname;

            app.sendEmail = function(props, callback) {

                var message = _.extend({"from": from}, props);

                smtp.send(message, function(err, message) {
                    if (err) {
                        maillog.error({msg: "Sending email",
                                       to: message.to || null,
                                       subject: message.subject || null});
                        callback(err, null);
                    } else {
                        maillog.info({msg: "Message sent",
                                      to: message.to || null,
                                      subject: message.subject || null});
                        callback(null, message);
                    }
                });
            };
        }

        var cleanup = config.cleanup || 600000;
        var dbstore = new DatabankStore(db, log, cleanup);

        if (!_(config).has("noweb") || !config.noweb) {
            app.session = express.session({secret: (_(config).has('sessionSecret')) ? config.sessionSecret : "insecure",
                                           store: dbstore});
        }

        // Configuration

        app.configure(function() {

            // Templates are in public
            app.set("views", __dirname + "/../public/template");
            app.set("view engine", "utml");
            app.use(requestLogger(log));
            app.use(rawBody);
            app.use(express.bodyParser());
            app.use(express.cookieParser());
            app.use(express.query());
            app.use(express.methodOverride());
            app.use(express.favicon());

            app.provider = new Provider(log);

            app.use(function(req, res, next) { 
                res.local("config", config);
                res.local("data", {});
                res.local("page", {});
                res.local("template", {});
                // Initialize null
                res.local("remoteUser", null);
                res.local("user", null);
                res.local("client", null);
                res.local("nologin", false);
                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);

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

        });

        app.error(function(err, req, res, next) {
            log.error(err);
            if (err instanceof HTTPError) {
                if (req.xhr || req.originalUrl.substr(0, 5) === '/api/') {
                    res.json({error: err.message}, err.code);
                } else if (req.accepts("html")) {
                    res.render("error", {page: {title: "Error"},
                                         data: {error: err}});
                } else {
                    res.writeHead(err.code, {"Content-Type": "text/plain"});
                    res.end(err.message);
                }
            } else {
                next(err);
            }
        });

        // Routes

        api.addRoutes(app);
        webfinger.addRoutes(app);
        dialback.addRoutes(app);
        clientreg.addRoutes(app);

        if (_.has(config, "uploaddir")) {
            // Simple boolean flag
            config.canUpload = true;
            uploads.addRoutes(app);
        }

        // Use "noweb" to disable Web site (API engine only)

        if (!_(config).has("noweb") || !config.noweb) {
            web.addRoutes(app);
        } else {
            // A route to show the API doc at root
            app.get("/", function(req, res, next) {

                var Showdown = require("showdown"),
                    converter = new Showdown.converter();

                Step(
                    function() {
                        fs.readFile(path.join(__dirname, "..", "API.md"), this);
                    },
                    function (err, data) {
                        var html, markdown;
                        if (err) {
                            next(err);
                        } else {
                            markdown = data.toString();
                            html = converter.makeHtml(markdown);
                            res.render("doc", {page: {title: "API"},
                                               data: {html: html}});
                        }
                    }
                );
            });
        }

        DatabankObject.bank = db;

        URLMaker.hostname = hostname;
        URLMaker.port = port;

        if (_(config).has('serverUser')) {
            app.on('listening', function() {
                process.setuid(config.serverUser);
            });
        }

        if (config.sockjs) {
            pumpsocket.connect(app, log);
        }

        app.run = function(callback) {
            var self = this,
                removeListeners = function() {
                    self.removeListener("listening", listenSuccessHandler);
                    self.removeListener("err", listenErrorHandler);
                },
                listenErrorHandler = function(err) {
                    removeListeners();
                    log.error(err);
                    callback(err);
                },
                listenSuccessHandler = function() {
                    var removeBounceListeners = function() {
                        bounce.removeListener("listening", bounceSuccess);
                        bounce.removeListener("err", bounceError);
                    },
                        bounceError = function(err) {
                            removeBounceListeners();
                            log.error(err);
                            callback(err);
                        },
                        bounceSuccess = function() {
                            log.info("Finished setting up bounce server.");
                            removeBounceListeners();
                            callback(null);
                        };
                    
                    log.info("Finished setting up main server.");

                    removeListeners();
                    if (useBounce) {
                        bounce.on("error", bounceError);
                        bounce.on("listening", bounceSuccess);
                        bounce.listen(80, hostname);
                    } else {
                        callback(null);
                    }
                };
            this.on("error", listenErrorHandler);
            this.on("listening", listenSuccessHandler);
            log.info("Listening on "+port+" for host " + address);
            this.listen(port, address);
        };

        callback(null, app);
    });
Ejemplo n.º 9
0
      connectionRemote.query('SELECT EXISTS(SELECT * FROM devices WHERE deviceId=\''+post.macid+'\') as find', function(err, rows, fields) {
      //console.log('Inside client connected '+val);
      
        if (err) 
          log.error(err);
        else{
            var find=rows[0]['find'];
           // console.log('Inside client connected '+find);
           if(find==0 && res[0]>9){ //check device is the new one, find=0 means new device found, no previous entry in the table
               //var devdis='INSERT INTO devices VALUES (DEFAULT,NULL,\''+post.macid+'\',NULL,2,1, DEFAULT,NULL,\''+res[2]+'\')';
               var thingspeak=null;
               if(res[2]==='bthm'){//for bthm
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3, field4, field5, field6) VALUES (\''+post.macid+'\', \'It records battery, temperature, humidity and moisture value\', 2,0, \'bthm\', \'packetId\', \'battery\', \'temperature\', \'humidity\', \'moisture\')';//table restructured
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It records battery, temperature, humidity and moisture value',
                      'field1'  :'batValue',
                      'field2'  :'tempValue',
                      'field3'  :'humidValue',
                      'field4'  :'moistValue',
                      'field5'  :'packetId'
                  }
               }
               else if(res[2]==='b'){//for hub
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3) VALUES (\''+post.macid+'\', \'It is a Hub conneccting various sensor nodes\', 2,0, \'b\', \'packetId\', \'battery\')';//for the normal Hub connection
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It is a Hub conneccting various sensor nodes',
                      'field1'  :'batValue',
                      'field2'  :'packetId'
                  }
               }
               else if(res[2]==='bm'){//for moisture only sensor
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3, field4) VALUES (\''+post.macid+'\', \'It records battery and moisture value\', 2,0, \'bm\', \'packetId\', \'battery\', \'moisture\')';//for the moisture sensor only
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It records battery and moisture value',
                      'field1'  :'batValue',
                      'field2'  :'moistValue',
                      'field3'  :'packetId'
                  }
               }
                connectionlocal.query(devdis, function(err, rows, fields) { //insert into the table 
                  if (err) 
                  log.error(err);
                  else{
                    log.info('New Sensor Device found, adding '+post.macid+' into device table');
                    var jsonS={
                         "action":'Device',
                         "data"  :"New Sensor Device found, adding "+post.macid+" into device table"
                    };
                    sendAll(jsonS);//sending button status to all device
                    client.createChannel(1, thingspeakchannelrow, function(err) {
                      if (!err) {//channel creation done
                          log.info('New channel created for sensor: '+res[0]+' type '+res[2]);
                          var jsonS={
                               "action":'thingspeak',
                               "data"  :"New channel created for sensor: "+res[0]+" type "+res[2]
                          };
                          sendAll(jsonS);//sending button status to all device
                          attachChannel(res[0]);//attaching the channel;
                      }
                      else
                      {
                        console.log(err)
                      }
                     });
                    connectionRemote.query(devdis, function(err, rows, fields) { //insert into the remote table 
                      if (err) 
                      log.error(err);
                      else{
                        log.info('New Sensor Device found, adding '+post.macid+' into Remote device table');
                      }
                    });
                  }
                });
                  
           }//end of find if condition

           else{
             log.info('Device '+post.macid+' sent new data');
            //var devdis='UPDATE devices SET status=1, seen= now() where status in (0,2) and macid=\''+post.macid+'\'';
             deviceStatus(post.macid, function(status,row){
                if(status==0){//insert only if the last row for that device was vice versa
                  var devdis='INSERT INTO deviceStatus VALUES (DEFAULT,\''+row+'\',1, DEFAULT)';
                  connectionlocal.query(devdis, function(err, rows, fields) { //update the table //query3
                    if (err)
                      log.error("MYSQL ERROR "+err);
                    else{
                      //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                      log.info('Device '+row+' went online');
                          connectionRemote.query(devdis, function(err, rows, fields) { //update the remote table //query3
                        if (err)
                          log.error("MYSQL ERROR "+err);
                        else{
                          //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                          log.info('Updated remote table for the online status');
                        }
                      });
                    }
                  });
                }
                else if (status==2){//if no last row exists
                  var devdis='INSERT INTO deviceStatus VALUES (DEFAULT,\''+row+'\',1, DEFAULT)';
                  connectionlocal.query(devdis, function(err, rows, fields) { //update the table //query3
                    if (err)
                      log.error("MYSQL ERROR "+err);
                    else{
                      //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                      log.info('Device '+row+' went online');
                      connectionRemote.query(devdis, function(err, rows, fields) { //update the remote table //query3
                        if (err)
                          log.error("MYSQL ERROR "+err);
                        else{
                          //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                          log.info('Updated remote table for the online status');
                        }
                      });
                    }
                  });
                }
             });
             var jsonS={
                     "deviceId":post.macid,
                     "status":1
               };
               sendAll(jsonS);//sending  online status to website
            }

         }
       });
Ejemplo n.º 10
0
Archivo: app.js Proyecto: e14n/pump2rss
    function(callback) {

        var app,
            bounce,
            client,
            requestLogger = function(log) {
                return function(req, res, next) {
                    var weblog = log.child({"req_id": uuid.v4(), component: "web"});
                    var end = res.end;
                    req.log = weblog;
                    res.end = function(chunk, encoding) {
                        var rec;
                        res.end = end;
                        res.end(chunk, encoding);
                        rec = {req: req, res: res};
                        weblog.info(rec);
                    };
                    next();
                };
            };

        // Set global databank info

        DatabankObject.bank = db;

        if (config.key) {

            log.info("Using SSL");

            app = express.createServer({key: fs.readFileSync(config.key),
                                        cert: fs.readFileSync(config.cert)});
            bounce = express.createServer(function(req, res, next) {
                var host = req.header('Host');
                res.redirect('https://'+host+req.url, 301);
            });

        } else {

            log.info("Not using SSL");

            app = express.createServer();
        }

        // Configuration

        log.info("Configuring app");

        app.configure(function(){
            var serverVersion = 'pump2rss/'+pump2rss.version + ' express/'+express.version + ' node.js/'+process.version,
                versionStamp = function(req, res, next) {
                    res.setHeader('Server', serverVersion);
                    next();
                },
                appObject = function(req, res, next) {
                    req.pump2rss = pump2rss;
                    res.local("pump2rss", pump2rss);
                    next();
                };

            app.set('views', __dirname + '/views');
            app.set('view engine', 'utml');
            app.use(requestLogger(log));
            app.use(versionStamp);
            app.use(appObject);
            app.use(express.bodyParser());
            app.use(app.router);
            app.use(express.static(__dirname + '/public'));
        });

        app.configure('development', function(){
            app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
        });

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

        // middleware

        var reqUser = function(req, res, next) {

            var webfinger = req.params.webfinger;

            User.ensureUser(webfinger, function(err, user) {
                if (err) {
                    next(err);
                } else {
                    req.user = user;
                    next();
                }
            });
        };

        // Routes

        log.info("Initializing routes");

        app.get('/', routes.index);
        app.post('/feed', routes.redirectFeed);
        app.get('/feed/:webfinger.atom', reqUser, routes.showFeed);
        app.get('/.well-known/host-meta.json', routes.hostmeta);

        // Create a dialback client

        log.info("Initializing dialback client");

        client = new DialbackClient({
            hostname: config.hostname,
            app: app,
            bank: db,
            userAgent: pump2rss.userAgent()
        });

        // Configure this global object

        Host.dialbackClient = client;

        // Let Web stuff get to config

        app.config = config;

        // For handling errors

        app.log = function(obj) {
            if (obj instanceof Error) {
                log.error(obj);
            } else {
                log.info(obj);
            }
        };

        // Start the app

        log.info({port: config.port, address: config.address}, "Starting app listener");

        app.listen(config.port, config.address, callback);

        // Start the bouncer

        if (bounce) {
            log.info({port: 80, address: config.address}, "Starting bounce listener");
            bounce.listen(80, config.address);
        }

    }], function(err) {
Ejemplo n.º 11
0
                        defaults);
} else {
    config = defaults;
}

if (config.logfile) {
    logParams.streams = [{path: config.logfile}];
} else if (config.nologger) {
    logParams.streams = [{path: "/dev/null"}];
} else {
    logParams.streams = [{stream: process.stderr}];
}

log = new Logger(logParams);

log.info("Initializing addhostname.js");

if (!config.params) {
    if (config.driver == "disk") {
        config.params = {dir: "/var/lib/pump2status/"};
    } else {
        config.params = {};
    }
}

// Define the database schema

if (!config.params.schema) {
    config.params.schema = {};
}
Ejemplo n.º 12
0
 loadModels( function(){
     logger.info( 'Loaded Models' );
     if (callback) callback();
 } );
Ejemplo n.º 13
0
 client.updateChannel(65, { "field1":devices[1].dashboard_data.Temperature,"field2":devices[1].dashboard_data.CO2,"field3":devices[1].dashboard_data.Humidity,"field4":devices[1].dashboard_data.Noise,"field5":devices[1].dashboard_data.Pressure, "field6":devices[1].wifi_status}, function(err, resp) {
   if (!err && resp > 0) {
       log.info('Thingspeak feed update successfully for NetAtmo ERTS-Lab');
   }
 });
Ejemplo n.º 14
0
 client.updateChannel(64, { "field1":modules[2].dashboard_data.Temperature,"field2":modules[2].dashboard_data.CO2,"field3":modules[2].dashboard_data.Humidity,"field4":modules[2].battery_vp}, function(err, resp) {
   if (!err && resp > 0) {
       log.info('Thingspeak feed update successfully for NetAtmo ERTS-IN');
   }
 });
Ejemplo n.º 15
0
		deployer.close(function () {
			log.info('deployer cleaned up');
			/* normal Node exit */
		});
Ejemplo n.º 16
0
 ws.onopen = function() {
   log.info('connected to websocket server');
 };
Ejemplo n.º 17
0
Archivo: app.js Proyecto: e14n/ih8.it
                        defaults);
} else {
    config = defaults;
}

if (config.logfile) {
    logParams.streams = [{path: config.logfile}];
} else if (config.nologger) {
    logParams.streams = [{path: "/dev/null"}];
} else {
    logParams.streams = [{stream: process.stderr}];
}

log = new Logger(logParams);

log.info("Initializing");

// Configure the service object

log.info({name: config.name, 
          description: config.description, 
          hostname: config.hostname},
         "Initializing ih8it object");

ih8it.name        = config.name;
ih8it.description = config.description;
ih8it.hostname    = config.hostname;

ih8it.protocol = (config.key) ? "https" : "http";

if (!config.params) {
Ejemplo n.º 18
0
serialPort.on("open", function () {
  log.info(env.portNo+' port opened');
  serialPort.flush();//flushing previous data
  attachChannels(); //attaching the api-keys
  //console.log('open');
  var count=0
  var res, dataout;
  serialPort.on('error', function(err) {
    log.error("Some error in reading the data "+err);
    var jsonS={
         "action":'Serial Error',
         "data"  :"Some error in reading the data "+err
    };
    sendAll(jsonS);//sending button status to all device
  });
  serialPort.on('disconnect', function(disc) {
    log.error("Port closed: "+disc);
    var jsonS={
         "action":'Serial Error',
         "data"  :"Port closed: "+disc
    };
    sendAll(jsonS);//sending button status to all device
  });
  serialPort.on('data', function(data) {
    log.info('data received: '+data);
    var jsonS={
         "action":'Serial data',
         "data"  :"data received: "+data
    };
    sendAll(jsonS);//sending button status to all device
    
    
    //console.log("Time: "+date);

    dataout=String(data);
    res = dataout.split(",");//getting strings
   // console.log(res[0]);//stores device id
    //console.log(res[1]);//stored packet number or id
   // console.log(res[2]);//gets device type
    
    
    //find if the device is new
    var post  = {macid: res[0]};
    //if(res[2].substring()){ //check if the data is corrupt or not by checking the third parameter, string

      connectionRemote.query('SELECT EXISTS(SELECT * FROM devices WHERE deviceId=\''+post.macid+'\') as find', function(err, rows, fields) {
      //console.log('Inside client connected '+val);
      
        if (err) 
          log.error(err);
        else{
            var find=rows[0]['find'];
           // console.log('Inside client connected '+find);
           if(find==0 && res[0]>9){ //check device is the new one, find=0 means new device found, no previous entry in the table
               //var devdis='INSERT INTO devices VALUES (DEFAULT,NULL,\''+post.macid+'\',NULL,2,1, DEFAULT,NULL,\''+res[2]+'\')';
               var thingspeak=null;
               if(res[2]==='bthm'){//for bthm
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3, field4, field5, field6) VALUES (\''+post.macid+'\', \'It records battery, temperature, humidity and moisture value\', 2,0, \'bthm\', \'packetId\', \'battery\', \'temperature\', \'humidity\', \'moisture\')';//table restructured
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It records battery, temperature, humidity and moisture value',
                      'field1'  :'batValue',
                      'field2'  :'tempValue',
                      'field3'  :'humidValue',
                      'field4'  :'moistValue',
                      'field5'  :'packetId'
                  }
               }
               else if(res[2]==='b'){//for hub
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3) VALUES (\''+post.macid+'\', \'It is a Hub conneccting various sensor nodes\', 2,0, \'b\', \'packetId\', \'battery\')';//for the normal Hub connection
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It is a Hub conneccting various sensor nodes',
                      'field1'  :'batValue',
                      'field2'  :'packetId'
                  }
               }
               else if(res[2]==='bm'){//for moisture only sensor
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3, field4) VALUES (\''+post.macid+'\', \'It records battery and moisture value\', 2,0, \'bm\', \'packetId\', \'battery\', \'moisture\')';//for the moisture sensor only
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It records battery and moisture value',
                      'field1'  :'batValue',
                      'field2'  :'moistValue',
                      'field3'  :'packetId'
                  }
               }
                connectionlocal.query(devdis, function(err, rows, fields) { //insert into the table 
                  if (err) 
                  log.error(err);
                  else{
                    log.info('New Sensor Device found, adding '+post.macid+' into device table');
                    var jsonS={
                         "action":'Device',
                         "data"  :"New Sensor Device found, adding "+post.macid+" into device table"
                    };
                    sendAll(jsonS);//sending button status to all device
                    client.createChannel(1, thingspeakchannelrow, function(err) {
                      if (!err) {//channel creation done
                          log.info('New channel created for sensor: '+res[0]+' type '+res[2]);
                          var jsonS={
                               "action":'thingspeak',
                               "data"  :"New channel created for sensor: "+res[0]+" type "+res[2]
                          };
                          sendAll(jsonS);//sending button status to all device
                          attachChannel(res[0]);//attaching the channel;
                      }
                      else
                      {
                        console.log(err)
                      }
                     });
                    connectionRemote.query(devdis, function(err, rows, fields) { //insert into the remote table 
                      if (err) 
                      log.error(err);
                      else{
                        log.info('New Sensor Device found, adding '+post.macid+' into Remote device table');
                      }
                    });
                  }
                });
                  
           }//end of find if condition

           else{
             log.info('Device '+post.macid+' sent new data');
            //var devdis='UPDATE devices SET status=1, seen= now() where status in (0,2) and macid=\''+post.macid+'\'';
             deviceStatus(post.macid, function(status,row){
                if(status==0){//insert only if the last row for that device was vice versa
                  var devdis='INSERT INTO deviceStatus VALUES (DEFAULT,\''+row+'\',1, DEFAULT)';
                  connectionlocal.query(devdis, function(err, rows, fields) { //update the table //query3
                    if (err)
                      log.error("MYSQL ERROR "+err);
                    else{
                      //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                      log.info('Device '+row+' went online');
                          connectionRemote.query(devdis, function(err, rows, fields) { //update the remote table //query3
                        if (err)
                          log.error("MYSQL ERROR "+err);
                        else{
                          //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                          log.info('Updated remote table for the online status');
                        }
                      });
                    }
                  });
                }
                else if (status==2){//if no last row exists
                  var devdis='INSERT INTO deviceStatus VALUES (DEFAULT,\''+row+'\',1, DEFAULT)';
                  connectionlocal.query(devdis, function(err, rows, fields) { //update the table //query3
                    if (err)
                      log.error("MYSQL ERROR "+err);
                    else{
                      //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                      log.info('Device '+row+' went online');
                      connectionRemote.query(devdis, function(err, rows, fields) { //update the remote table //query3
                        if (err)
                          log.error("MYSQL ERROR "+err);
                        else{
                          //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                          log.info('Updated remote table for the online status');
                        }
                      });
                    }
                  });
                }
             });
             var jsonS={
                     "deviceId":post.macid,
                     "status":1
               };
               sendAll(jsonS);//sending  online status to website
            }

         }
       });
    ///
    if(res[2]==='bthm')
    {
      //console.log(res[3]);//gets battery
      //console.log(res[4]);//gets temp
      //console.log(res[5]);//gets humidity
     // console.log(res[6]);//gets moisture
      if(!isNaN(res[3])&&!isNaN(res[4])&&!isNaN(res[5])&&!isNaN(res[6]))
      {
        var sensorVal='INSERT INTO feeds(device_Id, field1, field2, field3, field4, field5, field6) VALUES (\''+res[0]+'\',\''+res[2]+'\',\''+res[1]+'\',\''+res[3]+'\',\''+res[4]+'\',\''+res[5]+'\',\''+res[6]+'\')';
        connectionlocal.query(sensorVal, function(err, rows, fields) { //insert into the feed table 
          if (err)
            log.error('Error in inserting serial data, error: '+err);
          else{
            // log.info('Feed added for '+res[0]+' on '+date);
            connectionRemote.query(sensorVal, function(err, rows, fields) { //insert into the remote feed table 
              if (err){
                log.error('Error in inserting serial data, error: '+err);
                var jsonS={
                     "action":'Error',
                     "data"  :"Error in inserting serial data, error: "+err
                };
                sendAll(jsonS);//sending button status to all device
              }
              else
                 log.info('Remote feed updated with new data');
            });
          }
          });
          var jsonS={
            "deviceId":res[0],
            "action": 'data',
             "packetNo":res[1],
             "deviceType":res[2],
             "batValue":res[3],
             "tempValue":res[4],
             "humidityValue":res[5],
             "moistValue":res[6]
          };
          sendAll(jsonS);//to websocket client
          findChannel(res[0], function(channel_Id){//updating the thingspeak feed
                client.updateChannel(channel_Id, { "field1":res[3],"field2":res[4],"field3":res[5],"field4":res[6],"field5":res[1]}, function(err, resp) {
                if (!err && resp > 0) {
                    log.info('Thingspeak feed update successfully for channel id '+channel_Id);
                    var jsonS={
                         "action":'thingspeak',
                         "data"  :"Thingspeak feed update successfully for channel id "+channel_Id
                    };
                    sendAll(jsonS);//sending button status to all device
                }
                });
             

          });

          
      }
      else
         log.warn('Packet is corrupted, client id: '+res[0]);
    }
    else if(res[2]==='bm')
    {
      var sensorVal='INSERT INTO feeds(device_Id, field1, field2, field3, field4) VALUES (\''+res[0]+'\',\''+res[2]+'\',\''+res[1]+'\',\''+res[3]+'\',\''+res[4]+'\')';//only battery and moisture
      connectionlocal.query(sensorVal, function(err, rows, fields) { //insert into the feed table 
        if (err){
         log.error('Error in inserting serial data, error: '+err);
         var jsonS={
               "action":'Error',
               "data"  :"Error in inserting serial data, error: "+err
          };
          sendAll(jsonS);//sending button status to all device
        }
        else{
           //log.info('Feed added for '+res[0]+' on '+date);
           connectionRemote.query(sensorVal, function(err, rows, fields) { //insert into the feed table 
              if (err){
                 log.error('Error in inserting serial data, error: '+err);
                 var jsonS={
                       "action":'Error',
                       "data"  :"Error in inserting serial data, error: "+err
                  };
                  sendAll(jsonS);//sending button status to all device
               }
              else
                 log.info('Remote feed updated with new data');
            });
         }
      });
      var jsonS={
        "deviceId":res[0],
        "action": 'data',
         "packetNo":res[1],
         "deviceType":res[2],
         "batValue":res[3],
         "moistValue":res[4]
      };
      sendAll(jsonS);//to websocket client
      findChannel(res[0], function(channel_Id){//updating the thingspeak feed
            client.updateChannel(channel_Id, { "field1":res[3],"field2":res[4],"field3":res[1]}, function(err, resp) {
            if (!err && resp > 0) {
                log.info('Thingspeak feed update successfully for channel id '+channel_Id);
                var jsonS={
                     "action":'thingspeak',
                     "data"  :"Thingspeak feed update successfully for channel id "+channel_Id
                };
                sendAll(jsonS);//sending button status to all device
            }
            });
         

      });

    }
    else if(res[2]==='b')
    {
      var sensorVal='INSERT INTO feeds(device_Id, field1, field2, field3) VALUES (\''+res[0]+'\',\''+res[2]+'\',\''+res[1]+'\',\''+res[3]+'\')';//only battery
      connectionlocal.query(sensorVal, function(err, rows, fields) { //insert into the feed table 
        if (err)
         log.error('Error in inserting serial data, error: '+err);
        else{
           //log.info('Feed added for '+res[0]+' on '+date);
           connectionRemote.query(sensorVal, function(err, rows, fields) { //insert into the feed table 
              if (err){
               log.error('Error in inserting serial data, error: '+err);
               var jsonS={
                     "action":'Error',
                     "data"  :"Error in inserting serial data, error: "+err
                };
                sendAll(jsonS);//sending button status to all device
              }
              else
                 log.info('Remote feed updated with new data');
            });
         }
      });
      var jsonS={
        "deviceId":res[0],
        "action": 'data',
         "packetNo":res[1],
         "deviceType":res[2],
         "batValue":res[3]
      };
      sendAll(jsonS);//to websocket client
      findChannel(res[0], function(channel_Id){//updating the thingspeak feed
            client.updateChannel(channel_Id, { "field1":res[3],"field2":res[1]}, function(err, resp) {
            if (!err && resp > 0) {
                log.info('Thingspeak feed update successfully for channel id '+channel_Id);
                var jsonS={
                     "action":'thingspeak',
                     "data"  :"Thingspeak feed update successfully for channel id "+channel_Id
                };
                sendAll(jsonS);//sending button status to all device
            }
            });
         

      });
    }
    //count++;
    //console.log('data count : ' + count);
  //}
  //else
       //  log.warn('Packet is corrupted, client id: '+res[0]+' '+date);
  });
  serialPort.on('error', function(errors) {
     log.error('error in reading: ' + errors);
  });

});
Ejemplo n.º 19
0
test('instantiate from persisted toplogy', function(t) {
  var ring = chash.ring;
  chash2 = fash.createHash({
    log: LOG,
    algorithm: 'sha256',
    nodes: ring,
    numberOfReplicas: 2
  });
  LOG.info('chash2', chash2.nodeMap);
  LOG.info('chash', chash.nodeMap);
  LOG.info('chash ring', chash.ring);
  LOG.info('chash2 ring', chash2.ring);

  t.ok(chash2);
  t.equal(chash2.ring.length, chash.ring.length, 'ring sizes should be identical');
  chash.ring.forEach(function(node, index) {
    var node2 = chash2.ring[index];
    t.ok(node._hashSpace.eq(node2._hashSpace));
    t.equal(node.hashSpace, node2.hashSpace);
    t.equal(node.node, node2.node);
    t.equal(node.replica, node2.replica);
  });
  for (var i = 0; i < numberOfKeys; i++) {
    var random = Math.random().toString(33);
    var key = random.substring(Math.floor(Math.random() * random.length));
    var node1 = chash.getNode(key);
    var node2 = chash2.getNode(key);
    t.equal(node1, node2);
  }

  chash.addNode('FOOBAR');
  chash2.addNode('FOOBAR');
  t.equal(chash2.ring.length, chash.ring.length, 'ring sizes should be identical');
  chash.ring.forEach(function(node, index) {
    var node2 = chash2.ring[index];
    t.ok(node._hashSpace.eq(node2._hashSpace));
    t.equal(node.hashSpace, node2.hashSpace);
    t.equal(node.node, node2.node);
    t.equal(node.replica, node2.replica);
  });
  for (var i = 0; i < numberOfKeys; i++) {
    var random = Math.random().toString(33);
    var key = random.substring(Math.floor(Math.random() * random.length));
    var node1 = chash.getNode(key);
    var node2 = chash2.getNode(key);
    t.equal(node1, node2);
  }

  chash.removeNode('B');
  chash2.removeNode('B');
  t.equal(chash2.ring.length, chash.ring.length, 'ring sizes should be identical');
  LOG.info('chash', chash.ring);
  LOG.info('chash2', chash2.ring);
  chash.ring.forEach(function(node, index) {
    var node2 = chash2.ring[index];
    t.ok(node._hashSpace.eq(node2._hashSpace));
    t.equal(node.hashSpace, node2.hashSpace);
    t.equal(node.node, node2.node);
    t.equal(node.replica, node2.replica);
  });
  for (var i = 0; i < numberOfKeys; i++) {
    var random = Math.random().toString(33);
    var key = random.substring(Math.floor(Math.random() * random.length));
    var node1 = chash.getNode(key);
    var node2 = chash2.getNode(key);
    t.equal(node1, node2);
  }
  t.end();
});
Ejemplo n.º 20
0
 _.each(plugins, function(plugin, name) {
     if (_.isFunction(plugin.initializeSchema)) {
         log.info({plugin: name}, "Initializing schema.");
         plugin.initializeSchema(params.schema);
     }
 });
Ejemplo n.º 21
0
Archivo: app.js Proyecto: obra/pump.io
    db.connect({}, function(err) {

        var useHTTPS = _(config).has('key'),
            useBounce = _(config).has('bounce') && config.bounce,
            app,
            io,
            bounce,
            dialbackClient,
            requestLogger = function(log) {
                return function(req, res, next) {
                    var weblog = log.child({"req_id": uuid.v4(), component: "web"});
                    var end = res.end;
                    req.log = weblog;
                    res.end = function(chunk, encoding) {
                        var rec;
                        res.end = end;
                        res.end(chunk, encoding);
                        rec = {req: req, res: res};
                        if (_(req).has("principal")) {
                            rec.principal = req.principal;
                        }
                        if (_(req).has("client")) {
                            rec.client = req.client;
                        }
                        weblog.info(rec);
                    };
                    next();
                };
            };

        if (err) {
            log.error(err);
            callback(err, null);
            return;
        }

        if (useHTTPS) {
            log.info("Setting up HTTPS server.");
            app = express.createServer({key: fs.readFileSync(config.key),
                                        cert: fs.readFileSync(config.cert)});

            if (useBounce) {
                log.info("Setting up micro-HTTP server to bounce to HTTPS.");
                bounce = express.createServer(function(req, res, next) {
                    var host = req.header('Host');
                    res.redirect('https://'+host+req.url, 301);
                });
            }

        } else {
            log.info("Setting up HTTP server.");
            app = express.createServer();
        }

        app.config = config;

        if (config.smtpserver) {
            // harmless flag
            config.haveEmail = true;
            Mailer.setup(config, log);
        }

        var cleanup = config.cleanup || 600000;
        var dbstore = new DatabankStore(db, log, cleanup);

        if (!_(config).has("noweb") || !config.noweb) {
            app.session = express.session({secret: (_(config).has('sessionSecret')) ? config.sessionSecret : "insecure",
                                           store: dbstore});
        }

        // Configuration

        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 = urlparse(URLMaker.makeURL("/")).host;
                    if (host && host.toLowerCase() != urlHost) {
                        res.redirect(URLMaker.makeURL(req.url), 301);
                    } else {
                        next();
                    }
                };

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

            app.use(requestLogger(log));
	    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);

            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);

        });

        app.error(function(err, req, res, next) {
            log.error(err);
            if (err instanceof HTTPError) {
                if (req.xhr || req.originalUrl.substr(0, 5) === '/api/') {
                    res.json({error: err.message}, err.code);
                } else if (req.accepts("html")) {
                    res.status(err.code);
                    res.render("error", {page: {title: "Error"},
                                         error: err});
                } else {
                    res.writeHead(err.code, {"Content-Type": "text/plain"});
                    res.end(err.message);
                }
            } else {
                next(err);
            }
        });

        // Routes

        api.addRoutes(app);
        webfinger.addRoutes(app);
        clientreg.addRoutes(app);
        shared.addRoutes(app);

        if (_.has(config, "uploaddir")) {
            // Simple boolean flag
            config.canUpload = true;
            uploads.addRoutes(app);
            Image.uploadDir = config.uploaddir;
        }

        if (config.requireEmail) {
            confirm.addRoutes(app);
        }

        // Use "noweb" to disable Web site (API engine only)

        if (!_(config).has("noweb") || !config.noweb) {
            web.addRoutes(app);
        } else {
            // A route to show the API doc at root
            app.get("/", function(req, res, next) {

                var Showdown = require("showdown"),
                    converter = new Showdown.converter();

                Step(
                    function() {
                        fs.readFile(path.join(__dirname, "..", "API.md"), this);
                    },
                    function (err, data) {
                        var html, markdown;
                        if (err) {
                            next(err);
                        } else {
                            markdown = data.toString();
                            html = converter.makeHtml(markdown);
                            res.render("doc", {page: {title: "API"},
                                               html: html});
                        }
                    }
                );
            });
        }

        DatabankObject.bank = db;

        URLMaker.hostname = hostname;
        URLMaker.port = (config.urlPort) ? config.urlPort : port;

        Distributor.log = log.child({component: "distributor"});

        if (_(config).has('serverUser')) {
            app.on('listening', function() {
                process.setuid(config.serverUser);
            });
        }

        if (config.sockjs) {
            pumpsocket.connect(app, log);
        }

        if (config.firehose) {
            log.info({firehose: config.firehose}, "Setting up firehose");
            Firehose.setup(config.firehose, log);
        }

        if (config.spamhost) {
            if (!config.spamclientid ||
                !config.spamclientsecret) {
                throw new Error("Need client ID and secret for spam host");
            }
            log.info({spamhost: config.spamhost}, "Configuring spam host");
            ActivitySpam.init({
                host: config.spamhost,
                clientID: config.spamclientid,
                clientSecret: config.spamclientsecret,
                logger: log
            });
        }

        dialbackClient = new DialbackClient({
            hostname: hostname,
            bank: db,
            app: app,
            url: "/api/dialback"
        });

        Credentials.dialbackClient = dialbackClient;

        // Each worker takes a turn cleaning up, so *this* worker does
        // its cleanup once every config.workers cleanup periods

        var workers = config.workers || 1;
        var cleanupTime = 1200 * workers * 1000;

        // We set a timer so we start with an offset, instead of having
        // all workers start at almost the same time

        setTimeout(function() {
            log.info("Cleaning up old OAuth nonces");
            Nonce.cleanup();
            setInterval(function() {
                log.info("Cleaning up old OAuth nonces");
                Nonce.cleanup();
            }, cleanupTime);
        }, Math.floor(Math.random() * cleanupTime));

        app.run = function(callback) {
            var self = this,
                removeListeners = function() {
                    self.removeListener("listening", listenSuccessHandler);
                    self.removeListener("err", listenErrorHandler);
                },
                listenErrorHandler = function(err) {
                    removeListeners();
                    log.error(err);
                    callback(err);
                },
                listenSuccessHandler = function() {
                    var removeBounceListeners = function() {
                        bounce.removeListener("listening", bounceSuccess);
                        bounce.removeListener("err", bounceError);
                    },
                        bounceError = function(err) {
                            removeBounceListeners();
                            log.error(err);
                            callback(err);
                        },
                        bounceSuccess = function() {
                            log.info("Finished setting up bounce server.");
                            removeBounceListeners();
                            callback(null);
                        };
                    
                    log.info("Finished setting up main server.");

                    removeListeners();
                    if (useBounce) {
                        bounce.on("error", bounceError);
                        bounce.on("listening", bounceSuccess);
                        bounce.listen(80, address);
                    } else {
                        callback(null);
                    }
                };
            this.on("error", listenErrorHandler);
            this.on("listening", listenSuccessHandler);
            log.info("Listening on "+port+" for host " + address);
            this.listen(port, address);
        };

        callback(null, app);
    });
Ejemplo n.º 22
0
 _.each(plugins, function(plugin, name) {
     if (_.isFunction(plugin.initializeApp)) {
         log.info({plugin: name}, "Initializing app.");
         plugin.initializeApp(app);
     }
 });
Ejemplo n.º 23
0
 bounceSuccess = function() {
     log.info("Finished setting up bounce server.");
     removeBounceListeners();
     callback(null);
 };
Ejemplo n.º 24
0
var makeApp = function(config, callback) {

    var params,
        defaults = {port: 31337,
                    hostname: "127.0.0.1",
                    site: "pump.io",
                    sockjs: true,
                    debugClient: false,
                    firehose: "ofirehose.com",
                    requireEmail: false,
                    disableRegistration: false,
                    compress: false,
		    urlPort: null,
		    urlPath: null,
                    plugins: [],
		    redirectToCanonical: true,
		    redirectAddressToCanonical: false},
        port,
        hostname,
        address,
        log,
        db,
        logParams = {
            name: "pump.io",
            serializers: {
                req: Logger.stdSerializers.req,
                res: Logger.stdSerializers.res,
                principal: function(principal) {
                    if (principal) {
                        return {id: principal.id, type: principal.objectType};
                    } else {
                        return {id: "<none>"};
                    }
                },
                client: function(client) {
                    if (client) {
                        return {key: client.consumer_key, title: client.title || "<none>"};
                    } else {
                        return {key: "<none>", title: "<none>"};
                    }
                }
            }
        },
        plugins = {};

    // Fill in defaults if they're not there

    config = _.defaults(config, defaults);

    port     = config.port;
    hostname = config.hostname;
    address  = config.address || config.hostname;

    if (process.getuid) {
        if (port < 1024 && process.getuid() !== 0) {
            callback(new Error("Can't listen to ports lower than 1024 on POSIX systems unless you're root."), null);
            return;
        }
    }

    if (config.logfile) {
        logParams.streams = [{path: config.logfile}];
    } else if (config.nologger) {
        logParams.streams = [{path: "/dev/null"}];
    } else {
        logParams.streams = [{stream: process.stderr}];
    }

    log = new Logger(logParams);

    log.info("Initializing pump.io");

    // Initialize plugins

    _.each(config.plugins, function(pluginName) {
        log.info({plugin: pluginName}, "Initializing plugin.");
        plugins[pluginName] = require(pluginName);
        if (_.isFunction(plugins[pluginName].initializeLog)) {
            plugins[pluginName].initializeLog(log);
        }
    });

    // Initiate the DB

    if (_(config).has("params")) {
        params = config.params;
    } else {
        params = {};
    }

    if (_(params).has("schema")) {
        _.extend(params.schema, schema);
    } else {
        params.schema = schema;
    }

    // So they can add their own types to the schema

    _.each(plugins, function(plugin, name) {
        if (_.isFunction(plugin.initializeSchema)) {
            log.info({plugin: name}, "Initializing schema.");
            plugin.initializeSchema(params.schema);
        }
    });

    db = Databank.get(config.driver, params);

    // Connect...

    log.info("Connecting to databank with driver '"+config.driver+"'");

    db.connect({}, function(err) {

        var useHTTPS = _(config).has('key'),
            useBounce = _(config).has('bounce') && config.bounce,
            app,
            io,
            bounce,
            dialbackClient,
            requestLogger = function(log) {
                return function(req, res, next) {
                    var weblog = log.child({"req_id": uuid.v4(), component: "web"});
                    var end = res.end;
                    req.log = weblog;
                    res.end = function(chunk, encoding) {
                        var rec;
                        res.end = end;
                        res.end(chunk, encoding);
                        rec = {req: req, res: res};
                        if (_(req).has("principal")) {
                            rec.principal = req.principal;
                        }
                        if (_(req).has("client")) {
                            rec.client = req.client;
                        }
                        weblog.info(rec);
                    };
                    next();
                };
            };

        if (err) {
            log.error(err);
            callback(err, null);
            return;
        }

        if (useHTTPS) {
            log.info("Setting up HTTPS server.");
            app = express.createServer({key: fs.readFileSync(config.key),
                                        cert: fs.readFileSync(config.cert)});

            if (useBounce) {
                log.info("Setting up micro-HTTP server to bounce to HTTPS.");
                bounce = express.createServer(function(req, res, next) {
                    var host = req.header('Host');
                    res.redirect('https://'+host+req.url, 301);
                });
            }

        } else {
            log.info("Setting up HTTP server.");
            app = express.createServer();
        }

        app.config = config;

        if (config.smtpserver) {
            // harmless flag
            config.haveEmail = true;
            Mailer.setup(config, log);
        }

        var cleanup = config.cleanup || 600000;
        var dbstore = new DatabankStore(db, log, cleanup);

        if (!_(config).has("noweb") || !config.noweb) {
            app.session = express.session({secret: (_(config).has('sessionSecret')) ? config.sessionSecret : "insecure",
                                           store: dbstore});
        }

        // Configuration

        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);

            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);

        });

        app.error(function(err, req, res, next) {
            log.error(err);
            if (err instanceof HTTPError) {
                if (req.xhr || req.originalUrl.substr(0, 5) === '/api/') {
                    res.json({error: err.message}, err.code);
                } else if (req.accepts("html")) {
                    res.status(err.code);
                    res.render("error", {page: {title: "Error"},
                                         error: err});
                } else {
                    res.writeHead(err.code, {"Content-Type": "text/plain"});
                    res.end(err.message);
                }
            } else {
                next(err);
            }
        });

        // Routes

        api.addRoutes(app);
        webfinger.addRoutes(app);
        clientreg.addRoutes(app);
        shared.addRoutes(app);

        if (_.has(config, "uploaddir")) {
            // Simple boolean flag
            config.canUpload = true;
            uploads.addRoutes(app);
            Image.uploadDir = config.uploaddir;
        }

        if (config.requireEmail) {
            confirm.addRoutes(app);
        }

        // Use "noweb" to disable Web site (API engine only)

        if (!_(config).has("noweb") || !config.noweb) {
            web.addRoutes(app);
        } else {
            // A route to show the API doc at root
            app.get("/", function(req, res, next) {

                var Showdown = require("showdown"),
                    converter = new Showdown.converter();

                Step(
                    function() {
                        fs.readFile(path.join(__dirname, "..", "API.md"), this);
                    },
                    function (err, data) {
                        var html, markdown;
                        if (err) {
                            next(err);
                        } else {
                            markdown = data.toString();
                            html = converter.makeHtml(markdown);
                            res.render("doc", {page: {title: "API"},
                                               html: html});
                        }
                    }
                );
            });
        }

        DatabankObject.bank = db;

        URLMaker.hostname = hostname;
        URLMaker.port = (config.urlPort) ? config.urlPort : port;
        URLMaker.path = config.urlPath;

        Distributor.log = log.child({component: "distributor"});

        Distributor.plugins = _.filter(plugins, function(plugin) {
            return _.isFunction(plugin.distributeActivity);
        });

        if (_(config).has('serverUser')) {
            app.on('listening', function() {
                process.setuid(config.serverUser);
            });
        }

        if (config.sockjs) {
            pumpsocket.connect(app, log);
        }

        if (config.firehose) {
            log.info({firehose: config.firehose}, "Setting up firehose");
            Firehose.setup(config.firehose, log);
        }

        if (config.spamhost) {
            if (!config.spamclientid ||
                !config.spamclientsecret) {
                throw new Error("Need client ID and secret for spam host");
            }
            log.info({spamhost: config.spamhost}, "Configuring spam host");
            ActivitySpam.init({
                host: config.spamhost,
                clientID: config.spamclientid,
                clientSecret: config.spamclientsecret,
                logger: log
            });
        }

        dialbackClient = new DialbackClient({
            hostname: hostname,
            bank: db,
            app: app,
            url: "/api/dialback"
        });

        Credentials.dialbackClient = dialbackClient;

        // Each worker takes a turn cleaning up, so *this* worker does
        // its cleanup once every config.workers cleanup periods

        var workers = config.workers || 1;
        var cleanupTime = 1200 * workers * 1000;

        // We set a timer so we start with an offset, instead of having
        // all workers start at almost the same time

        setTimeout(function() {
            log.info("Cleaning up old OAuth nonces");
            Nonce.cleanup();
            setInterval(function() {
                log.info("Cleaning up old OAuth nonces");
                Nonce.cleanup();
            }, cleanupTime);
        }, Math.floor(Math.random() * cleanupTime));

        app.run = function(callback) {
            var self = this,
                removeListeners = function() {
                    self.removeListener("listening", listenSuccessHandler);
                    self.removeListener("err", listenErrorHandler);
                },
                listenErrorHandler = function(err) {
                    removeListeners();
                    log.error(err);
                    callback(err);
                },
                listenSuccessHandler = function() {
                    var removeBounceListeners = function() {
                        bounce.removeListener("listening", bounceSuccess);
                        bounce.removeListener("err", bounceError);
                    },
                        bounceError = function(err) {
                            removeBounceListeners();
                            log.error(err);
                            callback(err);
                        },
                        bounceSuccess = function() {
                            log.info("Finished setting up bounce server.");
                            removeBounceListeners();
                            callback(null);
                        };

                    log.info("Finished setting up main server.");

                    removeListeners();
                    if (useBounce) {
                        bounce.on("error", bounceError);
                        bounce.on("listening", bounceSuccess);
                        bounce.listen(80, address);
                    } else {
                        callback(null);
                    }
                };
            this.on("error", listenErrorHandler);
            this.on("listening", listenSuccessHandler);
            log.info("Listening on "+port+" for host " + address);
            this.listen(port, address);
        };

        // So they can add their own routes or other stuff to the app

        _.each(plugins, function(plugin, name) {
            if (_.isFunction(plugin.initializeApp)) {
                log.info({plugin: name}, "Initializing app.");
                plugin.initializeApp(app);
            }
        });

        callback(null, app);
    });
};
Ejemplo n.º 25
0
 * tst.kill.js: tests case where the worker child process dies unexpectedly
 */

var mod_assert = require('assert');
var mod_bunyan = require('bunyan');
var mod_path = require('path');
var mod_spawnasync = require('../lib/spawn-async.js');

var log, worker, npending;

log = new mod_bunyan({
    'name': mod_path.basename(process.argv[1]),
    'level': process.env['LOG_LEVEL'] || 'debug'
});

log.info('starting test');
worker = mod_spawnasync.createWorker({ 'log': log });

worker.aspawn(['sleep', '10'], function (err) {
	mod_assert.ok(err);
	mod_assert.equal(err.message, 'worker process exited unexpectedly');

	worker.aspawn([ 'echo', 'hello' ], function (err2, stdout, stderr) {
		mod_assert.ok(!err2);
		mod_assert.equal(stdout, 'hello\n');

		/* Try the same thing across a "destroy". */
		worker.aspawn([ 'sleep', '10' ], function (err3) {
			mod_assert.ok(err3);
			mod_assert.equal(err3.message,
			    'worker process was destroyed');
Ejemplo n.º 26
0
'use strict';
var http = require('http');
var Logger = require('bunyan');

var log = new Logger({
    name: 'test-server',
    level: 'debug'
});

var server = http.createServer(function (request, response) {
    var data = '';

    log.info({ url: request.url }, 'Incoming Request');

    request.on('data', function (chunk) {
        data += chunk;
    });

    response.writeHead(501, { 'Content-Type': 'application/json' });
    response.end(JSON.stringify({ message: 'not implemented' }));
});

var port = 3000;
server.listen(port);
log.info({
    port: port
}, 'listening');

Ejemplo n.º 27
0
                        defaults);
} else {
    config = defaults;
}

if (config.logfile) {
    logParams.streams = [{path: config.logfile}];
} else if (config.nologger) {
    logParams.streams = [{path: "/dev/null"}];
} else {
    logParams.streams = [{stream: process.stderr}];
}

log = new Logger(logParams);

log.info("Initializing ragtag.io");

if (!config.params) {
    if (config.driver == "disk") {
        config.params = {dir: "/var/lib/ragtag-io/"};
    } else {
        config.params = {};
    }
}

// Define the database schema

if (!config.params.schema) {
    config.params.schema = {};
}
Ejemplo n.º 28
0
replContext.once('init', function(self) {
  log.info('ldap replication successfully initiated');
});
Ejemplo n.º 29
0
    function(callback) {

        var app,
            bounce,
            client,
            requestLogger = function(log) {
                return function(req, res, next) {
                    var weblog = log.child({"req_id": uuid.v4(), component: "web"});
                    var end = res.end;
                    req.log = weblog;
                    res.end = function(chunk, encoding) {
                        var rec;
                        res.end = end;
                        res.end(chunk, encoding);
                        rec = {req: req, res: res};
                        weblog.info(rec);
                    };
                    next();
                };
            };

        if (_.has(config, "key")) {

            log.info("Using SSL");

            app = express.createServer({key: fs.readFileSync(config.key),
                                        cert: fs.readFileSync(config.cert)});
            bounce = express.createServer(function(req, res, next) {
                var host = req.header('Host');
                res.redirect('https://'+host+req.url, 301);
            });

        } else {

            log.info("Not using SSL");

            app = express.createServer();
        }

        // Configuration

        var dbstore = new DatabankStore(db, log, 60000);

        log.info("Configuring app");

        app.configure(function(){
            app.set('views', __dirname + '/views');
            app.set('view engine', 'utml');
            app.use(requestLogger(log));
            app.use(express.bodyParser());
            app.use(express.cookieParser());
            app.use(express.methodOverride());
            app.use(express.session({secret: (_(config).has('sessionSecret')) ? config.sessionSecret : "insecure",
                                     store: dbstore}));
            app.use(app.router);
            app.use(express.static(__dirname + '/public'));
        });

        app.configure('development', function(){
            app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
        });

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

        // Auth middleware

        var userAuth = function(req, res, next) {

            req.user = null;
            res.local("user", null);

            if (!req.session.userID) {
                next();
            } else {
                User.get(req.session.userID, function(err, user) {
                    if (err) {
                        next(err);
                    } else {
                        req.user = user;
                        res.local("user", user);
                        next();
                    }
                });
            }
        };

        var userOptional = function(req, res, next) {
            next();
        };

        var userRequired = function(req, res, next) {
            if (!req.user) {
                next(new Error("User is required"));
            } else {
                next();
            }
        };

        var noUser = function(req, res, next) {
            if (req.user) {
                next(new Error("Already logged in"));
            } else {
                next();
            }
        };

        var userIsUser = function(req, res, next) {
            if (req.params.webfinger && req.user.id == req.params.webfinger) {
                next();
            } else {
                next(new Error("Must be the same user"));
            }
        };

        // Routes

        log.info("Initializing routes");

        app.get('/', userAuth, userOptional, routes.index);
        app.get('/tag/:tag', userAuth, userOptional, routes.tag);
        app.get('/login', userAuth, noUser, routes.login);
        app.post('/login', userAuth, noUser, routes.handleLogin);
        app.post('/logout', userAuth, userRequired, routes.handleLogout);
        app.get('/about', userAuth, userOptional, routes.about);
        app.get('/authorized/:hostname', routes.authorized);
        app.get('/.well-known/host-meta.json', routes.hostmeta);
        app.post('/callback', pushroutes.subCallback);

        // Create a dialback client

        log.info("Initializing dialback client");

        client = new DialbackClient({
            hostname: config.hostname,
            app: app,
            bank: db,
            userAgent: "RagtagIO/0.1.0"
        });

        // Configure this global object

        Host.dialbackClient = client;

        // Configure the service object

        log.info({name: config.name, 
                  description: config.description, 
                  hostname: config.hostname},
                 "Initializing RagtagIO object");

        RagtagIO.name        = config.name;
        RagtagIO.description = config.description;
        RagtagIO.hostname    = config.hostname;

        RagtagIO.protocol = (config.key) ? "https" : "http";

        // Let Web stuff get to config

        app.config = config;

        // For handling errors

        app.log = function(obj) {
            if (obj instanceof Error) {
                log.error(obj);
            } else {
                log.info(obj);
            }
        };

        // Start the app

        log.info({port: config.port, address: config.address}, "Starting app listener");

        app.listen(config.port, config.address, callback);

        // Start the bouncer

        if (bounce) {
            log.info({port: 80, address: config.address}, "Starting bounce listener");
            bounce.listen(80, config.address);
        }

    }], function(err) {
Ejemplo n.º 30
0
server.listen(9080, function() {
        log.info('listening: %s', server.url);
});