app.get('/', function (req, res) {
   res.writeHead(200, { "Content-Type": "text/html", "x-guid": uuid.v1() });
   res.end('I am from the second stub server!');
 });
Exemple #2
0
function getGUID(){
	return uuid.v1();
}
function boundary() {
  return "----FormBoundary-" + uuid.v1();
}
Exemple #4
0
 onCreate: function() {
   this.set('id', uuid.v1());
 },
Exemple #5
0
router.get('/setup', function(req, res) {
	//create a sample user

	var uuid = _uuid.v1();

	// compose data
	var data = credential_data;

	// Load Users_credentials -table
	User_credentials()
		.done(function(credentials){
			// Load Users -table
			Users()
				.done(function(users){
					var found_credential,
						credential,
						found_user,
						user;

					found_credential = credentials.findOne({ 'username': data.user_credentials.username });
					found_user       = users.findOne({ 'uuid': uuid });

					if (!found_credential) {
						inserted_credential = credentials.insert( data.user_credentials );

						try {
							db.saveDatabase();
							log('credentials saved');

							if(!found_user) {
								inserted_user       = users.insert( data.user );
								log('user saved');

							} else {
								updated_user        = users.update( data.user );
								log('user updated');
							}
							db.saveDatabase();

							return res.json({
								success: true,
								data: inserted_user
							})

						} catch(err) {
							return res.json({ 
							success: false, 
							message: 'Saving credentials error' });
						}


					} else {
						return res.json({ 
							success: false, 
							message: 'User already exist' });
					}

				});

		}, res.send.bind(res))

	// return to route
});
Exemple #6
0
main.setGame = function(name) {
    var g = new game(uuid.v1(), name);
    this.games.push(g);

    return g;
};
/**
* Page blob basics.
* @ignore
* 
* @param {config}               config                           The configuration which contains the connectionString.
* @param {errorOrResult}        callback                         The callback function.
*/
function basicStorageBlockBlobOperations(config, callback) {
  // Create a blob client for interacting with the blob service from connection string
  // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
  var blobService = storage.createBlobService(config.connectionString);

  var fileToUpload = "HelloWorld.dat";
  writeRandomFile(fileToUpload, 1024);
  var blockBlobContainerName = "demoblockblobcontainer-" + guid.v1();
  var blockBlobName = "demoblockblob-" + fileToUpload;
  
  console.log('Block Blob Sample');
  
  // Create a container for organizing blobs within the storage account.
  console.log('1. Creating Container');
  blobService.createContainerIfNotExists(blockBlobContainerName, function (error) {
    if (error) {
      callback(error);
    } else {
      // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate 
      // access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions 
      // to allow public access to blobs in this container. Uncomment the line below to use this approach. Then you can view the image 
      // using: https://[InsertYourStorageAccountNameHere].blob.core.windows.net/demoblockblobcontainer-[guid]/demoblockblob-HelloWorld.png
      
      // Upload a BlockBlob to the newly created container
      console.log('2. Uploading BlockBlob');
      blobService.createBlockBlobFromLocalFile(blockBlobContainerName, blockBlobName, fileToUpload, function (error) {
        if (error) {
          callback(error);
        } else {
          // List all the blobs in the container
          console.log('3. List Blobs in Container');
          listBlobs(blobService, blockBlobContainerName, null, null, function (error, results) {
            if (error) {
              callback(error);
            } else {
              for (var i = 0; i < results.length; i++) {
                console.log(util.format('   - %s (type: %s)'), results[i].name, results[i].blobType);
              }
              
              // Download a blob to your file system
              console.log('4. Download Blob');
              var downloadedFileName = util.format('CopyOf%s', fileToUpload);
              blobService.getBlobToLocalFile(blockBlobContainerName, blockBlobName, downloadedFileName, function (error) {
                if (error) {
                  callback(error);
                } else {
                  // Create a read-only snapshot of the blob
                  console.log('5. Create a read-only snapshot of the blob'); 
                  blobService.createBlobSnapshot(blockBlobContainerName, blockBlobName, function (error, snapshotId) {
                    if (error) {
                      callback(error);
                    } else {
                      // Create three new blocks and upload them to the existing blob
                      console.log('6. Create three new blocks and upload them to the existing blob');
                      var buffer = getRandomBuffer(1024);
                      var blockIds = [];
                      var blockCount = 0;
                      var blockId = getBlockId(blockCount);
                      var uploadBlockCallback = function (error) {
                        if (error) {
                          callback(error);
                        } else {
                          blockCount++;
                          if (blockCount <= 3) {
                            blockId = getBlockId(blockCount);
                            blockIds.push(blockId);
                            blobService.createBlockFromText(blockId, blockBlobContainerName, blockBlobName, buffer, uploadBlockCallback);
                          } else {
                            // Important: Please make sure that you call commitBlocks in order to commit the blocks to the blob
                            var blockList = { 'UncommittedBlocks': blockIds };
                            blobService.commitBlocks(blockBlobContainerName, blockBlobName, blockList, function (error) {
                              
                              // Clean up after the demo 
                              console.log('7. Delete block Blob and all of its snapshots');
                              var deleteOption = { deleteSnapshots: storage.BlobUtilities.SnapshotDeleteOptions.BLOB_AND_SNAPSHOTS };
                              blobService.deleteBlob(blockBlobContainerName, blockBlobName, deleteOption, function (error) {
                                try { fs.unlinkSync(downloadedFileName); } catch (e) { }
                                if (error) {
                                  callback(error);
                                } else {
                                  // Delete the container
                                  console.log('8. Delete Container');
                                  blobService.deleteContainerIfExists(blockBlobContainerName, function (error) {
                                    try { fs.unlinkSync(fileToUpload); } catch (e) { }
                                    callback(error);
                                  });
                                }
                              });
                            });
                          }
                        }
                      };
                      
                      blockIds.push(blockId);
                      blobService.createBlockFromText(blockId, blockBlobContainerName, blockBlobName, buffer, uploadBlockCallback);
                    }
                  });
                }
              });
            }
          });
        }
      });
    }
  });
}
var uuid = require('node-uuid');

var v1 = uuid.v1();

console.log(v1);
Exemple #9
0
 function generateUuid() {
     return uuid.v4(uuid.v1());
 }
