/**********************************************
***                                         ***
***     packages and global variables       ***
***                                         ***
**********************************************/

// packages needed
var ws = require("nodejs-websocket");
var Q = require('q');
var restify = require("restify");
var request = require('request'); 

// the app server, setup to accept both query and post parameters
var vrexProxy = restify.createServer();
vrexProxy.use(restify.queryParser());
vrexProxy.use(restify.bodyParser());
// cross domain permissions
/* var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Accept, Origin, Referer, User-Agent, Content-Type, Authorization');
 
  // intercept OPTIONS method
  if (req.method === 'OPTIONS') {
    res.send(200);
  }
  else {
    next();
  }
};
vrexProxy.use(allowCrossDomain); */
Exemple #2
0
SessionServer.prototype.startup = function () {

  var self = this;


  this.server.use(restify.queryParser());
  this.server.use(restify.bodyParser());
  this.server.use(restify.CORS( {origins: ['*:*']}));
  this.server.use(restify.fullResponse());
  this.server.use(restify.jsonp());

  function unknownMethodHandler(req, res) {
      if (req.method.toUpperCase() === 'OPTIONS') {
          console.log('Received an options method request from: ' + req.headers.origin);
          var allowHeaders = ['Accept', 'Accept-Version', 'Content-Type', 'Api-Version', 'Origin', 'X-Requested-With', 'Authorization'];

          if (res.methods.indexOf('OPTIONS') === -1) {
              res.methods.push('OPTIONS');
          }

          res.header('Access-Control-Allow-Credentials', false);
          res.header('Access-Control-Expose-Headers', true);
          res.header('Access-Control-Allow-Headers', allowHeaders.join(', '));
          res.header('Access-Control-Allow-Methods', res.methods.join(', '));
          res.header('Access-Control-Allow-Origin', req.headers.origin);
          res.header('Access-Control-Max-Age', 1209600);

          return res.send(204);
      }
      else {
          return res.send(new restify.MethodNotAllowedError());
      }
  }
  this.server.on('MethodNotAllowed', unknownMethodHandler);

  this.server.on('XPUSH-send', function (params){
    self.send(params);
  });

  this.server.get('/node/:app/:channel', function (req, res, next) {

    self.getChannelServer(req.params.app, req.params.channel, function(serverInfo){

      var _seq = shortId.generate();

      res.send({
        status: 'ok',
        result: {
          seq:  _seq,
          channel: req.params.channel,
          server: serverInfo
        }
      });

      next();
    });

  });

  this.server.post('/auth', function (req, res, next) {

    var err = serverUtils.validEmptyParams(req, ['app', 'userId', 'password', 'deviceId']);
    if(err){
      res.send({status: 'error', message: err});
      return;
    }

    mongoPersister.retrieveUser(
      req.params.app,
      req.params.userId,
      req.params.deviceId,
      function (err, user) {

      if(err) {
        next(err);
        return;
      }

      if(!user) {
				res.send({status: 'error', message: 'User is not existed.'});
        return;
      }

      var _pw = serverUtils.encrypto(req.params.password);

      if(user.password == _pw){
        mongoPersister.updateUserToken(
          user.app,
          user.userId,
          user.deviceId,
          serverUtils.randomString(10),
          function (err, token) {

          if(err){
            res.send({status: 'error', message: err});
            return;
          }

          var serverNode = self.nodeManager.getServerNode(req.params.app + req.params.userId);
          var _url 	 = serverUtils.setHttpProtocal(serverNode.url);

          res.send({
            status: 'ok',
            result: {
              'token': token,
              'server': serverNode.name,
              'serverUrl': _url}
          });

          // TODO
          // store userId and token to check this token when connection of session socket.

        });

      }else{

        res.send({status: 'error', message: 'Password is not corrected'});
      }
    });

  });

  if(!this.conf.type || this.conf.type != 'PROXY'){

    require('../routes/routes')(self.conf, this.server, this.nodeManager);
  }

  this.server.listen(this.conf.port, function () {

    self.isStarted = true;

    for(var key in self.methods.GETS){
      self.server.get(key, self.methods.GETS[key]);
    }

    for(var key in self.methods.POSTS){
      self.server.post(key, self.methods.POSTS[key]);
    }

    for(var key in self.methods.staticFiles){
      console.log('HTTP static directory : ', self.methods.staticFiles[key].directory);
      self.server.get(key, restify.serveStatic(self.methods.staticFiles[key]));
    }


    self.emit('connected', /*self.server.url // http://0.0.0.0:8000 */
      self.conf.host, self.conf.port);

  });

  this.server._fireEvent = function (eventName, datas) {
    var _r = self.emit(eventName, datas);
    return _r;
  };

};
Exemple #3
0
/**
 * @overview instantiates web server for service
 */

/* jshint -W097 */
"use strict";

var restify = require('restify'),
    request = require('request'),
    cloud = require('./cloud.js'),
    server = restify.createServer();

server.use(restify.bodyParser({ mapParams: false }));

server.post('/update', cloud.processTrackerAlert);

server.listen(8888, function() {
    console.log('%s listening at %s', server.name, server.url);
});


// A 'cronjob' to run the notify task. Yeah,
// it leaks memory.


var minutes = 1, interval = minutes * 1000 * 60;

setInterval(cloud.notifyNearbyUsers, interval/4);
// refresh vehicles everyday
setInterval(cloud.refreshRecoveredVehicles, interval);
Exemple #4
0
var Restify = require('restify');
var Util = require('util');

var server = Restify.createServer();
server.use(Restify.bodyParser()); //Parse body content of message sent to the server


//setup cors
Restify.CORS.ALLOW_HEADERS.push('accept');
Restify.CORS.ALLOW_HEADERS.push('sid');
Restify.CORS.ALLOW_HEADERS.push('lang');
Restify.CORS.ALLOW_HEADERS.push('origin');
Restify.CORS.ALLOW_HEADERS.push('withcredentials');
Restify.CORS.ALLOW_HEADERS.push('x-requested-with');
server.use(Restify.CORS());

module.exports = server;
module.exports = function (app, sessionKey) {

   longjohn.async_trace_limit = 5;  // defaults to 10
   longjohn.empty_frame = 'ASYNC CALLBACK';

   app.use(restify.acceptParser(app.acceptable));
   app.use(restify.authorizationParser());
   app.use(restify.dateParser());
   app.use(restify.queryParser());
   app.use(restify.jsonp());
   app.use(restify.gzipResponse());
   app.use(restify.bodyParser());

   var os = require('os');
   console.log(os.platform() + ", " + os.release());
   // having issues on WIndows with nodegyp and toobusy, Windows SDK solution works on some platforms
   // https://github.com/TooTallNate/node-gyp/#installation
   if (os.platform().indexOf('win') < 0) {
     console.log("Loading toobusy");
     // send a 503 if the server is too busy
     var toobusy = require('toobusy')
     app.use(function(req, res, next) {
      if (toobusy()) {
        res.send(503, "I'm busy right now, sorry.");
      } else {
        next();
      }
     });
   }

   app.use(clientSessions({
     cookieName: 'session'    // defaults to session_state
     , secret: sessionKey
     , duration: config.session_timeout // in ms
     // refresh every access through the api
     , path: '/api'
     , httpOnly: true // defaults to true
     , secure: false   // defaults to false
     , cookie: {
         maxAge: config.session_timeout
         , ephemeral: config.ephemeral_cookie
     }
   }));

   // client-sessions documentation is "correct", but the devs added a work around to the cookie expiry problem
   app.use(function(req, res, next) {
     if (req.session) {
       req.session.setDuration(config.session_timeout);
     }
     next();
   });


    app.use(restify.throttle({
      burst: 100,
      rate: 50,
      ip: true,
      overrides: {
        '192.168.1.1': {
           rate: 0,        // unlimited
           burst: 0
         }
      }
    }));
   app.use(restify.conditionalRequest());
};
Exemple #6
0
var restify = require('restify');
var unknownMethodHandler = require('../utls.js').unknownMethodHandler;
var hasPermission = require('../auth.js').hasPermission;
var config = require('../config.json');
var plugins = require("../services/plugins.js").plugins;
var saveconfig = require('../utls.js').saveconfig;
var servers = require('../services/index.js').servers;
var initServer = require('../services/index.js').initServer;
var restserver = restify.createServer();
var path = require('path');
var async = require('async');
var mime = require('mime');
var request = require('request');
var log = require('../log.js');

restserver.use(restify.bodyParser());
restserver.use(restify.authorizationParser());
restserver.use(restify.queryParser());
restserver.on('MethodNotAllowed', unknownMethodHandler);

restserver.use(
	function crossOrigin(req,res,next){
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	return next();
	}
);

