Saturday, 11 March 2017

Meteor application MongoDB connection timed out

I'm running a Meteor application with Phusion Passenger as standalone meteor application with separate MongoDB. In Passenger.json I set MONGO_URL as:

"MONGO_URL":"mongodb://user:password@host:port/dbName”

I've created MongoDB in Mizrosoft Azure as NoSQL DocumentDB. When I start passenger to run the app it shows following error in the log file:

MongoError: connection 0 to HOST:10250 timed out
App 47594 stderr:     at Object.Future.wait (DIRECTORY/bundle/programs/server/node_modules/fibers/future.js:449:15)
App 47594 stderr:     at new MongoConnection (packages/mongo/mongo_driver.js:217:27)
App 47594 stderr:     at new MongoInternals.RemoteCollectionDriver (packages/mongo/remote_collection_driver.js:4:16)
App 47594 stderr:     at Object.<anonymous> (packages/mongo/remote_collection_driver.js:38:10)
App 47594 stderr:     at Object.defaultRemoteCollectionDriver (packages/underscore.js:784:19)
App 47594 stderr:     at new Mongo.Collection (packages/mongo/collection.js:99:40)
App 47594 stderr:     at AccountsServer.AccountsCommon (packages/accounts-base/accounts_common.js:23:18)
App 47594 stderr:     at new AccountsServer (packages/accounts-base/accounts_server.js:18:5)
App 47594 stderr:     at meteorInstall.node_modules.meteor.accounts-base.server_main.js (packages/accounts-base/server_main.js:9:12)
App 47594 stderr:     at fileEvaluate (packages/modules-runtime.js:197:9)
App 47594 stderr:     - - - - -
App 47594 stderr:     at Function.MongoError.create (DIRECTORY/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/error.js:29:11)
App 47594 stderr:     at Socket.<anonymous> (DIRECTORY/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connection.js:184:20)
App 47594 stderr:     at Socket.g (events.js:260:16)
App 47594 stderr:     at emitNone (events.js:67:13)
App 47594 stderr:     at Socket.emit (events.js:166:7)
App 47594 stderr:     at Socket._onTimeout (net.js:333:8)
App 47594 stderr:     at _runOnTimeout (timers.js:537:11)
App 47594 stderr:     at _makeTimerTimeout (timers.js:528:3)
App 47594 stderr:     at Timer.unrefTimeout (timers.js:597:5)
[ 2017-03-11 20:25:57.7781 47554/7f74a99c1700 age/Cor/App/Implementation.cpp:304 ]: Could not spawn process for application DIRECTORY/bundle: An error occurred while starting the web application. It exited before signalling successful startup back to Phusion Passenger.

Is there any problem with the way I defined MONGO_URL ?



via mostafiz

Error in Login Route

I have a system set up to let user's update their password via email. Once they have updated the password for some reason passport with not authenticate the new password. They can only login with the old old. However looking in the database the password has clearly been updated. I believe there is an error in my login functionality.

router.post('/login', function(req, res, next) {
      passport.authenticate('local', function(err, user, info) {
        if (err) return next(err)
        console.log('this' + err)
        if (!user) {
          return res.redirect('/login')
          console.log('there was no user')
        }
        req.logIn(user, function(err) {
            console.log('logging in')
          if (err) return next(err);
          return res.redirect('/');
        });
      })(req, res, next);
    });



via AndrewLeonardi

Small-Meduim size multiplayer game best implementation practice with node js

I am developing a multiplayer online game with node-js and socket.io and I am wondering if I am on the right path considering implementation.

the first approach I took was like this:

  1. one app class manages logic and socket events
  2. some small model class for structure and/or database queries

but it's got pretty messy around +2k lines and I am afraid I cant debug it anymore

the second approach i have in mind is :

  • one app class
  • one class to manage socket events
  • DataModel classes that will control the game logic

or another approach :

  • sharing socket events to classes and every class manages its own events

Which one should I choose? I think I need an expert opinion. thanks in advance.



via Ashkan Ghodrat

Node.js password hash and salt questions

I'm implementing an authenticated web app and I've some questions about username and password storage.

There is no possibility of implementing any TFA method and I need some expert advice about the way I'm saving in the database the hashed password and the salt.

These are my JS functions to generate the salt and the way I hash the password:

createSalt = function() {
var len = 30;
return crypto.randomBytes(Math.ceil(len * 3 / 4))
    .toString('base64') // convert to base64 format
    .slice(0, len) // return required number of characters
    .replace(/\+/g, '0') // replace '+' with '0'
    .replace(/\//g, '0'); // replace '/' with '0'
}

hashPassword = function(password, salt) {
    var hash = crypto.createHash('sha256');
    hash.update(password || "");
    hash.update(salt || "");
    return hash.digest('hex');
}

Any comment or improvement?

Thanks in advice.



via Pablo

SaaS: protecting data from other tenants and the service

Much has been written here and elsewhere about the subject, and all this has been great food for thought. However, have not found a question which deals with our scenario specifically or indeed provides clear answers so bear with me.

Background

  • Node.js backend with multiple frontends but with the overall SaaS theme.
  • Multiple users but in the low hundreds not millions.
  • Data being held is very sesitive and its security and integrity is both a legal/regulatory concern as well as one of our key selling points against the competition.
  • Every user's schema is quite a bit different so initial plan is to settle for a a NoSQL solution like MongoDB.

The Security Ladder

  1. Level one: soft protection from other users. The bare minimum in any multi-tenant app is to ensure no user can view another user's data. This should be accomplished by the app and its Data Access Layer. (But there's always the possibility of a bug creeping in here or there and successful malicious attacks that foil all protections carefully vowen into the DAL.)
  2. Level two: hard protection from other users. In database-per-tenant strategies we have slightly better walls between users (different db connections, etc) which decreases attack surface. In our particular case this also makes sense from a document integrity point of view (each user has quite a different schema).
  3. Level three: system intrusion. Protection from attackers who manage to gain physical access to database files. Most major DBaaS provide hardware-backed disk encryption and key rotation strategies for encryption at rest so even if someone gets the files they're of limited use.
  4. Level four: SaaS intrusion. Combines database-per-tenant with encryption-at-rest where only the user holds the decryption key to prevent SaaS personnel from reading data. May sound a little extreme but some data is too sensitive to risk a dbo being able to do a casual SELECT *. A user holding and providing decryption keys for on-the-fly data decryption also helps ensure no malicious client is able to escape their sandbox and do harm to other clients' data.

Road to Encryption Heaven

Azure Table Storage offers Transparent Data Encryption but entrusts access to encryption keys to everyone who has access to the Azure portal. Hence, only Level 3.

We came across MongoDB's Encrypted Storage Engine which sounded just like what we wanted: data encrypted at rest, decrypted data resides only in memory, keys could be user-managed at a KMIP-compliant third party. However, keys are per-mongod process and would require a new mongod instance per every user. Not ideal.

Another solution we considered was something like mongoose-encryption (roughly equivalent to column encryption in SQL Server) where sensitive collections have some or all columns en/decrypted. Sounds promising but our gut feeling says it would be better to have this functionality at a database engine level and not as a DAL plugin. Moreover, it 'only' offers column-level encryption; we'd prefer encryption where it's not visible what collections reside inside a database and how many rows they have.

What Else Is There?

Having spent two days googling and asking many of the major DBaaS for help I turn to SO.

  1. Do you think we are climbing the wrong mountain? In other words, perhaps it would be more beneficial to put all business logic in a client app and have it connect to a database directly rather than go through a server-side intermediary that has temporary access to sensitive data? (But then we're not a SaaS anymore and all our assets can be downloaded.)
  2. Do you know of any database engine or provider that does not assume the app and any database admin should have unfettered access to customer data? Witnessing encryption-at-rest only now becoming a feature are we still a few years away from enabling data access strategies (almost) taking apps out of the equation and allowing users to truly protect their data?
  3. For brevity I skip the entirety of key management logistics: how users should give the app temporary access to decryption keys held by a third party, how to deal with decryption over multiple requests, etc. I realise this is a can of worms in and of itself.
  4. Apologies for the long read!


via Dav

passport js local strategy not working

    var express = require('express');
    var passport = require('passport');
    var Strategy = require('passport-local').Strategy;
    var User = require('./routes/authentication.js');

    // Create a new Express application.
    var app = express();

    passport.use(new Strategy(
      function(username, password, cb) {
        User.findByUsername(username, function(err, user) {
         if (err) { return cb(err); }
         if (!user) { return cb(null, false); }
         if (user.password != password) { return cb(null, false); }
          return cb(null, user);
        });
      })
    );

    passport.serializeUser(function(user, cb) {
     cb(null, user.id);
    });

    passport.deserializeUser(function(id, cb) {
     User.findById(id, function (err, user) {
      if (err) { return cb(err); }
      cb(null, user);
     });
    });

    app.use(function(req, res, next) {
     res.header("Access-Control-Allow-Origin", "http://localhost:3000");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,      Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", true);
    next();
   });

app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

// Define routes.
app.get('/',
  function(req, res) {
    res.render('home', { user: req.user });
  });

app.get('/login',
  function(req, res){
    res.render('login');
  });

app.post('/login', 
  function(request, response, next) {
    console.log(request.session)
    passport.authenticate('local', 
    function(err, user, info) {
        if (!user){ response.send(info.message);}
        else {
          console.log(user);
          request.login(user, function(error) {
              if (error) return next(error);
              console.log("Request Login supossedly successful.");
              return response.send('Login successful');
          });
          //response.send('Login successful');
        }

    })(request, response, next);
  }
);

app.get('/logout',
  function(req, res){
    req.logout();
    res.redirect('/');
  });

app.get('/checklog', function (req, res, next) {
  if (req.isAuthenticated()) {
    next();
  } else {
    res.send('login');
  }
}, function (req, res, next) {
  res.send('profile');
})
app.listen(5000);

Any help will be appreciated. The above code is not setting the cookie and because of that the req.isAuthenticated() returns false everytime. There is no problem with findbyid and findbyusername methods. sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss



via Malik Lakhani

Inject argument into npm script command

I have an npm script that looks like:

"scripts": {
    "example": "webpack-dev-server --content-base examples/embeddable/"
},

I'd like to form the --content-base argument dynamically based on whatever's passed when calling the npm script, like:

npm run example -- embeddable

I know the -- syntax works for making args available to process.argv, but I'm not calling a Node script here so I'm not sure how to access them when forming the command. Does anyone else know of a good, cross-platform way to do this? (Must work on Windows.)



via Jura