Exemple #10
0
  run: function(global) {
    console.log("V3 mvcflow start");

    // start from create Node Model
    console.log("Test Class Target:");
    var oTarget = new Target();
    oTarget.setId(uuid.v1());
    oTarget.setInfo(new Info());
    oTarget.getInfo().setCode("a.b.c.D");
    oTarget.getInfo().setName("D 0");
    oTarget.getInfo().setRemark("this is a target");
    console.log("oTarget: " + printTarget(oTarget));
    console.log("");

    console.log("Test Class Scope:");
    var oScope = new Scope();
    oScope.registerTarget(oTarget);
    var oScopeTarget = oScope.getTarget(oTarget.getId());
    console.log("oScopeTarget is: " + printTarget(oScopeTarget));
    var oGenedInfo = generateMockInfo();
    var oGenedTarget = generateMockTarget();
    for (var i = 0; i < 10; i++) {
      var oGenedItemTaget = generateMockTarget();
      oScope.registerTarget(oGenedItemTaget);
    }
    var aProps = oScope.getAllTargetIds()
    console.log("scope all tIds are: " + aProps);
    console.log("");

    console.log("Test Class NodeModel, Node:");
    var oGuestNodeModel = generateNodeModel({
      "code": "mvcflow.sample.nodes.Guest",
      "name": "Guest",
      "remark": "This is Guest node",
      "exits": ["logon", "exit"]
    });
    var oGuestNode = oGuestNodeModel.newInstance();
    var oLogonNodeModel = generateNodeModel({
      "code": "mvcflow.sample.nodes.Logon",
      "name": "Logon",
      "remark": "This is Logon node",
      "exits": ["success", "error"]
    });
    var oLogonNode = oLogonNodeModel.newInstance();
    var oHomeNodeModel = generateNodeModel({
      "code": "mvcflow.sample.nodes.Home",
      "name": "Home",
      "remark": "This is Home node",
      "exits": ["logout", "business"]
    });
    var oHomeNode = oHomeNodeModel.newInstance();
    var oBusinessNodeModel = generateNodeModel({
      "code": "mvcflow.sample.nodes.Business",
      "name": "Business",
      "remark": "This is Business node",
      "exits": ["complete"]
    });
    var oBusinessNode = oBusinessNodeModel.newInstance();
    console.log("");

    console.log("Test Class FlowModel:");
    var oFlowModel = new FlowModel();
    oFlowModel.setInfo(new Info());
    oFlowModel.getInfo().setCode("mvcflow.sample.flows.Menu");
    oFlowModel.getInfo().setName("Menu");
    oFlowModel.getInfo().setRemark("Menu FM");
    oFlowModel.setExits(["flowend"]);

    oFlowModel.addNode(oGuestNode);
    oFlowModel.addNode(oLogonNode);
    oFlowModel.addNode(oHomeNode);
    oFlowModel.addNode(oBusinessNode);

    // Flow mappings
    // Guest.exit -> flow.flowend
    // Guest.logon -> logon
    // Logon.success -> Home
    // Logon.error -> Guest
    // Home.logout -> Guest
    // Home.business -> Business
    // Business.complete -> Home
    oFlowModel.setEntry(oGuestNode.getId());
    oFlowModel.addMapping(generateSource(oGuestNode, "logon"), generateDestination(false, oLogonNode));
    oFlowModel.addMapping(generateSource(oGuestNode, "exit"), generateDestination(true, "flowend"));
    oFlowModel.addMapping(generateSource(oLogonNode, "success"), generateDestination(false, oHomeNode));
    oFlowModel.addMapping(generateSource(oLogonNode, "error"), generateDestination(false, oGuestNode));
    oFlowModel.addMapping(generateSource(oHomeNode, "logout"), generateDestination(false, oGuestNode));
    oFlowModel.addMapping(generateSource(oHomeNode, "business"), generateDestination(false, oBusinessNode));
    oFlowModel.addMapping(generateSource(oBusinessNode, "complete"), generateDestination(false, oHomeNode));

    var oFlowEngine = new FlowEngine();
    oFlowEngine.setFlowModel(oFlowModel);
    oFlowEngine.start();
    oFlowEngine.goToNextNode("logon");
    oFlowEngine.goToNextNode("success");
    oFlowEngine.goToNextNode("business");
    oFlowEngine.goToNextNode("complete");
    oFlowEngine.goToNextNode("logout");
    oFlowEngine.goToNextNode("exit");
    console.log("");

    // Test subflow
    console.log("Test Sub Flow");
    // NodeModel & Nodes
    var oBusinessMasterNodeModel = generateNodeModel({
      "code": "mvcflow.sample.nodes.BusinessMaster",
      "name": "BusinessMaster",
      "remark": "This is Business Master node",
      "exits": ["detail", "exit"]
    });
    var oBusinessMasterNode = oBusinessMasterNodeModel.newInstance();
    var oBusinessDetailNodeModel = generateNodeModel({
      "code": "mvcflow.sample.nodes.BusinessDetail",
      "name": "BusinessDetail",
      "remark": "This is Business Detail node",
      "exits": ["master"]
    });
    var oBusinessDetailNode = oBusinessDetailNodeModel.newInstance();
    // FlowModel
    var oBusinessFlowModel = generateFlowModel({
      "code": "mvcflow.sample.flows.BusinessFlow",
      "name": "BusinessFlow",
      "remark": "Master Detail Business flow",
      "exits": ["complete"]
    });
    oBusinessFlowModel.registerModel(oBusinessMasterNodeModel);
    oBusinessFlowModel.registerModel(oBusinessDetailNodeModel);
    var oBusinessFlowNode = oBusinessFlowModel.newInstance();
    oBusinessFlowModel.addNode(oBusinessMasterNode);
    oBusinessFlowModel.addNode(oBusinessDetailNode);
    oBusinessFlowModel.setEntry(oBusinessMasterNode.getId());
    oBusinessFlowModel.addMapping(generateSource(oBusinessMasterNode, "detail"), generateDestination(false, oBusinessDetailNode));
    oBusinessFlowModel.addMapping(generateSource(oBusinessMasterNode, "exit"), generateDestination(true, "complete"));
    oBusinessFlowModel.addMapping(generateSource(oBusinessDetailNode, "master"), generateDestination(false, oBusinessMasterNode));
    // FlowEngine run
    var oBusinessFlowEngine = generateFlowEngine(oBusinessFlowModel);
    oBusinessFlowEngine.start();
    oBusinessFlowEngine.goToNextNode("detail");
    oBusinessFlowEngine.goToNextNode("master");
    oBusinessFlowEngine.goToNextNode("exit");
    console.log("");

    // Test App Flow (Embed with Sub Flow)
    console.log("Test App Flow");
    // FlowModel
    var oAppFlowModel = generateFlowModel({
      "code": "mvcflow.sample.flows.App",
      "name": "App",
      "remark": "This is App flow",
      "exits": ["flowend"]
    });
    // dependcies
    oAppFlowModel.registerModel(oGuestNodeModel);
    oAppFlowModel.registerModel(oLogonNodeModel);
    oAppFlowModel.registerModel(oHomeNodeModel);
    oAppFlowModel.registerModel(oBusinessFlowModel);
    // nodes
    oAppFlowModel.addNode(oGuestNode);
    oAppFlowModel.addNode(oLogonNode);
    oAppFlowModel.addNode(oHomeNode);
    oAppFlowModel.addNode(oBusinessFlowNode);
    // mappings
    oAppFlowModel.setEntry(oGuestNode.getId());
    oAppFlowModel.addMapping(generateSource(oGuestNode, "logon"), generateDestination(false, oLogonNode));
    oAppFlowModel.addMapping(generateSource(oGuestNode, "exit"), generateDestination(true, "flowend"));
    oAppFlowModel.addMapping(generateSource(oLogonNode, "success"), generateDestination(false, oHomeNode));
    oAppFlowModel.addMapping(generateSource(oLogonNode, "error"), generateDestination(false, oGuestNode));
    oAppFlowModel.addMapping(generateSource(oHomeNode, "logout"), generateDestination(false, oGuestNode));
    oAppFlowModel.addMapping(generateSource(oHomeNode, "business"), generateDestination(false, oBusinessFlowNode));
    oAppFlowModel.addMapping(generateSource(oBusinessFlowNode, "complete"), generateDestination(false, oHomeNode));
    // FlowEngine run
    var oAppFlowEngine = generateFlowEngine(oAppFlowModel);
    oAppFlowEngine.start();
    oAppFlowEngine.goToNextNode("logon");
    oAppFlowEngine.goToNextNode("success");
    oAppFlowEngine.goToNextNode("business");
    oAppFlowEngine.goToNextNode("detail");
    oAppFlowEngine.goToNextNode("master");
    oAppFlowEngine.goToNextNode("exit");
    oAppFlowEngine.goToNextNode("logout");
    oAppFlowEngine.goToNextNode("logon");
    oAppFlowEngine.goToNextNode("error");
    oAppFlowEngine.goToNextNode("exit");
    console.log("");

    console.log("Test FlowMaker");
    //FlowMaker.saveFlowModelToFile(oAppFlowModel);
    //FlowMaker.readFlowModelFromFile();
    // How to serialize FlowModel
    // Implements ways of NodeModel to string.
    // Implements ways of Node to string (without model), use code for reference
    // Implements ways of Mapping to string, use ID instead Node.
    // If depends on a FlowModel, load dependcies FlowModel first.
    var nodeModelJsonString = nodeModelToJSONString(oGuestNodeModel);
    console.log("nodeModelToJSONString: " + nodeModelJsonString);
    var nodeJsonString = nodeToJSONString(oGuestNode);
    console.log("nodeToJSONString: " + nodeJsonString);
    var flowModelJsonString = flowModelToJSONString(oBusinessFlowModel);
    console.log("flowModelToJSONString: " + flowModelJsonString);
    var subflowModelJsonStringWith = flowModelToJSONString(oAppFlowModel);
    console.log("subflowModelJsonStringWith: " + flowModelJsonString);
    FlowMaker.saveFlowModelToFile(oBusinessFlowModel);
    FlowMaker.saveFlowModelToFile(oAppFlowModel);
    var oReadBusinessFlowModel = FlowMaker.readFlowModelFromFile("mvcflow.sample.flows.BusinessFlow");
    console.log("readFM:" + printObject(oReadBusinessFlowModel));
    var oReadAppFlowModel = FlowMaker.readFlowModelFromFile("mvcflow.sample.flows.App");
    // FlowEngine run
    var oReadAppFlowEngine = generateFlowEngine(oReadAppFlowModel);
    oReadAppFlowEngine.start();
    oReadAppFlowEngine.goToNextNode("logon");
    oReadAppFlowEngine.goToNextNode("success");
    oReadAppFlowEngine.goToNextNode("business");
    oReadAppFlowEngine.goToNextNode("detail");
    oReadAppFlowEngine.goToNextNode("master");
    oReadAppFlowEngine.goToNextNode("exit");
    oReadAppFlowEngine.goToNextNode("logout");
    oReadAppFlowEngine.goToNextNode("logon");
    oReadAppFlowEngine.goToNextNode("error");
    oReadAppFlowEngine.goToNextNode("exit");
  }