function restauth(req, service, permission){
	if (!('X-Access-Token' in req.headers) && 'x-access-token' in req.headers){
		req.headers['X-Access-Token'] = req.headers['x-access-token']
Exemple #7
0
var API = module.exports = function (opts) {
    if (typeof (opts) !== 'object') {
        throw new TypeError('opts (Object) required');
    }

    if (typeof (opts.backend) !== 'object') {
        throw new TypeError('opts.backend (Object) required');
    }

    if (typeof (opts.api) !== 'object') {
        throw new TypeError('opts.api (Object) required');
    }

    var log;

    if (opts.log) {
        log = opts.log({
            component: 'workflow-api'
        });
    } else {
        if (!opts.logger) {
            opts.logger = {};
        }

        opts.logger.name = 'workflow-api';
        opts.logger.serializers = restify.bunyan.serializers;

        opts.logger.streams = opts.logger.streams || [ {
            level: 'info',
            stream: process.stdout
        }];

        log = opts.api.Logger = new Logger(opts.logger);
    }

    opts.api.name = opts.api.name || 'WorkflowAPI';
    opts.api.acceptable = ['application/json'];

    if (!opts.api.port && !opts.api.path) {
        opts.api.path = '/tmp/' + uuid();
    }

    opts.api.log = log;
    var server = restify.createServer(opts.api);
    var Backend = require(opts.backend.module);
    opts.backend.opts.log = log;
    var backend = Backend(opts.backend.opts);
    var factory = Factory(backend);

    // Define path and versioned routes:
    var WORKFLOWS_PATH = '/workflows';
    var WORKFLOW_PATH = WORKFLOWS_PATH + '/:uuid';
    var WORKFLOWS_ROUTE = {
        path: WORKFLOWS_PATH,
        version: '0.1.0'
    };
    var WORKFLOW_ROUTE = {
        path: WORKFLOW_PATH,
        version: '0.1.0'
    };

    var JOBS_PATH = '/jobs';
    var JOB_PATH = JOBS_PATH + '/:uuid';
    var JOBS_ROUTE = {
        path: JOBS_PATH,
        version: '0.1.0'
    };
    var SNAP_PATH = '/snapshot';
    var SNAP_ROUTE = {
        path: SNAP_PATH,
        version: '0.1.0'
    };
    var JOB_ROUTE = {
        path: JOB_PATH,
        version: '0.1.0'
    };
    var JOB_INFO_PATH = JOB_PATH + '/info';
    var JOB_INFO_ROUTE = {
        path: JOB_INFO_PATH,
        version: '0.1.0'
    };
    var JOB_CANCEL_PATH = JOB_PATH + '/cancel';
    var JOB_CANCEL_ROUTE = {
        path: JOB_CANCEL_PATH,
        version: '0.1.0'
    };
    var JOB_RESUME_PATH = JOB_PATH + '/resume';
    var JOB_RESUME_ROUTE = {
        path: JOB_RESUME_PATH,
        version: '0.1.0'
    };

    var PING_PATH = '/ping';
    var PING_ROUTE = {
        path: PING_PATH,
        version: '0.1.0'
    };

    server.use(restify.requestLogger());
    server.use(restify.acceptParser(server.acceptable));
    server.use(restify.dateParser());
    server.use(restify.queryParser());
    server.use(restify.bodyParser({
        overrideParams: true,
        mapParams: true
    }));
    server.use(restify.fullResponse());

    server.acceptable.unshift('application/json');

    // Return Service Unavailable if backend is not connected
    server.use(function ensureBackendConnected(req, res, next) {
        if (typeof (backend.connected) !== 'undefined' &&
            backend.connected === false) {
            return next(new restify.ServiceUnavailableError(
                'Backend not connected'));
        }

        return next();
    });

    // Write useful x-* headers
    server.use(function (req, res, next) {
        res.on('header', function onHeader() {
            var now = Date.now();
            res.header('x-request-id', req.getId());
            var t = now - req.time();
            res.header('x-response-time', t);
            res.header('x-server-name', os.hostname());
        });
        next();
    });

    // Audit all requests, don't log response bodies for GETs
    server.on('after', function (req, res, route, err) {
        var method = req.method;
        var path = req.path();
        if (method === 'GET' || method === 'HEAD') {
            if (path === '/ping') {
                return;
            }
        }
        // Successful GET res bodies are uninteresting and big.
        var body = !(method === 'GET' &&
            Math.floor(res.statusCode / 100) === 2);

        restify.auditLogger({
            log: req.log.child({ route: route }, true),
            body: body
        })(req, res, route, err);
    });

    // Define handlers:
    function listWorkflows(req, res, next) {
        backend.getWorkflows(req.params, function (err, workflows) {
            if (err) {
                return next(new restify.InternalError(err));
            }
            res.send(200, workflows);
            return next();
        });
    }

    function postWorkflow(req, res, next) {
        var workflow = {};
        var wf_members = ['name', 'uuid', 'timeout', 'chain', 'onerror',
                          'max_attempts', 'initial_delay', 'max_delay',
                          'oncancel'];
        var error;
        var meta = {};

        if (typeof (opts.api.wf_extra_params) !== 'undefined') {
            wf_members = wf_members.concat(opts.api.wf_extra_params);
        }

        // Up to the user if want to identify the workflow
        // with self.cooked uuid:
        wf_members.forEach(function (p) {
            if (req.params[p]) {
                workflow[p] = req.params[p];
            }
        });

        if (workflow.chain) {
            workflow.chain.forEach(function (task, i, arr) {
                if (!task.body) {
                    error = new restify.ConflictError('Task body is required');
                }
                task.body = vm.runInNewContext('(' + task.body + ')', {});
                if (task.fallback) {
                    task.fallback =
                        vm.runInNewContext('(' + task.fallback + ')', {});
                }
                workflow.chain[i] = task;
            });
        }

        if (workflow.onerror) {
            workflow.onerror.forEach(function (task, i, arr) {
                if (!task.body) {
                    error = new restify.ConflictError('Task body is required');
                }
                task.body = vm.runInNewContext('(' + task.body + ')', {});
                if (task.fallback) {
                    task.fallback =
                        vm.runInNewContext('(' + task.fallback + ')', {});
                }
                workflow.onerror[i] = task;
            });
        }

        if (workflow.oncancel) {
            workflow.oncancel.forEach(function (task, i, arr) {
                if (!task.body) {
                    error = new restify.ConflictError('Task body is required');
                }
                task.body = vm.runInNewContext('(' + task.body + ')', {});
                if (task.fallback) {
                    task.fallback =
                        vm.runInNewContext('(' + task.fallback + ')', {});
                }
                workflow.oncancel[i] = task;
            });
        }

        if (error) {
            return next(error);
        }

        if (req.headers['request-id']) {
            meta.req_id = req.headers['request-id'];
        }

        return factory.workflow(workflow, meta, function (err, result) {
            if (err) {
                return next(err.toRestError);
            }
            res.header('Location', req.path() + '/' + result.uuid);
            // If Request-Id hasn't been set, we'll set it to workflow UUID:
            if (!req.headers['request-id']) {
                res.header('request-id',  result.uuid);
            }

            res.send(201, result);
            return next();
        });
    }

    function getWorkflow(req, res, next) {
        // If Request-Id hasn't been set, we'll set it to workflow UUID:
        if (!req.headers['request-id']) {
            res.header('request-id',  req.params.uuid);
        }

        var meta = {
            req_id: req.id
        };

        backend.getWorkflow(req.params.uuid, meta, function (err, workflow) {
            if (err) {
                return next(err.toRestError);
            } else {
                res.send(200, workflow);
                return next();
            }
        });
    }

    function updateWorkflow(req, res, next) {
        var error, meta = {};
        // If Request-Id hasn't been set, we'll set it to workflow UUID:
        if (!req.headers['request-id']) {
            res.header('request-id',  req.params.uuid);
        }

        meta.req_id = req.id;

        if (req.params.chain) {
            req.params.chain.forEach(function (task) {
                if (!task.body) {
                    error = new restify.ConflictError('Task body is required');
                }
            });
        }

        if (req.params.onerror) {
            req.params.onerror.forEach(function (task) {
                if (!task.body) {
                    error = new restify.ConflictError('Task body is required');
                }
            });
        }

        if (req.params.oncancel) {
            req.params.oncancel.forEach(function (task) {
                if (!task.body) {
                    error = new restify.ConflictError('Task body is required');
                }
            });
        }

        if (error) {
            return next(error);
        }

        return backend.updateWorkflow(req.params, meta,
            function (err, workflow) {
                if (err) {
                    return next(err.toRestError);
                }
                res.send(200, workflow);
                return next();
            });
    }

    function deleteWorkflow(req, res, next) {
        // If Request-Id hasn't been set, we'll set it to workflow UUID:
        if (!req.headers['request-id']) {
            res.header('request-id',  req.params.uuid);
        }

        var meta = {
            req_id: req.id
        };

        backend.getWorkflow(req.params.uuid, function (err, workflow) {
            if (err) {
                return next(err.toRestError);
            } else {
                return backend.deleteWorkflow(workflow, meta,
                  function (err, deleted) {
                    if (err) {
                        return next(new restify.InternalError(err));
                    }

                    if (deleted) {
                        res.send(204);
                        return next();
                    } else {
                        return next(new restify.InternalError(
                            'Cannot delete the workflow'));
                    }
                });
            }
        });
    }

    function listJobs(req, res, next) {
        var exec_values =
          ['queued', 'failed', 'succeeded', 'running', 'canceled'],
            cb = function (err, jobs, count) {
                if (err) {
                    return next(new restify.InternalError(err));
                }
                if (count) {
                    res.header('x-count', count);
                }
                res.send(200, jobs);
                return next();
            };

        if (req.params.execution) {
            if (exec_values.indexOf(req.params.execution) === -1) {
                return next(new restify.ConflictError(
                  'Execution must be one of queued, failed, ' +
                  'succeeded, canceled or running'));
            }
        }

        if (req.params.offset) {
            req.params.offset = Number(req.params.offset);
        }

        if (req.params.limit) {
            req.params.limit = Number(req.params.limit);
        }

        return backend.getJobs(req.params, cb);
    }


    function snapshot(req, res, next) {
        return backend.getJobs(function (err, jobs, count) {
            if (err) {
                return next(new restify.InternalError(err));
            }
            return backend.getRunners(function (err2, runners) {
                if (err2) {
                    return next(new restify.InternalError(err2));
                }
                return backend.getJobs({
                    execution: 'running'
                }, function (err3, running, running_count) {
                    if (err3) {
                        return next(new restify.InternalError(err3));
                    }
                    return backend.getJobs({
                        execution: 'queued'
                    }, function (err4, queued, queued_count) {
                        if (err4) {
                            return next(new restify.InternalError(err4));
                        }

                        res.header('x-count', count);

                        res.send(200, {
                            service: {
                                name: 'workflow',
                                component: 'jobs',
                                ident: req.headers.host,
                                pid: process.pid
                            },
                            stats: {
                                uptime: process.uptime(),
                                memory: process.memoryUsage(),
                                total_jobs: count,
                                running_jobs: running_count,
                                queued_jobs: queued_count
                            },
                            types: [ 'jobs',
                                'runners',
                                'running_jobs',
                                'queued_jobs'],
                            jobs: jobs,
                            running_jobs: running,
                            queued_jobs: queued,
                            runners: runners
                        });
                        return next();
                    });
                });
            });
        });
    }

    function postJob(req, res, next) {
        var job = {
            params: {}
        };
        var meta = {};
        var members = ['exec_after', 'workflow', 'target', 'num_attempts',
                        'uuid', 'locks'];

        var job_members = [];
        if (typeof (opts.api.job_extra_params) !== 'undefined') {
            job_members = opts.api.job_extra_params;
        }

        Object.keys(req.params).forEach(function (p) {
            if (members.indexOf(p) !== -1) {
                job[p] = req.params[p];
            } else if (job_members.indexOf(p) !== -1) {
                job[p] = req.params[p];
                // We are adding them here too due to back-compat reasons:
                job.params[p] = req.params[p];
            } else {
                job.params[p] = req.params[p];
            }
        });

        if (req.headers['request-id']) {
            meta.req_id = req.headers['request-id'];
        }

        factory.job(job, meta, function (err, result) {
            if (err) {
                if (typeof (err) === 'string') {
                    return next(new restify.ConflictError(err));
                } else {
                    return next(err.toRestError);
                }
            }
            // If Request-Id hasn't been set, we'll set it to job UUID:
            if (!req.headers['request-id']) {
                res.header('request-id',  result.uuid);
            }
            res.header('Location', req.path() + '/' + result.uuid);
            res.status(201);
            res.send(result);
            return next();
        });
    }

    function getJob(req, res, next) {
        // If Request-Id hasn't been set, we'll set it to job UUID:
        if (!req.headers['request-id']) {
            res.header('request-id',  req.params.uuid);
        }
        var meta = {
            req_id: req.id
        };

        backend.getJob(req.params.uuid, meta, function (err, job) {
            if (err) {
                return next(err.toRestError);
            } else {
                res.send(200, job);
                return next();
            }
        });
    }

    function getInfo(req, res, next) {
        // If Request-Id hasn't been set, we'll set it to job UUID:
        if (!req.headers['request-id']) {
            res.header('request-id',  req.params.uuid);
        }

        var meta = {
            req_id: req.id
        };

        backend.getInfo(req.params.uuid, meta, function (err, info) {
            if (err) {
                return next(err.toRestError);
            } else {
                res.send(200, info);
                return next();
            }
        });
    }

    function postInfo(req, res, next) {
        var info = {}, meta = {};
        Object.keys(req.params).forEach(function (p) {
            if (p !== 'uuid') {
                info[p] = req.params[p];
            }
        });
        // If Request-Id hasn't been set, we'll set it to job UUID:
        if (!req.headers['request-id']) {
            res.header('request-id',  req.params.uuid);
        }

        meta.req_id = req.id;

        backend.addInfo(req.params.uuid, info, meta, function (err) {
            if (err) {
                return next(err.toRestError);
            } else {
                res.send(200);
                return next();
            }
        });
    }

    function cancelJob(req, res, next) {
        var meta = {};
        backend.getJob(req.params.uuid, function (err, job) {
            if (err) {
                return next(err.toRestError);
            } else if (job.execution === 'succeeded' ||
                            job.execution === 'failed') {
                return next(new restify.ConflictError(
                  'Finished jobs cannot be canceled'));
            } else {
                // If Request-Id hasn't been set, we'll set it to job UUID:
                if (!req.headers['request-id']) {
                    res.header('request-id',  req.params.uuid);
                }
                meta.req_id = req.id;

                return backend.updateJobProperty(
                  job.uuid,
                  'execution',
                  'canceled',
                  meta,
                  function (err) {
                    if (err) {
                        return next(new restify.InternalError(err));
                    }
                    job.execution = 'canceled';
                    log.info('Job %s canceled', req.params.uuid);
                    res.send(200, job);
                    return next();
                  });
            }
        });
    }

    // Accepts 'error' and 'result' params. When nothing is given, assumes
    // result is 'OK' and moves forward. When error is given, it means the
    // remote process failed, and the job will be finished with 'failed'
    // execution. Otherwise, chain_results for the task which put the job to
    // wait will be updated with the given result, and the job will be resumed
    // (re-queued, so it gets picked by the runner when there are free slots).
    function resumeJob(req, res, next) {
        var meta = {};
        backend.getJob(req.params.uuid, function (err, job) {
            if (err) {
                return next(err.toRestError);
            } else if (job.execution !== 'waiting') {
                return next(new restify.ConflictError(
                  'Only waiting jobs can be resumed'));
            } else {
                // If Request-Id hasn't been set, we'll set it to job UUID:
                if (!req.headers['request-id']) {
                    res.header('request-id',  req.params.uuid);
                }
                meta.req_id = req.id;

                job.execution = (req.params.error) ? 'failed' : 'queued';
                var r = job.chain_results[job.chain_results.length - 1];
                r.result = (req.params.result) ? req.params.result :
                    ((req.params.error) ? '' : 'External task: OK');
                r.error = (req.params.error) ? req.params.error: '';
                r.finished_at = new Date().toISOString();
                job.chain_results[job.chain_results.length - 1] = r;

                return backend.updateJob(job, meta, function (err, theJob) {
                    if (err) {
                        return next(new restify.InternalError(err));
                    }
                    log.info('Job %s resumed', req.params.uuid);
                    res.send(200, theJob);
                    return next();
                });
            }
        });
    }
    // --- Routes
    // Workflows:
    server.get(WORKFLOWS_ROUTE, listWorkflows);
    server.head(WORKFLOWS_ROUTE, listWorkflows);
    server.post(WORKFLOWS_ROUTE, postWorkflow);
    // Workflow:
    server.get(WORKFLOW_ROUTE, getWorkflow);
    server.head(WORKFLOW_ROUTE, getWorkflow);
    server.put(WORKFLOW_ROUTE, updateWorkflow);
    server.del(WORKFLOW_ROUTE, deleteWorkflow);
    // Jobs:
    server.get(JOBS_ROUTE, listJobs);
    server.head(JOBS_ROUTE, listJobs);
    server.get(SNAP_ROUTE, snapshot);
    server.head(SNAP_ROUTE, snapshot);
    server.post(JOBS_ROUTE, postJob);
    // Job:
    server.get(JOB_ROUTE, getJob);
    server.head(JOB_ROUTE, getJob);
    // Cancel job:
    server.post(JOB_CANCEL_ROUTE, cancelJob);
    // Resume job:
    server.post(JOB_RESUME_ROUTE, resumeJob);
    // Job status info:
    server.get(JOB_INFO_ROUTE, getInfo);
    server.head(JOB_INFO_ROUTE, getInfo);
    server.post(JOB_INFO_ROUTE, postInfo);
    // Ping:
    server.get(PING_ROUTE, function (req, res, next) {
        var data = {
            pid: process.pid
        };

        if (typeof (backend.ping) === 'function') {
            return backend.ping(function (err) {
                if (err) {
                    data.backend = 'down';
                    data.backend_error = err.message;

                    res.send(data);
                    return next();

                } else {
                    data.backend = 'up';
                    res.send(data);
                    return next();
                }
            });
        } else {
            data.backend = 'unknown';
            res.send(data);
            return next();
        }
    });

    return {
        init: function init(onInit, onError) {
            var port_or_path = (!opts.api.port) ?
                               opts.api.path :
                               opts.api.port;
            backend.on('error', function (err) {
                return onError(err);
            });

            backend.init(function () {
                log.info('API backend initialized');
            });

            return server.listen(port_or_path, function () {
                log.info('%s listening at %s', server.name, server.url);
                return onInit();
            });

        },
        // These are properties, maybe it's a good idea to define getters:
        server: server,
        backend: backend,
        log: log
    };
};
Exemple #8
0
        'application/json': function formatFoo(req, res, body) {
            if (body instanceof Error)
                return body.stack;
            if (Buffer.isBuffer(body))
                return body.toString('base64');
            return Util.inspect(body);
        }
    }
});
server.use(Restify.acceptParser(server.acceptable));
server.use(Restify.authorizationParser());
server.use(Restify.dateParser());
server.use(Restify.queryParser());
server.use(Restify.jsonp());
server.use(Restify.gzipResponse());
server.use(Restify.bodyParser());
server.use(Restify.throttle({
    burst: 100,
    rate: 50,
    ip: true,
    overrides: {
        '127.0.0.1': {
            rate: 0,        // unlimited
            burst: 0
        }
    }
}));
server.use(Restify.conditionalRequest());

Restify.CORS.ALLOW_HEADERS.push('accept');
Restify.CORS.ALLOW_HEADERS.push('sid');
  restify.acceptParser( server.acceptable ),
  restify.throttle( throttleOptions ),
  restify.dateParser(),
  restify.queryParser(),
  restify.fullResponse(),
];

if ( nconf.get('Security:UseAuth') ) {
  plugins.push( require( path.join(__dirname, 'plugins', 'customAuthorizationParser') )() );
}

if ( nconf.get('Security:UseACL') ) {
  plugins.push( require( path.join(__dirname, 'plugins', 'customACLPlugin') )() );
}

plugins.push( restify.bodyParser() );
plugins.push( restify.gzipResponse() );

server.use( plugins );

/**
 * CORS
 */

var corsOptions = {
  origins: nconf.get('CORS:Origins'),
  credentials: nconf.get('CORS:Credentials'),
  headers: nconf.get('CORS:Headers'),
};

server.pre( restify.CORS(corsOptions) );
Exemple #10
0
function createServer(options) {
    var server = restify.createServer({
        name: 'sapi/' + serverVersion(),
        handleUncaughtExceptions: false,
        log: options.log,
        version: ['1.0.0', '2.0.0']
    });

    server.pre(function setDefaultApiVersion(req, res, next) {
        /**
         * If the client does not set Accept-Version, then we default
         * the header to "~1".
         *
         * *Could* do:
         *    req.headers['accept-version'] = '~1'
         * but that lies in the audit log. Would like a
         * `req.setVersion()` in restify instead of hacking private
         * `req._version`.
         */
        if (req.headers['accept-version'] === undefined) {
            req._version = '~1';
        }

        next();
    });

    // Set stock Triton service headers.
    server.use(function stdTritonResHeaders(req, res, next) {
        res.on('header', function onHeader() {
            res.header('Server', server.name);
            res.header('x-request-id', req.getId());
            res.header('x-server-name', HOSTNAME);
        });

        next();
    });

    server.use(restify.queryParser({allowDots: false, plainObjects: false}));
    server.use(restify.bodyParser());
    server.use(restify.requestLogger());
    server.on('after', options.metricsManager.collectRestifyMetrics
        .bind(options.metricsManager));

    server.on('after', tritonAuditLogger.createAuditLogHandler({
        log: options.log,
        reqBody: {
            maxLen: 1024
        },
        resBody: {},
        routeOverrides: {
            // Make the frequent `GetConfig` calls visible via `bunyan -p`.
            'getconfigs': {
                logLevel: 'debug'
            }
        }
    }));

    endpoints.attachTo(server, options.model);

    return (server);
}
function startServer(serverPort, config, callback) {

  var mmApi = require('./lib/MediaManagerApiCore')(config, { singleton: false });

  var bunyan = require('bunyan');
  var logger = bunyan.createLogger({
    name: serverName,
    streams: [
      {
        level: "info",
        path: logDir + '/' + infoLogfile
      },
      {
        level: "error",
        path: logDir + '/' + errorLogfile
      }
    ]
  });

  server = restify.createServer({name: serverName,
    version: version});

  server.use(restify.bodyParser({ mapParams: false }));

//
//  MediaManagerApiRouter: Sets up routing to resources for the Media Manager API.
//
  var MediaManagerApiRouter = function () {

    //
    //  initialize: sets up all the routes. Invoked at the end of object construction.
    //
    this.initialize = function () {
      var that = this;
      console.log('MediaManagerApiRouter.initialize: initializing...');
      _.each(_.values(this.resources), function (resource) {

        //
        //  Collection routes:
        //

        //
        //  create route (POST resource.path)
        //
        var pat = resource.requestPath('create');
        console.log('MediaManagerApiRouter.initialize: create, request path to match - ' + pat);
        server.post(pat,
          function create(req, res, next) {
            logger.info({
              event: '__request__',
              req: req
            });
            var options = {
              onSuccess: that.genOnSuccess(resource, req, res),
              onError: that.genOnError(resource, req, res)
            };
            var parsedUrl = url.parse(req.url, true);
            if (_.has(parsedUrl, 'query')) {
              options['query'] = parsedUrl.query;
            }
            if (_.has(req, 'body') && req.body) {
              options.attr = req.body;
            }
            resource.doRequest('POST',
              options);
            return next();
          });


        //
        //  update route (PUT resource.path)
        //
        pat = resource.requestPath('update');
        console.log('MediaManagerApiRouter.initialize: update, request path to match - ' + pat);
        server.put(pat,
          function update(req, res, next) {
            logger.info({
              event: '__request__',
              req: req
            });
            var options = {
              id: req.params[0],
              req: req,
              onSuccess: that.genOnSuccess(resource, req, res),
              onError: that.genOnError(resource, req, res)
            };
            var parsedUrl = url.parse(req.url, true);
            if (_.has(parsedUrl, 'query')) {
              options['query'] = parsedUrl.query;
            }
            if (_.has(req, 'body') && req.body) {
              options.attr = req.body;
            }
            resource.doRequest('PUT',
              options);
            return next();
          });

        //
        //  index route (GET resource.path)
        //
        pat = resource.requestPath('index');
        console.log('MediaManagerApiRouter.initialize: index, request path to match - ' + pat);
        server.get(pat,
          function (req, res, next) {
            logger.info({
              event: '__request__',
              req: req});
            var options = {
              req: req,
              onSuccess: that.genOnSuccess(resource, req, res),
              onError: that.genOnError(resource, req, res)
            };
            var parsedUrl = url.parse(req.url, true);
            if (_.has(parsedUrl, 'query')) {
              options['query'] = parsedUrl.query;
            }
            resource.doRequest('GET',
              options);
            return next();
          });

        //
        //  Singular instance routes:
        //

        //
        //  read route (GET resource.path, where resource.path points to an instance)
        //
        pat = resource.requestPath('read');
        console.log('MediaManagerApiRouter.initialize: read, request path to match - ' + pat);
        server.get(pat,
          function (req, res, next) {
            logger.info({event: '__request__',
              id: req.params[0],
              req: req});
            resource.doRequest('GET',
              {id: req.params[0],
                onSuccess: that.genOnSuccess(resource, req, res),
                onError: that.genOnError(resource, req, res)});
            return next();
          });
        console.log('MediaManagerApiRouter.initialize: read defined!');

        //
        //  delete a single instance . route (DELETE resource.path)
        //
        pat = resource.requestPath('delete');
        console.log('MediaManagerApiRouter.initialize: delete, request path to match - ' + pat);
        server.del(pat,
          function (req, res, next) {
            logger.info({
              event: '__request__',
              req: req});
            var options = {
              id: req.params[0],
              req: req,
              onSuccess: that.genOnSuccess(resource, req, res),
              onError: that.genOnError(resource, req, res)
            };
            var parsedUrl = url.parse(req.url, true);
            if (_.has(parsedUrl, 'query')) {
              options['query'] = parsedUrl.query;
            }
            resource.doRequest('DELETE',
              options);
            return next();
          });

        //
        //  delete a collection. route (DELETE resource.path)
        //
        pat = resource.requestPath('collection');
        console.log('MediaManagerApiRouter.initialize: delete a collection, request path to match - ' + pat);
        server.del(pat,
          function (req, res, next) {
            logger.info({
              event: '__request__',
              req: req});
            var options = {
              req: req,
              onSuccess: that.genOnSuccess(resource, req, res),
              onError: that.genOnError(resource, req, res)
            };
            var parsedUrl = url.parse(req.url, true);
            if (_.has(parsedUrl, 'query')) {
              options['query'] = parsedUrl.query;
            }
            resource.doRequest('DELETE',
              options);
            return next();
          });
      });
    };

    console.log('MediaManagerApiRouter.constructor: Setting up resources, typeof(mmApi) === ' + typeof(mmApi) + ', mmApi attributes - ' + _.keys(mmApi));

    this.resources = {
      Images: new mmApi.Images('/images',
        {instName: 'image',
          pathPrefix: '/' + urlVersion}),
      Importers: new mmApi.Importers('/importers',
        {instName: 'importer',
          pathPrefix: '/' + urlVersion}),
      ImportersImages: new mmApi.ImportersImages(null,
        {pathPrefix: '/' + urlVersion,
          subResource: new mmApi.Importers(
            '/importers',
            {instName: 'importer',
              subResource: new mmApi.Images(
                '/images',
                {instName: 'image'})
            })
        }),
      StorageSynchronizers: new mmApi.StorageSynchronizers('/storage/synchronizers',
        {instName: 'synchronizer',
          pathPrefix: '/' + urlVersion }),
      Tags:new mmApi.Tags('/tags',
        {instName:'tag',
          pathPrefix:'/' + urlVersion}),
      Tagger:new mmApi.Tagger('/tagger',
        {instName:'tagger',
          pathPrefix:'/' + urlVersion})
    };

    this.genOnSuccess = function (resource, req, res) {
      return function (responseBody) {
        console.log('index.js: Handling - ' + req.method + ' ' + req.url + ', response payload of length - ' + JSON.stringify(responseBody).length);
        logger.info({event: '__resposne__',
          status: 0});
        res.json(200, responseBody);
      };
    };

    this.genOnError = function (resource, req, res) {
      return function (responseBody) {
        console.log('index.js: Handling - ' + req.method + ' ' + resource.path + ', response payload - ' + JSON.stringify(responseBody));
        var fields = {event: '__response__',
          status: 1,
          error_code: _.has(responseBody, 'error_code') ? responseBody.error_code : -1,
          error_message: _.has(responseBody, 'error_message') ? responseBody.error_message : ""};
        logger.info(fields);
        res.json(500, responseBody);
      };
    };

    this.initialize();
  };

  var mediaManagerApiRouter = new MediaManagerApiRouter();

  async.waterfall(
    [
      function (next) {
        server.listen(serverPort, function () {
          logger.info({event: '__start__',
            listening: serverPort});
          next();
        });

      }
    ],
    function (err, result) {
      if (err) {
        console.log('Unable to start server: ', err);
        callback(err);
      }
      callback(null, result);
    }
  );

}