Exemple #11
0
function create(author,name){
    data.author = author,
    data.id = uuid.v1()
    data.name = name
}
describe('/server/api/job', function () {

  var TENANT = 'nlc-test';
  var JOB = uuid.v1();
  var ENDPOINTBASE = '/api/' + TENANT + '/jobs/' + JOB;

  this.timeout(5000);

  before(function () {

    this.error = {
      error : 'test-generated',
      statusCode : httpstatus.INTERNAL_SERVER_ERROR
    };

  });

  this.timeout(5000);

  beforeEach(function () {

    this.cacheMock = new mocks.CacheMock();

    this.controllerOverrides = {
      './cache' : this.cacheMock
    };

    this.controller = proxyquire('./job.controller', this.controllerOverrides);

    this.restMock = {
      ensureAuthenticated : function (req, res, next) {
        next();
      }
    }

    this.app = express();

    this.appOverrides = {
      './job.controller' : this.controller,
      '../../config/rest' : this.restMock
    }

    this.app.use('/api', proxyquire('./index', this.appOverrides));

    this.agent = request.agent(this.app);

  });

  describe('/:tenantid/jobs/:jobid', function () {

    describe('GET', function () {

      it('should retrieve job info', function (done) {
        this.agent
          .get(ENDPOINTBASE)
          .expect('Content-Type', /json/)
          .expect(httpstatus.OK)
          .end(function (err, resp) {
            resp.should.have.property('body');
            this.cacheMock.get.should.have.been.calledWith(JOB);
            done(err);
          }.bind(this));
      });

      it('should return 404 if job not found', function (done) {
        this.cacheMock.get.returns(null);

        this.agent
          .get(ENDPOINTBASE)
          .expect('Content-Type', /json/)
          .expect(httpstatus.NOT_FOUND)
          .end(function (err, resp) {
            this.cacheMock.get.should.have.been.calledWith(JOB);
            done(err);
          }.bind(this));
      });

    });

  });

});
Exemple #13
0
module.exports.run = function (argv) {

    // Parse args
    var args = nopt({'guid': String}, {}, argv);

    if(!args.argv.remain.length) {
        return Q.reject('No path specified.');
    }

    // Set parameters/defaults for create
    var projectPath = args.argv.remain[0];
    if (fs.existsSync(projectPath)){
        return Q.reject('Project directory already exists:\n\t' + projectPath);
    }
    var packageName = args.argv.remain[1] || 'Cordova.Example',
        appName     = args.argv.remain[2] || 'CordovaAppProj',
        // 64 symbols restriction goes from manifest schema definition
        // http://msdn.microsoft.com/en-us/library/windows/apps/br211415.aspx
        safeAppName = appName.length <= 64 ? appName : appName.substr(0, 64),
        templateOverrides = args.argv.remain[3],
        guid        = args['guid'] || uuid.v1(),
        root        = path.join(__dirname, '..', '..');

    console.log('Creating Cordova Windows Project:');
    console.log('\tApp Name  : ' + appName);
    console.log('\tNamespace : ' + packageName);
    console.log('\tPath      : ' + projectPath);
    if (templateOverrides) {
        console.log('\tCustomTemplatePath : ' + templateOverrides);
    }

    // Copy the template source files to the new destination
    console.log('Copying template to ' + projectPath);
    shell.cp('-rf', path.join(root, 'template', '*'), projectPath);

    // Copy our unique VERSION file, so peeps can tell what version this project was created from.
    shell.cp('-rf', path.join(root, 'VERSION'), projectPath);

    // copy node_modules to cordova directory
    shell.cp('-r', path.join(root, 'node_modules'), path.join(projectPath, 'cordova'));

    // copy check_reqs module to cordova directory
    shell.cp('-rf', path.join(root, 'bin', 'check_reqs*'), path.join(projectPath, 'cordova'));
    shell.cp('-rf', path.join(root, 'bin', 'lib', 'check_reqs*'), path.join(projectPath, 'cordova', 'lib'));

    if (templateOverrides && fs.existsSync(templateOverrides)) {
        console.log('Copying template overrides from ' + templateOverrides + ' to ' + projectPath);
        shell.cp('-rf', templateOverrides, projectPath);
    }

    // replace specific values in manifests' templates
    ['package.windows.appxmanifest', 'package.windows80.appxmanifest', 'package.phone.appxmanifest', 'package.windows10.appxmanifest'].forEach(function (file) {
        var fileToReplace = path.join(projectPath, file);
        shell.sed('-i', /\$guid1\$/g, guid, fileToReplace);
        shell.sed('-i', /\$packagename\$/g, packageName, fileToReplace);
        shell.sed('-i', /\$projectname\$/g, safeAppName, fileToReplace);
    });

    // Delete bld forder and bin folder
    ['bld', 'bin', '*.user', '*.suo', 'MyTemplate.vstemplate'].forEach(function (file) {
        shell.rm('-rf', path.join(projectPath, file));
    });

    // TODO: Name the project according to the arguments
    // update the solution to include the new project by name
    // version BS
    // index.html title set to project name ?
    
    return Q.resolve();
};
Exemple #14
0
    fromSocket: function(socket, cb) {

      // If a socket makes it here, even though its associated session is not specified,
      // it's authorized as far as the app is concerned, so no need to do that again.
      // Instead, use the cookie to look up the sid, and then the sid to look up the session data


      // If sid doesn't exit in socket, we have to do a little work first to get it
      // (or generate a new one-- and therefore a new empty session as well)
      if (!socket.handshake.sessionID && !socket.handshake.headers.cookie) {

        // If no cookie exists, generate a random one (this will create a new session!)
        var generatedCookie = sails.config.session.key + '=' + uuid.v1();
        socket.handshake.headers.cookie = generatedCookie;
        sails.log.verbose('Could not fetch session, since connecting socket (', socket.id, ') has no cookie.');
        sails.log.verbose('Is this a cross-origin socket..?)');
        sails.log.verbose('Generated a one-time-use cookie:', generatedCookie);
        sails.log.verbose('This will result in an empty session, i.e. (req.session === {})');


        // Convert cookie into `sid` using session secret
        // Maintain sid in socket so that the session can be queried before processing each incoming message
        socket.handshake.cookie = cookie.parse(generatedCookie);
        // Parse and decrypt cookie and save it in the socket.handshake
        socket.handshake.sessionID = parseSignedCookie(socket.handshake.cookie[sails.config.session.key], sails.config.session.secret);

        // Generate and persist a new session in the store
        Session.generate(socket.handshake, function(err, sessionData) {
          if (err) return cb(err);
          sails.log.silly('socket.handshake.sessionID is now :: ', socket.handshake.sessionID);

          // Provide access to adapter-agnostic `.save()`
          return cb(null, new SocketIOSession({
            sid: sessionData.id,
            data: sessionData
          }));
        });
        return;
      }


      try {
        // Convert cookie into `sid` using session secret
        // Maintain sid in socket so that the session can be queried before processing each incoming message
        socket.handshake.cookie = cookie.parse(socket.handshake.headers.cookie);
        // Parse and decrypt cookie and save it in the socket.handshake
        socket.handshake.sessionID = parseSignedCookie(socket.handshake.cookie[sails.config.session.key], sails.config.session.secret);
      } catch (e) {
        sails.log.error('Could not load session for socket #' + socket.id);
        sails.log.error('The socket\'s cookie could not be parsed into a sessionID.');
        sails.log.error('Unless you\'re overriding the `authorization` function, make sure ' +
          'you pass in a valid `' + sails.config.session.key + '` cookie');
        sails.log.error('(or omit the cookie altogether to have a new session created and an ' +
          'encrypted cookie sent in the response header to your socket.io upgrade request)');
        return cb(e);
      }

      // If sid DOES exist, it's easy to look up in the socket
      var sid = socket.handshake.sessionID;

      // Cache the handshake in case it gets wiped out during the call to Session.get
      var handshake = socket.handshake;

      // Retrieve session data from store
      Session.get(sid, function(err, sessionData) {

        if (err) {
          sails.log.error('Error retrieving session from socket.');
          return cb(err);
        }

        // sid is not known-- the session secret probably changed
        // Or maybe server restarted and it was:
        // (a) using an auto-generated secret, or
        // (b) using the session memory store
        // and so it doesn't recognize the socket's session ID.
        else if (!sessionData) {
          sails.log.verbose('A socket (' + socket.id + ') is trying to connect with an invalid or expired session ID (' + sid + ').');
          sails.log.verbose('Regnerating empty session...');

          Session.generate(handshake, function(err, sessionData) {
            if (err) return cb(err);

            // Provide access to adapter-agnostic `.save()`
            return cb(null, new SocketIOSession({
              sid: sessionData.id,
              data: sessionData
            }));
          });
        }

        // Otherwise session exists and everything is ok.

        // Instantiate SocketIOSession (provides .save() method)
        // And extend it with session data
        else return cb(null, new SocketIOSession({
          data: sessionData,
          sid: sid
        }));
      });
    }