var mainServer = config.LBServer.path;

////////////////////////////////redis////////////////////////////////////////
var redisClient = redis.createClient(config.Redis.port,config.Redis.ip);
redisClient.on('error',function(err){
    console.log('Error '.red, err);
    });
////////////////////////////////////////////////////////////////////////////////


////////////////////////////////rest server///////////////////////////////////////////////////////////////////////////
var server = restify.createServer();
server.use(restify.fullResponse()).use(restify.bodyParser());
server.listen(config.HTTPServer.port);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var httpPOST = function(custumerData, section, data)
{
    
  //http://192.168.0.60/CSRequestWebApi/api/
    var post_domain = custumerData.domain;  
    var post_port = custumerData.port;  
    var post_path = custumerData.path;  
  
    //var post_data = querystring.stringify({  
    //  'your' : 'post',  
    //  'data': JSON.stringify( data )
Exemple #13
0
 * @return {q.Promise[]} Array of promises
 */
const tempFiles = function (sections) {
  var hfProms = [];
  var time    = Date.now();
  sections    = Array.prototype.slice.call(arguments);
  sections.forEach(function (s) {
    var sPath = path.join(tmpDir, md5(s) + '-' + time + '.html');
    hfProms.push(writeFile(sPath, s).then(function () {
      return sPath;
    }));
  });
  return hfProms;
};

server.post('/', restify.bodyParser(), function (req, res, next) {
  var html   = req.body && req.body.html;
  var header = req.body && req.body.header;
  var footer = req.footer && req.body.footer;

  if (html) {
    Object.getOwnPropertyNames(req.query).forEach(i => {
      let t = req.query[i].toLowerCase();
      if (t === 'true' || t === 'false') {
        req.query[i] = t === 'true';
      }
    });
    req.query.debug = req.query.debug || isEB;

    var hfProms = tempFiles(header, footer);
Exemple #14
0
var restify = require("restify");
var Compose = require("./compose.js");

require("./utils.js");

var errors = [
	{
		"test"	: error => error["code"] == 'ENOENT',
		"class"	: restify.errors.NotFoundError
	}
]

var server = restify.createServer();
server.use(restify.bodyParser({maxBodySize: 60 * 1024}));

server.post('/stacks/:stack', function(req, res, next) {
	var stack = req.params.stack;
	var content = req.body;
	Compose
		.save_stack(stack, content)
		.then(stack => undefined)
		.compose(res.handle_response(next, {"success_code": 201}))
	;
});

server.get('/stacks/:stack', function(req, res, next) {
	var stack = req.params.stack;
	Compose
		.get_stack(stack)
		.compose(
			res.handle_response(next, {"errors": errors})
Exemple #15
0
function init_server() {
	var server = restify.createServer()

	server.use(restify.CORS())

	restify.CORS.ALLOW_HEADERS.push("authorization")
	restify.CORS.ALLOW_HEADERS.push("withcredentials")
	restify.CORS.ALLOW_HEADERS.push("x-requested-with")
	restify.CORS.ALLOW_HEADERS.push("x-forwarded-for")
	restify.CORS.ALLOW_HEADERS.push("x-real-ip")
	restify.CORS.ALLOW_HEADERS.push("x-customheader")
	restify.CORS.ALLOW_HEADERS.push("user-agent")
	restify.CORS.ALLOW_HEADERS.push("keep-alive")
	restify.CORS.ALLOW_HEADERS.push("host")
	restify.CORS.ALLOW_HEADERS.push("accept")
	restify.CORS.ALLOW_HEADERS.push("connection")
	restify.CORS.ALLOW_HEADERS.push("upgrade")
	restify.CORS.ALLOW_HEADERS.push("content-type")
	restify.CORS.ALLOW_HEADERS.push("dnt") // Do not track
	restify.CORS.ALLOW_HEADERS.push("if-modified-since")
	restify.CORS.ALLOW_HEADERS.push("cache-control")

	server.on("MethodNotAllowed", function(request, response) {
		if (request.method.toUpperCase() === "OPTIONS") {
			response.header("Access-Control-Allow-Credentials", true)
			response.header("Access-Control-Allow-Headers", restify.CORS.ALLOW_HEADERS.join(", "))
			response.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
			response.header("Access-Control-Allow-Origin", request.headers.origin)
			response.header("Access-Control-Max-Age", 0)
			response.header("Content-type", "text/plain charset=UTF-8")
			response.header("Content-length", 0)
			response.send(204)
		} else {
			response.send(new restify.MethodNotAllowedError())
		}
	})

	server.get('/', (req, res) => {
		getDocs(res)
	})

	server.get('/q/:query', (req, res) => {
			try {
				prepare_query(JSON.parse(req.params.query), res)
			} catch (e) {
				res.send(400, {
					error: 'malformed request'
				})
			}
	})

	server.get('/map/:query', (req, res) => {
		getMap(JSON.parse(req.params.query), res)
	})


	server.use(restify.bodyParser())
	server.post('/q', (req, res) => {
			try {
				prepare_query(req.params, res)
			} catch (e) {
				res.send(400, {
					error: 'malformed request'
				})
			}
	})

	server.listen((process.env.PORT || config.server_port), function() {
		console.log('where2 listening at port %s', (process.env.PORT || config.server_port))
		create_db()
	})
}
Exemple #16
0
            var msg = 'Request body size exceeds ' + CONFIG.api.maxRequestSize;
            next(new restify.errors.RequestEntityTooLargeError(msg));
          }
          else {
            req._jsonp_body = query;
          }
        }
      }
    }
  }
  
  return next();
});

server.use(restify.bodyParser({
  mapParams: false,
  maxBodySize: CONFIG.api.maxRequestSize
}));


// We have to parse the body ourselves here, because restify.bodyParser() 
// creates the reader and parser together, so there's no way to inject anything
server.use(function(req, res, next){
  if (req._jsonp_body) {
    req.body = req._jsonp_body;
  }
  next();
});


server.use(restify.queryParser());
server.use(restify.jsonp());
Exemple #17
0
var restify = require('restify');

var config = require('./config/config');

var redisClient = config.redisClient;
var mongoClient = config.mongoClient;

// Get the request handlers.
var handlers = [];
handlers.push(require('./controllers/admin'));

// Create the RESTful server.
var server = restify.createServer();
server.use(restify.queryParser({mapParams: false}));
server.use(restify.bodyParser({mapParams: true}));

// Install the request handler.
for (var i = 0; i < handlers.length; i++) {
	handlers[i](server, redisClient, mongoClient);
}

// Run the server.
server.listen(config.port, function(){
	console.log("Listening at %s", server.url);
});
Exemple #18
0
    }
});

var RESOURCES = Object.freeze({
    INITIAL: "/",
    TOKEN: "/token",
    PUBLIC: "/public",
    SECRET: "/secret"
});

server.use(restify.authorizationParser());
// server.use(restify.bodyParser({ mapParams: false }));
restifyOAuth2.ropc(server, {
    tokenEndpoint: RESOURCES.TOKEN,
    hooks: hooks,
    plugins: restify.bodyParser({ mapParams: false })
});