function createApp (argv, sequelize, config) {
  var app = express()

  // Session
  var sessionSettings = {
    secret: uuid.v1(),
    saveUninitialized: false,
    resave: false
  }
  sessionSettings.cookie = {
    secure: true
  }

  app.use(session(sessionSettings))
  app.use('/', WcMiddleware(corsSettings))

  app.use( bodyParser.json() )       // to support JSON-encoded bodies
  app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
  }))

  var config = require('../config/config')
  sequelize = wc_db.getConnection(config.db)

  debug(config)

  app.use(function(req,res, next) {
    res.locals.sequelize = sequelize
    res.locals.config = config
    next()
  })

  app.set('view engine', 'ejs')

  config.ui = config.ui || {}
  config.ui.tabs = [
    {"label" : "Home", "uri" : "/"},
    {"label" : "Balance", "uri" : "/balance"},
    {"label" : "Images", "uri" : "/random_rate"},
    {"label" : "Audio", "uri" : "/random_rate_audio"},
    {"label" : "Video", "uri" : "/random_rate_video"},
    {"label" : "Top", "uri" : "/top"},
    {"label" : "Tags", "uri" : "/tag"},
    {"label" : "Faucet", "uri" : "/faucet"},
    {"label" : "Deposit", "uri" : "/deposit"},
    {"label" : "Withdrawal", "uri" : "/withdrawal"}
  ]
  config.ui.name = "Testcoin"

  app.post('/addcredits', faucetpost)
  app.post('/addmedia', addMedia)
  app.get('/balance', balance)
  app.get('/clear', clear)
  app.get('/deposit', deposit)
  app.get('/faucet', faucet)
  app.get('/toledger', toledger)
  app.get('/random_rate', random_rate)
  app.get('/random_rate_audio', audio)
  app.get('/random_rate_video', video)
  app.all('/rate', rate)
  app.get('/sweep', sweep)
  app.all('/tag', tag)
  app.get('/top', top)
  app.get('/wallet/test', wallet)
  app.get('/withdrawal', withdrawal)
  app.post('/withdrawalrequest', withdrawalrequest)
  app.get('/', home)

  return app
}
Exemple #16
0
	storeSnapshot:function(snapshot,callback){
		snapshotsDB[this.aggreName][uuid.v1()] = snapshot;
		callback(null,snapshot);
	},
Exemple #17
0
module.exports.create = function (destinationDir, config, options) {
    if(!destinationDir) return Q.reject('No destination directory specified.');

    var projectPath = path.resolve(destinationDir);
    if (fs.existsSync(projectPath)) {
        return Q.reject(new CordovaError('Project directory already exists:\n\t' + projectPath));
    }

    // Set parameters/defaults for create
    var packageName = (config && config.packageName()) || 'Cordova.Example';
    var appName = (config && config.name()) || 'CordovaAppProj';
        // 64 symbols restriction goes from manifest schema definition
        // http://msdn.microsoft.com/en-us/library/windows/apps/br211415.aspx
    var safeAppName = appName.length <= 64 ? appName : appName.substr(0, 64);
    var templateOverrides = options.customTemplate;
    var guid = options.guid || uuid.v1();
    var root = path.join(__dirname, '..', '..');

    events.emit('log', 'Creating Cordova Windows Project:');
    events.emit('log', '\tPath: ' + path.relative(process.cwd(), projectPath));
    events.emit('log', '\tNamespace: ' + packageName);
    events.emit('log', '\tName: ' + appName);
    if (templateOverrides) {
        events.emit('log', '\tCustomTemplatePath: ' + templateOverrides);
    }

    // Copy the template source files to the new destination
    events.emit('verbose', 'Copying windows template project to ' + projectPath);
    shell.cp('-rf', path.join(root, 'template', '*'), projectPath);

    // Duplicate cordova.js to platform_www otherwise it will get removed by prepare
    shell.cp('-rf', path.join(root, 'template/www/cordova.js'), path.join(projectPath, 'platform_www'));
    // Duplicate splashscreen.css to platform_www otherwise it will get removed by prepare
    var cssDirectory = path.join(projectPath, 'platform_www', 'css');
    recursiveCreateDirectory(cssDirectory);
    shell.cp('-rf', path.join(root, 'template/www/css/splashscreen.css'), cssDirectory);

    // Copy cordova-js-src directory
    events.emit('verbose', 'Copying cordova-js sources to platform_www');
    shell.cp('-rf', path.join(root, 'cordova-js-src'), path.join(projectPath, 'platform_www'));

    // Copy our unique VERSION file, so peeps can tell what version this project was created from.
    shell.cp('-rf', path.join(root, 'VERSION'), projectPath);

    // copy node_modules to cordova directory
    events.emit('verbose', 'Copying node_modules to ' + projectPath);
    shell.cp('-r', path.join(root, 'node_modules'), path.join(projectPath, 'cordova'));

    // copy check_reqs module to cordova directory
    shell.cp('-rf', path.join(root, 'bin', 'check_reqs*'), path.join(projectPath, 'cordova'));
    shell.cp('-rf', path.join(root, 'bin', 'lib', 'check_reqs*'), path.join(projectPath, 'cordova', 'lib'));

    if (templateOverrides && fs.existsSync(templateOverrides)) {
        events.emit('verbose', 'Copying windows template overrides from ' + templateOverrides + ' to ' + projectPath);
        shell.cp('-rf', templateOverrides, projectPath);
    }

    // Copy base.js into the target project directory
    var destinationDirectory = path.join(projectPath, 'platform_www', 'WinJS', 'js');
    var destBaseJsPath = path.join(destinationDirectory, 'base.js');
    var srcBaseJsPath = path.join(root, 'node_modules', 'winjs', 'js', 'base.js');
    recursiveCreateDirectory(destinationDirectory);
    shell.cp('-f', srcBaseJsPath, destBaseJsPath);

    // replace specific values in manifests' templates
    events.emit('verbose', 'Updating manifest files with project configuration.');
    [ 'package.windows.appxmanifest', 'package.phone.appxmanifest',
      'package.windows10.appxmanifest' ]
    .forEach(function (item) {
        var manifest = AppxManifest.get(path.join(projectPath, item));
        if (manifest.hasPhoneIdentity) {
            manifest.getPhoneIdentity().setPhoneProductId(guid);
        }

        manifest.setPackageName(packageName)
            .setAppName(safeAppName)
            .write();
    });

    // Delete bld forder and bin folder
    ['bld', 'bin', '*.user', '*.suo', 'MyTemplate.vstemplate'].forEach(function (file) {
        shell.rm('-rf', path.join(projectPath, file));
    });

    events.emit('log', 'Windows project created with ' + pkg.name + '@' + pkg.version);
    return Q.resolve();
};
Exemple #18
0
	storeEvent:function(e,callback){

		eventsDB[this.aggreName][uuid.v1()] = e;
		callback(null);
	}