server.get(RESOURCES.INITIAL, function (req, res) {
    var response = {
        _links: {
            self: { href: RESOURCES.INITIAL },
            "http://rel.example.com/public": { href: RESOURCES.PUBLIC }
        }
    };

    if (req.username) {
        response._links["http://rel.example.com/secret"] = { href: RESOURCES.SECRET };
    } else {
Exemple #19
0
var dummyTime = 0;

// received an update message - store info
brokerUdpListener.on('message', function (message, remote) {
    messagesFromRouter++;

    if (message.length > 0)
    {
        addNodeData(message.toString());
    }
});

// Listen for and act on Broker HTTP Requests
var restify = require('restify');
var brokerListener = restify.createServer();
brokerListener.use(restify.bodyParser());
brokerListener.server.setTimeout(10000)

brokerListener.pre(function(req, res, next) {
    //console.log("REQ:", req.url);
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.setHeader('Content-Type', 'application/json');
    next();
});
brokerListener.get('/', getRoot);

brokerListener.get('/biotz', getAllBiotData);
brokerListener.get('/biotz/count', getBiotCount);
brokerListener.get('/biotz/status', getBiotzStatus);
brokerListener.get('/biotz/synchronise', biotSync);
Exemple #20
0
function configureBodyParser() {
	server.use(restify.bodyParser({ mapParams: false }));
}
Exemple #21
0
	start: function(){
		if (!this.running && !this.starting) {
			var me 		= this,
				options = this._ssl == null ? {} : this._ssl;
				
			options.name = this.name;
			options.version = this.defaultVersion;
			options.responseTimeHeader = this.responseTimeHeader;
			
			if (this.responseTimeFormatter !== null)
				options.responseTimeFormatter = this.responseFormatter;
			
			if (this.formatters !== null)
				options.formatters = this.formatters;
				
			//TODO: Support logging with Bunyan/Loggers
			
			this._server = restify.createServer(options);
			
			// Add a makeshift "all" method to the server
			this._server.all = function(route,method){
				me._server.get(route,method);
				me._server.put(route,method);
				me._server.post(route,method);
				me._server.del(route,method);
				me._server.head(route,method);
			};
			
			this._server.use(restify.acceptParser(this._server.acceptable));
			this.applyProcessor('preauthentication');
			this.applyProcessor('postauthentication');
			this.applyProcessor('preauthorization');
			this._server.use(restify.authorizationParser());
			this.applyProcessor('postauthorization');
			this._server.use(restify.dateParser());
			this._server.use(restify.queryParser());
			this._server.use(restify.bodyParser());
			
			this._server.use(function(req,res,next){
				if (req.body)
					req.body = typeof req.body == "string" ? JSON.parse(req.body) : req.body;
				next();
			});
			
			this.applyProcessor('prerequest');
			
			var _evt = [
				'NotFound',
				'MethodNotAllowed',
				'VersionNotAllowed',
				'after',
				'uncaughtException'
			];
			
			for (var e=0;e<_evt.length;e++)
				this._server.on(_evt[e],this['on'+_evt[e]]);
				
			this.generateRoutes();
			
			this.applyProcessor('postrequest');
			
			// End of request
			this._server.server.on('request',function(req,res){
				me.onRequestEnd(req,res);
			});
			
			this._serverOptions = options;
			
			this._server.listen(this.port,function(){
				
				me.on('start',function(){
					me.onReady();
				});

				me.onStart();
			});
		}  else {
			console.log('WARNING: '.yellow.bold+'Server already started or in process of starting. Cannot start twice. Make sure autoStart=true and start() are not being executed sequentially.');
		}
	},
module.exports = new Promise((resolve, reject) => {
    try {
        var restify = require('restify');
        var server = restify.createServer();

        server.use(restify.queryParser());
        server.use(restify.bodyParser());
        server.use(restify.CORS());


        var v1BuyerRouter = require('../src/routers/v1/master/buyer-router');
        v1BuyerRouter.applyRoutes(server);

        var v1SupplierRouter = require('../src/routers/v1/master/supplier-router');
        v1SupplierRouter.applyRoutes(server);

        var v1ProductRouter = require('../src/routers/v1/master/product-router');
        v1ProductRouter.applyRoutes(server);

        var v1TextileRouter = require('../src/routers/v1/master/textile-router');
        v1TextileRouter.applyRoutes(server)

        var v1FabricRouter = require('../src/routers/v1/master/fabric-router');
        v1FabricRouter.applyRoutes(server);

        var v1AccessoriesRouter = require('../src/routers/v1/master/accessories-router');
        v1AccessoriesRouter.applyRoutes(server);

        var v1SparepartRouter = require('../src/routers/v1/master/sparepart-router');
        v1SparepartRouter.applyRoutes(server);

        var v1GeneralRouter = require('../src/routers/v1/master/general-router');
        v1GeneralRouter.applyRoutes(server);

        var v1UoMRouter = require('../src/routers/v1/master/uom-router');
        v1UoMRouter.applyRoutes(server);

        var v1UnitRouter = require('../src/routers/v1/master/unit-router');
        v1UnitRouter.applyRoutes(server);

        var v1CategoryRouter = require('../src/routers/v1/master/category-router');
        v1CategoryRouter.applyRoutes(server);

        // var v1PurchaseOrderExternalRouter = require('../src/routers/v1/purchasing/purchase-order-external-router');
        // v1PurchaseOrderExternalRouter.applyRoutes(server);

        var v1PurchaseOrderRouter = require('../src/routers/v1/purchasing/purchase-order-router');
        v1PurchaseOrderRouter.applyRoutes(server,"/v1/purchasing/po");

        var v1DeliveryOrderRouter = require('../src/routers/v1/purchasing/delivery-order-router');
        v1DeliveryOrderRouter.applyRoutes(server);

        server.on('NotFound', function(request, response, cb) {
 
        }); // When a client request is sent for a URL that does not exist, restify will emit this event. Note that restify checks for listeners on this event, and if there are none, responds with a default 404 handler. It is expected that if you listen for this event, you respond to the client.
        server.on('MethodNotAllowed', function(request, response, cb) {
 
        }); // When a client request is sent for a URL that does exist, but you have not registered a route for that HTTP verb, restify will emit this event. Note that restify checks for listeners on this event, and if there are none, responds with a default 405 handler. It is expected that if you listen for this event, you respond to the client.
        server.on('VersionNotAllowed', function(request, response, cb) {

        }); // When a client request is sent for a route that exists, but does not match the version(s) on those routes, restify will emit this event. Note that restify checks for listeners on this event, and if there are none, responds with a default 400 handler. It is expected that if you listen for this event, you respond to the client.
        server.on('UnsupportedMediaType', function(request, response, cb) {
 
        }); // When a client request is sent for a route that exist, but has a content-type mismatch, restify will emit this event. Note that restify checks for listeners on this event, and if there are none, responds with a default 415 handler. It is expected that if you listen for this event, you respond to the client.
        server.on('after', function(request, response, route, error) {
 
        }); // Emitted after a route has finished all the handlers you registered. You can use this to write audit logs, etc. The route parameter will be the Route object that ran.
        server.on('uncaughtException', function(request, response, route, error) {
 
        }); // Emitted when some handler throws an uncaughtException somewhere in the chain. The default behavior is to just call res.send(error), and let the built-ins in restify handle transforming, but you can override to whatever you want here.


        server.listen(process.env.PORT, process.env.IP);
        console.log(`server created at ${process.env.IP}:${process.env.PORT}`);
        resolve(`${process.env.IP}:${process.env.PORT}`);
    }
    catch (e) {
        reject(e);
    };
});
Exemple #23
0
module.exports = function(server) {

  server.post({
      url: '/accounts',
      swagger: {
        summary: 'Create an account',
        notes: 'A unique email is expected. Passwords are hashed before being stored.',
        nickname: 'createAccount'        
      }, 
      validation: {
        email: { isRequired: true, isEmail: true, scope: 'query', description: 'Your email for login.'},
        password: { isRequired: true, scope: 'query', description: 'A new password for your account.'},
        neighborhood: { isRequired: true, scope: 'query', description: 'Neighborhood id of the user.'}
      }
    },[
      restify.queryParser(),
      restify.bodyParser(),     
      restifyValidation.validationPlugin({errorsAsArray: false}),
    ],
    accounts.create);

      // Get a user
  server.get({
      url: '/accounts/:username',
      swagger: {
        summary: 'Get the user profile',
        notes: 'Returns profile information',
        nickname: 'getUser'        
      },
      validation: {
        // email: { isRequired: true, isEmail: true, scope: 'query', description: 'Your email for login.'},
        // password: { isRequired: true, scope: 'query', description: 'A new password for your account.'}
      }
    },[  // middleware
      restify.bodyParser(),
      restifyValidation.validationPlugin({errorsAsArray: false})
    ], 
    function (req, res, next) {
      if (!req.username) {
        return res.sendUnauthenticated();
      }
      return accounts.get(req, res, next);
    });

  // Save a user
  server.put({
      url: '/accounts/:username',
      swagger: {
        summary: 'Add or update a User',
        notes: '',
        nickname: 'updateUser'              
      },
      validation: {}
    },[ // middleware
      restify.queryParser(),
      restify.bodyParser(),
      restifyValidation.validationPlugin({errorsAsArray: false})
    ],
    function (req, res, next) {
      if (!req.username || req.username !== req.params.username) {
        return res.sendUnauthenticated();
      }
      return accounts.put(req, res, next);
    });
};
Exemple #24
0
function startSvr() {
    var server = restify.createServer();
    var client = restify.createJsonClient({
        url: sdkSvrUri
    });
    server.use(restify.queryParser({mapParam : true}));
    server.use(restify.bodyParser({mapParam : true}));
    server.get('/sdkapi/login', function (req, res, next) {
        console.log('get request ' + JSON.stringify(req.params));
        client.post('/ucloud/verify_login', req.params, function (err, _req, _res, obj) {
            if (err) {
                console.log(err);
                console.log(err.stack);
                req.log.error({err: err}, 'error request login');
                return next(err);
            }
            res.send(obj);
            console.log('responds to ' + JSON.stringify(obj));
            return next();
        });
    });

    server.post('/sdkapi/buy', function (req, res, next) {
        console.log('get request ' + JSON.stringify(req.params));
        var params = {
            channel: req.params.channel,
            uid: req.params.uid,
            token: req.params.token,
            appUid: req.params.uid,
            serverId: "10",
            productId: req.params.productId,
            productCount: parseInt(req.params.count),
            productName: req.params.productName,
            productDesc: req.params.productDesc,
            productUrl: "http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif",
            singlePrice: 100,
            realPayMoney: req.params.count * 100, // all product costs ¥10 per one
            ext: "abc" // something will return back when callback from server
        };
        client.post('/ucloud/pending_pay', params, function (err, _req, _res, obj) {
            if (err) {
                console.log(err);
                console.log(err.stack);
                req.log.error({err: err}, 'error request login');
                return next(err);
            }
            var result = null;
            if (obj.code === 0) {
                result = {
                    code: obj.code,
                    orderId: obj.orderId,
                    payInfo: obj.payInfo,
                    uid: params.uid,
                    appUid: params.appUid,
                    serverId: params.serverId,
                    productId: params.productId,
                    productCount: params.productCount,
                    realPayMoney: params.realPayMoney
                };
            } else {
                result = {code : obj.code};
            }
            res.send(result);
            console.log('responds to ' + JSON.stringify(result));
            return next();

        });
    });

    server.post('/sdkapi/charge', function (req, res, next) {
        console.log('get request ' + JSON.stringify(req.params));
        var params = {
            channel: req.params.channel,
            uid: req.params.uid,
            token: req.params.token,
            appUid: req.params.uid,
            serverId: "10",
            productCount: req.params.count,
            singlePrice: 10,
            realPayMoney: req.params.count * 10, // ¥1.0 can buy 10 currency
            ext: "abc", // something will return back when callback from server
        };
        client.post('/ucloud/pending_pay', params, function (err, _req, _res, obj) {
            if (err) {
                console.log(err);
                console.log(err.stack);
                req.log.error({err: err}, 'error request login');
                return next(err);
            }
            var result = null;
            if (obj.code === 0) {
                result = {
                    code: obj.code,
                    orderId: obj.orderId,
                    payInfo: obj.payInfo,
                    uid: params.uid,
                    appUid: params.appUid,
                    serverId: params.serverId,
                    currencyCount: params.currencyCount,
                    realPayMoney: params.realPayMoney,
                    ratio: 10
                };
            } else {
                result  = {code : obj.code};
            }
            res.send(result);
            console.log('responds to ' + JSON.stringify(result));
            return next();

        });
    });

        console.log("xxxxxxxx");
    server.post('/callback/charge',  function (req, res, next) {
        console.log("receive callback charge: " + JSON.stringify(req.params));
        //res.send({code : -1});
        //next();
    });

    server.post('/callback/buy',  function (req, res, next) {
        console.log("receive callback buy: " + JSON.stringify(req.params));
        //res.send({code : -1});
        //next();
    });

    server.listen(8080);
    server.on('uncaughtException', function (req, res, route, err) {
        console.log('on exception ' + err.message);
        console.log('on exception ' + err.stack);
    });
}
Exemple #25
0
var app = module.exports = function(config) {
  var server = restify.createServer({ name: 'notify' });
  var port = config.port || 3000;
  var smtp = mailer.createTransport("SMTP", config.smtp);

  // TODO: add authentication...

  // setup body Parser
  server.use(restify.bodyParser());

  // get all channels
  server.get('/', function(req, res, next) {
    //db.createReadStream().pipe(res);
    res.send('Welcome to Notify Service');
    return next();
  });

  // get channel info
  server.get('/:channel', function(req, res, next) {
    db.get(req.params.channel, function(err, channel) {
      if (err) { res.send(404); return next(); }
      res.send(channel);
      return next();
    })
  });

  // publish
  server.post('/publish/:channel', function(req, res, next) {
    // validate subscriber
    if (!req.params.title) { 
      res.send(500, { error: 'publish title is required!'}); 
      return next();
    }
    if (!req.params.msg) { 
      res.send(500, { error: 'publish msg is required!'}); 
      return next();
    }

    db.get(req.params.channel, function(err, channel) {
      if (err) { res.send(404); return next(); }
      notify(req.params, channel.subscriptions);
      res.send(200);
      return next();
    });
  });

  // subscribe
  server.post('/subscribe/:channel', function(req, res, next) {
    // validate subscriber
    if (!req.params.name) { 
      res.send(500, { error: 'subscriber name is required!'}); 
      return next();
    }
    if (!req.params.service) { 
      res.send(500, { error: 'subscriber service is required!'}); 
      return next();
    }
    // fetch channel data
    db.get(req.params.channel, function(err, channel) {
      // if not found then create new channel
      if (err) { channel = { name: req.params.channel, subscriptions: []}; }
      // fetch subscription
      var subscription = _(channel.subscriptions).findWhere({name: req.params.name});
      // if not found add subscription to channel
      if (!subscription) { 
        channel.subscriptions.push(req.params);
      } else {
        // otherwise update subscription with new information
        _(subscription).extend(req.params);
      }
      // save channel to db
      db.put(channel.name, channel, function(err) {
        if (err) { res.send(500); return next(); }
        // send success
        res.send(200);
        return next();
      });
    });
  });

  // remove channel
  server.del('/:channel', function(req, res, next) {
    db.del(req.params.channel, function(err) {
      res.send(200);
    });
  });

  server.listen(port, function() {
    console.log('~ notify ~');
    console.log('listening on %s', port);
  });

  function notify(info, list) {
    _(list).each(function(item) { send(item, info); });
  };

  var send = mm()
    .dispatch(function(contact, msg) {
      return contact.service;
    })
    .when("email", function(contact, info) {
      mail(contact.address, info);
    })
    .when("http", function(contact, info) {
      post(contact.href, info);
    })
    .when("sms", function(contact, info) {
      console.log('POST' + contact.phone);
    })
    ;

  var post = function(href, info) {
    request.post(href, {json: info}, function(e,r,b) {
      if (e) { return console.log(e); }
      console.log('Msg Sent: ' + b);
    });
  };
  
  // email notification
  var mail = function(toAddress, info) {
    var mailOptions = {
        from: config.smtp.fromAddress, // sender address
        to: toAddress, // list of receivers
        subject: info.title, // Subject line
        text: info.msg // plaintext body
    };

    // send mail with defined transport object
    smtp.sendMail(mailOptions, function(err, res){
        if(err){ return console.log(error); } 
        console.log("Message sent: " + res.message);
        // if you don't want to use this transport object anymore, uncomment following line
        //smtpTransport.close(); // shut down the connection pool, no more messages
    });  
  };
};
Exemple #26
0
var createServer = module.exports.createServer = function(options) {
  assert.object(options);
  assert.object(options.log);
  assert.string(options.dbconn);

  // connect to db
  mongoose.connect(options.dbconn);

  // start up server
  var server = restify.createServer({
      log: options.log,
      name: 'village-api',
      version: '1.0.0'
  });

  server.pre(restify.pre.sanitizePath());
  server.pre(restify.pre.userAgentConnection());
  server.use(restify.requestLogger());

  server.use(restify.acceptParser(server.acceptable));
  server.use(restify.dateParser());
  server.use(restify.authorizationParser());
  server.use(restify.queryParser());
  server.use(restify.gzipResponse());
  server.use(restify.bodyParser());

  // auth
  // todo - grab creds first
  // pass to authentication
  server.use(auth.authenticate);
  server.use(crossOrigin);

  server.opts('.*', handleOptions);

  // set up routes
  initRoutes(server, [
    { url: '/families', model: models.Family },
    { url: '/students', model: models.Student },
    { url: '/config',   model: models.Config }
  ], options);

  // default / handler
  server.get('/', function root(req, res, next) {
    res.send(200, 'ok');
    next();
  });

  // Setup an audit logger
  if (!options.noAudit) {
    server.on('after', restify.auditLogger({
      body: true,
      log: bunyan.createLogger({
            level: 'info',
            name: 'village-api-audit',
            stream: process.stdout
      })
    }));
  }

  return (server);
};
		function (done) {
			publicServer = restify.createServer({
				name: 'cipherlayer-server',
				log: log
			});

			log.info('PUBLIC SERVICE starting on PORT ' + publicPort);

			publicServer.on('after', function (req, res) {
				var logInfo = {
					request: {
						method: req.method,
						headers: req.headers,
						url: req.url,
						path: req._url.pathname,
						query: req._url.query,
						params: req.params,
						time: req._time
					},
					response: {
						statusCode: res.statusCode,
						hasBody: res.hasBody,
						bodySize: _.size(res.body),
						time: Date.now()
					},
					user: req.user,
					tokenInfo: req.tokenInfo
				};
				delete(logInfo.request.params.password);

				req.log.info(logInfo, "response");
			});

			if (config.accessControlAllow) {
				publicServer.use(restify.CORS({
					origins: config.accessControlAllow.origins,
					credentials: true,
					headers: config.accessControlAllow.headers
				}));

				publicServer.opts(/.*/, function (req, res, next) {
					res.header("Access-Control-Allow-Methods", req.header("Access-Control-Request-Methods"));
					res.header("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
					res.send(200);
					return next();
				});
			}

			publicServer.use(restify.queryParser());
			publicServer.use(bodyParserWrapper(restify.bodyParser({maxBodySize: 1024 * 1024 * 3})));

			var versionControlOptions = _.clone(config.version);
			versionControlOptions.public = [
				"/auth/sf",
				"/auth/sf/*",
				"/auth/in",
				"/auth/in/*",
				"/auth/google",
				"/auth/google/*",
				"/auth/login/refreshToken*",
				"/user/activate*",
				"/heartbeat",
				"/user/email/available"
			];
			publicServer.use(versionControl(versionControlOptions));

			publicServer.on('uncaughtException', function (req, res, route, error) {
				log.error({exception: {req: req, res: res, route: route, err: error}});
				if (!res.statusCode) {
					res.send(500, {err: 'internal_error', des: 'uncaught exception'});
				}
			});

			var routesPath = path.join(__dirname, './public_routes/');
			fs.readdirSync(routesPath).forEach(function (filename) {
				require(routesPath + filename)(publicServer);
			});

			var platformsPath = path.join(__dirname, '/platforms/');
			fs.readdirSync(platformsPath).forEach(function (filename) {
				require(platformsPath + filename).addRoutes(publicServer, passport);
			});

			publicServer.get(/(.*)/, checkAccessTokenParam, checkAuthHeader, decodeToken, permissions, findUser, pinValidation, userAppVersion, prepareOptions, platformsSetUp, propagateRequest);
			publicServer.post(/(.*)/, checkAccessTokenParam, checkAuthHeader, decodeToken, permissions, findUser, pinValidation, userAppVersion, prepareOptions, platformsSetUp, propagateRequest);
			publicServer.del(/(.*)/, checkAccessTokenParam, checkAuthHeader, decodeToken, permissions, findUser, pinValidation, userAppVersion, prepareOptions, platformsSetUp, propagateRequest);
			publicServer.put(/(.*)/, checkAccessTokenParam, checkAuthHeader, decodeToken, permissions, findUser, pinValidation, userAppVersion, prepareOptions, platformsSetUp, propagateRequest);

			publicServer.listen(publicPort, function () {
				log.info('PUBLIC SERVICE listening on PORT ' + publicPort);
				done();
			});
		},
Exemple #28
0
function CartoDBApiProxy(server, host, port, api_key) {

  server.use(restify.acceptParser(server.acceptable));
  server.use(restify.queryParser());
  server.use(restify.bodyParser());

  var urls = this.urls = new URLs();
  var proxy = new httpProxy.RoutingProxy();

  server.get('/api/sql', function (req, res, next) {
    if(req.params.api_key !== api_key) {
      res.send(403);
      return next();
    }
    res.send(urls.to_json());
  });

  var create_url_controller = function(type, req, res, next) {
    //check auth
    if(req.params.api_key !== api_key) {
      res.send(403);
      return next();
    }

    if(req.params.url && req.params.path) {
      urls.create(req.params.url, type, req.params.path);
      res.send();
    } else {
      res.send(400);
    }
    return next();
  }

  server.post('/api/sql', function (req, res, next) {
    return create_url_controller('sql', req, res, next);
  });

  server.post('/api/tiles', function (req, res, next) {
    return create_url_controller('tiles', req, res, next);
  });



  var proxy_to = function(u, req, res) {
    req.url = u + "&api_key=" + api_key;
    req.headers['Host'] = host;
    req.method = 'GET'
    req.headers['Content-Length'] = 0;
    proxy.proxyRequest(req, res, {
      host: host,
      port: port
    });
  }

  var proxy_regexp = /^\/([a-zA-Z0-9_\.~\-]+)\/?/;
  var proxy_controller = function (req, res, next) {
    console.log(req.params);
    if(urls.exists(req.params[0])) {
      var u = urls.evaluate(req.params[0], req.params);
      console.log(u);
      proxy_to(u, req, res);
    } else {
      res.send(404);
    }
  };

  server.get(proxy_regexp, proxy_controller);
  server.post(proxy_regexp, proxy_controller);

}
Exemple #29
0
var restify = require('restify');
var _ = require('underscore');

var DS = require('./DS');

var server = restify.createServer({ name: 'api' })

server
  .use(restify.fullResponse())
  .use(restify.bodyParser())

var ds = new DS();

// The main API route for movies
server.get('/api/movies', function (req, res, next) {
  ds.allMovies()
    .then(function(m) { res.send(m); })
    .catch(function(err) { res.send(500, err) });
});

server.get("/api/movies/:key", function(req, res, next) {
    ds.find(req.params.key)
             .then(function(m) { res.send(m); })
             .error(function (e) {
               res.send(400, {err: e.message});
             })
            .catch(function(err) { res.send(500, err) });
});

server.put("/api/movies/:key", function(req, res, next) {
    ds.voteMovie(req.params.key, req.body.vote)
// Server Class
function Server() {
  var self = this;
  
  if (arguments.callee._singletonInstance)
    return arguments.callee._singletonInstance;
  arguments.callee._singletonInstance = self;
  
  self.restServer    = restify.createServer();
  self.queue         = new Queue(['add-task', 'update-task', 'add-section', 'update-section', 'add-tasklog']);
  
  self.restServer.use(restify.fullResponse());
  self.restServer.use(restify.bodyParser());
  
  self.restServer.post('/add/section', function (request, response, next) {
    self.queue.push('add-section', new Section(JSON.parse(request.params.data)));
    response.send(200, new Date());
    response.end();
    return next();
  });
  
  self.restServer.post('/update/section', function (request, response, next) {
    self.queue.push('update-section', new Section(JSON.parse(request.params.data)));
    response.send(200, new Date());
    response.end();
    return next();
  });

  self.restServer.post('/add/task', function (request, response, next) {
    self.queue.push('add-task', new Task(JSON.parse(request.params.data)));
    response.send(200, new Date());
    response.end();
    return next();
  });
  
  self.restServer.post('/update/task', function (request, response, next) {
    self.queue.push('update-task', new Task(JSON.parse(request.params.data)));
    response.send(200, new Date());
    response.end();
    return next();
  });
  
  self.restServer.post('/update/tasks', function (request, response, next) {
    var tasks = JSON.parse(request.params.data);
    for (var i = 0; i < tasks.length; i++) {
      self.queue.push('update-task', new Task(tasks[i]));
    }
    response.send(200, new Date());
    response.end();
    return next();
  });
  
  self.restServer.post('/add/tasklog', function (request, response, next) {
    self.queue.push('add-tasklog', new TaskLog(JSON.parse(request.params.data)));
    response.send(200, new Date());
    response.end();
    return next();
  });
  
  self.restServer.get('/data', function (request, response, next){
    response.send(200, {sections: GoogleDrive.sections, tasks: GoogleDrive.tasks, lastSync: GoogleDrive.lastSync});
  });

  self.restServer.get(/.*/, restify.serveStatic({
    directory: './public'
  }));
  
  self.start = function(port) {
    self.restServer.listen(port, function (){
      GoogleDrive.updateSections();
      GoogleDrive.updateTasks();
      GoogleDrive.updateTaskLogs();
      console.log('%s listening at %s', self.restServer.name, self.restServer.url);
    });
  }

}