/**
* Append blob basics.
* @ignore
* 
* @param {config}               config                           The configuration which contains the connectionString.
* @param {errorOrResult}        callback                         The callback function.
*/
function basicStorageAppendBlobOperations(config, callback) {
  // Create a blob client for interacting with the blob service from connection string
  // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
  var blobService = storage.createBlobService(config.connectionString);

  var fileToUpload = "HelloAppend.dat";
  writeRandomFile(fileToUpload, 1024);
  var appendBlobContainerName = "demoappendblobcontainer-" + guid.v1();
  var appendBlobName = "demoappendblob-" + fileToUpload;
  
  console.log('Append Blob Sample');
  
  // Create a container for organizing blobs within the storage account.
  console.log('1. Creating Container');
  blobService.createContainerIfNotExists(appendBlobContainerName, function (error) {
    if (error) {
      callback(error);
    } else {
      // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate 
      // access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions 
      // to allow public access to blobs in this container. Uncomment the line below to use this approach. Then you can view the file 
      // using: https://[InsertYourStorageAccountNameHere].blob.core.windows.net/demoappendblobcontainer-[guid]/demopageblob-HelloAppend.dat
      
      // Upload a PageBlob to the newly created container
      console.log('2. Uploading AppendBlob');
      blobService.createAppendBlobFromLocalFile(appendBlobContainerName, appendBlobName, fileToUpload, function (error) {
        if (error) {
          callback(error);
        } else {
          // List all the blobs in the container
          console.log('3. List Blobs in Container');
          listBlobs(blobService, appendBlobContainerName, null, null, function (error, results) {
             if (error) {
              callback(error);
            } else {
              for (var i = 0; i < results.length; i++) {
                console.log(util.format('   - %s (type: %s)'), results[i].name, results[i].blobType);
              }
              
              // Download a blob to your file system
              console.log('4. Download Blob');
              var downloadedFileName = util.format('CopyOf%s', fileToUpload);
              blobService.getBlobToLocalFile(appendBlobContainerName, appendBlobName, downloadedFileName, function (error) {
                if (error) {
                  callback(error);
                } else {
                  fs.stat(downloadedFileName, function(error, stats) {
                    console.log('5. Append block to append blob');
                    blobService.appendBlockFromText(appendBlobContainerName, appendBlobName, 'text to be appended', { appendPosition: stats.size } /** Verify that the blob has NOT been written by another process */, function(error){
                      if (error) {
                        callback(error);
                      } else {
                        console.log('   Downloaded File Size: %s', stats.size);
                        try { fs.unlinkSync(downloadedFileName); } catch (e) { }
                        // Clean up after the demo 
                        console.log('6. Delete Append Blob');
                        blobService.deleteBlob(appendBlobContainerName, appendBlobName, function (error) {
                          if (error) {
                            callback(error);
                          } else {
                            // Delete the container
                            console.log('7. Delete Container');
                            blobService.deleteContainerIfExists(appendBlobContainerName, function (error) {
                              try { fs.unlinkSync(fileToUpload); } catch (e) { }
                              callback(error);
                            });
                          }
                        });
                      }
                    });
                  });
                }
              });
            }
          });
        }
      });
    }
  });
}
Exemple #20
0
// set up ======================================================================
// get all the tools we need
var fs = require('fs'); 
var express  = require('express');
var http = require('http')
var app      = express();
var request = require('request');

var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');

var uuid = require("node-uuid");

var myuuid = uuid.v1();


//me will eventually have a url and name field
global.me = { "m_count":0,"uuid": myuuid , "want":{} };
global.inbox = {"count":0, "messages":[]};
global.peers = {"count":0, "peers":[]};
global.requests = {"count":0, "contacts":[]};
global.heartbeats = {};
global.translation = '';

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({
    extended: true
function ReconnectServer()
{
    var reqIdX='';

    try
    {
        reqIdX = uuid.v1();
    }
    catch(ex)
    {

    }
    socket.on('connect', function(){
        logger.debug('[DVP-HTTPProgrammingAPIDEBUG] - [%s] - [SOCKET] -   Socket connected ',reqIdX);

        argsNum++;
    });
    socket.on('event', function(data){
        logger.debug('[DVP-HTTPProgrammingAPIDEBUG] - [%s] - [SOCKET] -   Socket event fired  %s',reqIdX,data);
        console.log(data);

    });
    socket.on('message', function(data) {


            logger.debug('[DVP-HTTPProgrammingAPIDEBUG] - [%s] - [SOCKET] -   Socket message received  %s', reqIdX, data);
        data.forEach(function (item) {
            logger.debug('[DVP-HTTPProgrammingAPIDEBUG] - [%s] - [SOCKET] -   Socket' +
            'message received data type of  %s', reqIdX, item);
            if (item.type == "message") {

                console.log(clc.green("Info: ") + clc.green(item.info));
                if(IsSessionFill)
                {
                    console.log("session already filled ",sessionID);
                    console.log(typeof (item.data));
                    console.log(item.data);
                }else
                {
                    console.log(typeof (item.data));
                    console.log(item.data);
                    sessionID=item.data.session;

                    IsSessionFill=true;
                }


            } else if (item.type == "warnning") {
                console.log(clc.yellow("Info: ") + clc.yellow(item.info));
                console.log(item.data);


            } else if (data.type == "session") {

                console.log("Session Hit");
                if(!sessionID)
                {
                    sessionID = item.ID;
                }

                console.log("SessionID recieved " + sessionID);

            } else if (item.type == "action") {

                console.log(clc.blue("Info: ") + clc.blue(item.info));
                console.log(item.data);
                InputSender(item.data);


            } else if (item.type == "error") {


                console.log(clc.red("Info: ") + clc.red(item.info));
                console.log(item.data);

                IsDone = true;

                socket.disconnect();


            }

        });



    });

    socket.on('disconnect', function(){

        logger.debug('[DVP-HTTPProgrammingAPIDEBUG] - [%s] - [SOCKET] -   Socket disconnected',reqIdX);
        IsDone=false;
        argsNum=0;
    });


}
	ns.on('connect', function (socket) {
		var clientId = uuid.v1();

		socket.on('desktop:connect', function () {
			console.log('Desktop client {%s} connected', clientId);

			desktops[clientId] = {
				socket: socket,
				pin: '1234',
				secured: true,
				devices: [ ]
			};

			socket.on('disconnect', function () {
				console.log('Desktop {%s} disconnected', clientId);

				var desktop = desktops[clientId];

				if (desktop !== undefined) {
					desktop.socket.disconnect();

					desktop.devices.forEach(function (deviceId) {
						if (devices[deviceId]) {
							//devices[deviceId].socket.emit('desktop:disconnected');
							devices[deviceId].socket.disconnect();
							devices[deviceId] = null;

							delete devices[deviceId];
						}
					});

					desktops[clientId] = null;

					delete desktops[clientId];
				}
			});

			socket.emit('connection:complete', { uuid: clientId });
		});

		socket.on('device:connect', function (data) {
			console.log('Device client {%s} connected', clientId);

			socket.on('disconnect', function () {
				console.log('Device {%s} disconnected', clientId);

				if (devices[clientId]) {
					console.log('Disconnecting device client {%s}', clientId);

					devices[clientId].socket.disconnect();

					var associatedDesktop = desktops[devices[clientId].desktopId];

					if (associatedDesktop) {
						console.log('Notifying desktop about device disconnect');

						associatedDesktop.socket.emit('device:disconnected', { uuid: clientId });

						var index = associatedDesktop.devices.indexOf(clientId);

						if (index > -1) {
							associatedDesktop.devices.splice(index, 1);
						}
					}

					devices[clientId] = null;

					delete devices[clientId];
				}
			});

			// check pin and uuid here
			if (!data || !data.uuid || !data.pin) {
				console.log('Invalid data parameters', data);
				return socket.disconnect();
			}

			if (!desktops[data.uuid]) {
				//return socket.emit('error', 'No such UUID');
				console.log('Invalid desktop uuid: {%s}', data.uuid);
				return socket.disconnect();
			}

			/*if (desktops[data.uuid].secured && desktops[data.uuid].pin !== data.pin) {
				//return socket.emit('error', 'Invalid PIN');
				console.log('Invalid PIN');
				return socket.disconnect();
			}*/

			devices[clientId] = {
				socket: socket,
				desktopId: data.uuid
			};

			desktops[data.uuid].devices.push(clientId);
			desktops[data.uuid].socket.emit('device:connectionComplete');

			socket.emit('connection:complete', { uuid: clientId });
		});

		socket.on('device:motion', function (data) {
			console.log('Received motion event from device {%s}', clientId);

			var desktopId = devices[clientId].desktopId;

			if (desktops[desktopId]) {
				desktops[desktopId].socket.emit('device:motion', data);
			}
		});

		socket.on('device:tap', function () {
			console.log('Received tap event from device {%s}', clientId);

			var desktopId = devices[clientId].desktopId;

			if (desktops[desktopId]) {
				desktops[desktopId].socket.emit('device:tap');
			}
		});
	});
Exemple #23
0
	socket.on('join', function(data) {
        var socketData = {};
        socketData.type = "player";
        socketData.uuid = uuid.v1();
			
		if (typeof(data) === 'undefined') {
            socket.disconnect();
			return;
        }
		
		if (data.roomType == 'pv') {
			if (data.roomId == null) {
				var newRoom = buildRoom(id, socket, null, data.nick, null, data.mode);
                newRoom.isPv = true;
                draftServer.addPrivateWaitingRoom(newRoom);
                socketData.roomId = id;
				id++;
                if (id > 9999) id = 0;
				socket.emit('join_success', { roomId : socketData.roomId });
			} else {
				if (!draftServer.hasPrivateWaitingRoom(data.roomId)) {
					socket.emit('join_fail', { error : 'noroom' });
					return;
				} else {
                    var privRoom = draftServer.getPrivateWaitingRoom(data.roomId);
					privRoom.player2 = socket;
					privRoom.player2nickname = data.nick;
                    privRoom.lastActivity = new Date();
					rooms[privRoom.id] = privRoom;
                    rooms[privRoom.id].decreaseTimer = getIntervalFunction(privRoom.id, 1000);
                    socketData.roomId = privRoom.id;
					draftServer.removePrivateWaitingRoom(privRoom.id);
					socket.emit('join_success');
					privRoom.player1.emit('player_join', {nick : data.nick, id: socketData.roomId, mode: privRoom.mode});
					socket.emit('player_join', {nick : privRoom.player1nickname, id: socketData.roomId, mode: privRoom.mode});
				}
			}
		} else {
			if (freeRoom[data.mode] == null) {
				freeRoom[data.mode] = buildRoom(id, socket, null, data.nick, null, data.mode);
                freeRoom[data.mode].isPv = false;
				id++;
                if (id > 9999) id = 0;
                socketData.roomId = freeRoom[data.mode].id;
				socket.emit('join_success');
			} else {
				freeRoom[data.mode].player2 = socket;
				freeRoom[data.mode].player2nickname = data.nick;
                freeRoom[data.mode].lastActivity = new Date();
                socketData.roomId = freeRoom[data.mode].id;

				rooms[socketData.roomId] = freeRoom[data.mode];
                rooms[socketData.roomId].decreaseTimer = getIntervalFunction(freeRoom[data.mode].id, 1000);
				freeRoom[data.mode] = null;
                payload = { nick : rooms[socketData.roomId].player1nickname, id: socketData.roomId, mode: data.mode };
                rooms[socketData.roomId].player1.emit('player_join', {nick : data.nick, id: socketData.roomId, mode: data.mode});
                socket.emit('join_success');
                socket.emit('player_join', payload );
			}
			
		}

        socket.socketData = socketData;
	});
Exemple #24
0
    .then(function(apiRes) {
        var items = apiRes.body.items;
        if (!items.length || !items[0].revisions) {
            throw new rbUtil.HTTPError({
                status: 404,
                body: {
                    type: 'not_found#page_revisions',
                    description: 'Page or revision not found.',
                    apiResponse: apiRes
                }
            });
        }
        // the response item
        var dataResp = apiRes.body.items[0];
        // the revision info
        var apiRev = dataResp.revisions[0];
        // are there any restrictions set?
        // FIXME: test for the precise attributes instead, this can easily
        // break if new keys are added.
        var restrictions = Object.keys(apiRev).filter(function(key) {
            return /hidden$/.test(key);
        });

        //get the redirect property, it's inclusion means true
        var redirect = dataResp.redirect !== undefined;

        return restbase.put({ // Save / update the revision entry
            uri: self.tableURI(rp.domain),
            body: {
                table: self.tableName,
                attributes: {
                    // FIXME: if a title has been given, check it
                    // matches the one returned by the MW API
                    // cf. https://phabricator.wikimedia.org/T87393
                    title: normalizeTitle(dataResp.title),
                    page_id: parseInt(dataResp.pageid),
                    rev: parseInt(apiRev.revid),
                    tid: uuid.v1(),
                    namespace: parseInt(dataResp.ns),
                    user_id: apiRev.userid,
                    user_text: apiRev.user,
                    timestamp: apiRev.timestamp,
                    comment: apiRev.comment,
                    tags: apiRev.tags,
                    restrictions: restrictions,
                    redirect: redirect
                }
            }
        })
        .then(function() {
            // if there are any restrictions imposed on this
            // revision, forbid its retrieval, cf.
            // https://phabricator.wikimedia.org/T76165#1030962
            if (restrictions && restrictions.length > 0) {
                throw new rbUtil.HTTPError({
                    status: 403,
                    body: {
                        type: 'access_denied#revision',
                        title: 'Access to resource denied',
                        description: 'Access is restricted for revision ' + apiRev.revid,
                        restrictions: restrictions
                    }
                });
            }
            // no restrictions, continue
            rp.revision = apiRev.revid + '';
            rp.title = dataResp.title;
            return self.getTitleRevision(restbase, req);
        });
    }).catch(function(e) {
Exemple #25
0
 },
 email_verified: {
   type: Boolean,
   default: false
 },
 hashed_password: {
   type: String,
   default: ''
 },
 salt: {
   type: String,
   default: ''
 },
 unique_code: {
   type: String,
   default: uuid.v1(),
   index: {
     unique: true
   }
 }, //used to forgot password for verify email address
 created: {
   type: Date,
   default: Date.now
 },
 
 phone: {
   type: Number,
   default: 0
 },
 phone_verified: {
   type: Boolean,
Exemple #26
0
 .post((req, res) => {
   req.body.id = uuid.v1();
   simpleDB[req.body.id] = req.body;
   res.json(req.body.id);
 })
Exemple #27
0
        $async.eachSeries(routines, function(requestedRoutine,callback) {
                if(typeof self.routineDefinitions[requestedRoutine.routine] !== 'undefined'){
                    try{
                        var routineId, routine;

                        //check if routine within already added consolidated routines
                        //console.log('initializeRoutines routine: '+requestedRoutine.routine);
                        if(typeof self.consolidateRoutines[requestedRoutine.routine] === 'undefined'){
                            routineId = $uuid.v1();
                            self.routines[routineId] = new self.routineDefinitions[requestedRoutine.routine](req, res);

                            if(self.routines[routineId].consolidate===true){
                                self.consolidateRoutines[requestedRoutine.routine] = routineId;
                            }

                            routine = self.routines[routineId];
                            for(var key in routine){
                                //console.log('initializeRoutines routine - process - '+key+': '+requestedRoutine.routine);
                                if(routine.hasOwnProperty(key)){
                                    switch(key){
                                        case 'onBeforeRaw':
                                            self.beforeRaw.push(routineId);
                                            break;
                                        case 'onRaw':
                                            self.raw.push(routineId);
                                            break;
                                        case 'onAfterRaw':
                                            self.afterRaw.push(routineId);
                                            break;
                                        case 'onBeforeActions':
                                            self.beforeActions.push(routineId);
                                            break;
                                        case 'onFieldAction':
                                            self.fieldAction.push(routineId);
                                            break;
                                        case 'onInitialActions':
                                            self.initialActions.push(routineId);
                                            break;
                                        case 'onActions':
                                            self.actions.push(routineId);
                                            break;
                                        case 'onAfterActions':
                                            self.afterActions.push(routineId);
                                            break;
                                        case 'onComplete':
                                            self.complete.push(routineId);
                                            break;
                                    }
                                }
                            }
                        }else{
                            routineId = self.consolidateRoutines[requestedRoutine.routine];
                            routine = self.routines[routineId];
                        }

                        routine.onInit(requestedRoutine.properties,column,self.core).then(function(){
                            callback();
                        });
                    }catch(e){
                        console.error(err);
                    }
                }else{
                    console.log('routine not found: '+requestedRoutine.routine);
                    callback();
                }
            },
Exemple #28
0
exports.add = function(req, res) {
    console.log('Start processing user.add!');
    console.log(JSON.stringify(req.headers));
    console.log(req.body, req.files);

    var id = uuid.v1();
    var user = {
        publicID: id,
        created: new Date(),
        signedin: false
    };

    if (req.body['user']) {
        requser = req.body['user'];
        user.name = requser['name'];
        user.password = requser['password'];

        UsersDB.insert(user, function(err, newDoc) {
            if (err === null) {
                res.format({
                    json: function() {
                        user.id = id;
                        res.status(201).json(user);
                    },
                    html: function() {
                        res.writeHead(303, {
                            Connection: 'close',
                            Location: '/users/' + id
                        });
                        res.end();
                    }
                })
            }
        });
    } else {
        console.log('Parsing with busboy...');
        var busboy = new Busboy({
            headers: req.headers
        });
        busboy.on('field', function(fieldname, value, fieldnameTruncated, valueTruncated) {
            console.log('Parsing form: ' + fieldname);
            if (fieldname === 'name') {
                user.name = value;
            } else if (fieldname === 'password') {
                user.password = value;
            } else {
                console.warn("Unknown field: " + fieldname);
            }
        });
        busboy.on('finish', function() {
            UsersDB.insert(user, function(err, newDoc) {
                if (err === null) {
                    res.format({
                        json: function() {
                            user.id = id;
                            res.status(201).json(user);
                        },
                        html: function() {
                            res.writeHead(303, {
                                Connection: 'close',
                                Location: '/users/' + id
                            });
                            res.end();
                        }
                    })
                }
            });
        });
        req.pipe(busboy);
    }

};
Exemple #29
0
 getUUID: function () {
   return uuid.v1();
 },
Exemple #30
0
 createEvent: function(event) {
   return _.assign({
     id: uuid.v1(),
     row: 0
   }, event)
 }