<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[robert onodi]]></title><description><![CDATA[Code life.]]></description><link>http://blog.robertonodi.me/</link><generator>Ghost 0.11</generator><lastBuildDate>Wed, 02 Aug 2023 22:49:23 GMT</lastBuildDate><atom:link href="http://blog.robertonodi.me/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Node.js authentication series: Passport local strategy using email and password.]]></title><description><![CDATA[<p>Before getting started, we can rule out that there are many authentication strategies that we can implement in our application. This depends on the use-case, we can have local authentication strategies, that use in most of the time the e-mail and password of the user. In other cases we can</p>]]></description><link>http://blog.robertonodi.me/node-authentication-series-email-and-password/</link><guid isPermaLink="false">d2e18a94-f5fa-4f91-9f3d-e947085ef506</guid><category><![CDATA[nodejs]]></category><category><![CDATA[mongodb]]></category><category><![CDATA[security]]></category><category><![CDATA[authenticaiton]]></category><category><![CDATA[passport]]></category><dc:creator><![CDATA[Robert Onodi]]></dc:creator><pubDate>Wed, 21 Oct 2015 15:31:24 GMT</pubDate><content:encoded><![CDATA[<p>Before getting started, we can rule out that there are many authentication strategies that we can implement in our application. This depends on the use-case, we can have local authentication strategies, that use in most of the time the e-mail and password of the user. In other cases we can use third party providers to authenticate our users, like login with Facebook buttons.</p>

<p><strong>The full app is available on <a href="https://github.com/robert52/express-starter">GitHub</a> the article will go through only important parts.</strong></p>

<p>I don't want to get into details for each method, we will discuss them at in the appropriate article. I would like to focus on the e-mail and password authentication. This is the most simple, yet in many cases wrongly implemented. Don't get me wrong probably this implementation will become obsolete someday, due to frequent changes and loop holes in security.</p>

<p>Many people don't take security seriously enough when building their application from scratch. Many companies have invested millions in proper security systems for their platforms. So this should raise an alarm when we talk about the security of our application.</p>

<h2 id="shortlistofbestpractices">Short list of best practices</h2>

<p>This is my list of best practices when dealing with e-mail and password authentication (suggestions are much appreciated):</p>

<ul>
<li>Do not store passwords in plain text in DB.</li>
<li>Generate password hash using a key stretching/derivation function.</li>
<li>Generate a random salt for each user.</li>
<li>Do not return password and salt in results from DB query.</li>
<li>Return password and salt only if explicitly requested.</li>
<li>Do not persist user sensitive data in sessions, like password and salt.</li>
<li>Try to be "slow" when computing hashes. </li>
<li>Throttle multiple requests for login request.</li>
<li>Throttle bad login attempts.</li>
<li>Consider using something like <a href="https://www.npmjs.com/package/helmet">helmet</a>.</li>
</ul>

<h2 id="abouttheauthenticationstrategy">About the authentication strategy</h2>

<p>Probably you all have seen a simple login form with e-mail and password fields. Almost every website or application has a similar login mechanism. The magic behind this is very simple, a user inserts the e-mail and password used on registration, which is matched against the persisted values in the database.</p>

<p>Obviously the implementation is a bit more complex. First, we don't store the user's  password in the database, instead we store a one way derived key (or hash) of the password in a stretched form. One way means that we cannot revert the process and get the initial password from the hash. Stretched means, that regardless of the user's password length we are always going to have a string of, let's say 40 characters.</p>

<p>Secondly, we want to have something unique for each user, to combine it with the user's password, so that we don't obtain the same hash for the same password for two users, we will call this the <em>salt</em>. Like we and salt and pepper in food, to get different flavors.</p>

<h2 id="applicationstructure">Application structure</h2>

<pre><code class="language-text">    app
    -- controllers
    ---- authenticaiton.js
    ---- account.js
    -- models
    ---- user.js
    -- helpers
    ---- password.js
    -- middlewares
    ---- authentication.js
    -- routes
    ---- authentication.js
    ---- account.js
    ---- main.js
    -- views
    ---- home.html
    ---- signin.html
    ---- signup.html
    ---- account.html
    config
    -- environments
    -- strategies
    ---- local.js
    -- index.js
    -- express.js
    -- passport.js
    -- mongoose.js
    -- routes.js
    -- models.js
    public
    tests
    -- unit
    -- integration
    package.json
    server.js
</code></pre>

<p>This is a conceptual application structure, I've used my <a href="https://github.com/robert52/express-starter">express starter</a> app. We'll only focus on some parts of the application and the rest of the application will be available on <a href="https://github.com/robert52/express-starter">GitHub</a>.</p>

<h2 id="hashingthepassword">Hashing the password</h2>

<p>We discussed that we cannot store the user's password in plain text in the database, because of security reasons. Beside that, we have to combine the password with a salt.</p>

<p>In order to hash the password we can use Node's built in <code>crypto</code> module. An alternative would be to use <a href="https://github.com/ncb000gt/node.bcrypt.js">bcrypt</a> for node.js, but I will let you figure out what suits your needs.</p>

<p>Generally people think that password hashing should be fast. But, its the other way around, when hashing password, I want it to be slow as possible, not slow as a lazy cat, but slow enough to be expensive to compute.</p>

<p>Why expensive to compute? Well because MD5 is super fast, too fast, you can generate all the possible passwords of 6 characters long in tens of seconds. You could use MD5 like this, M5(password + salt), but will not help you. With the proper hardware you could crack and try as many possibilities as you want.</p>

<h3 id="solution">Solution?</h3>

<p>Password stretching, and password stretching. Let's say that to generate our hash, it takes 200ms. To generate 10 passwords using the same algorithm would take 2000ms, which is 2 seconds, obviously we can use parallel computing to reduce the time needed, but this is not the case. Hence the computing necessity increases, and becomes time consuming.</p>

<p>Be advised that this can be a double edged blade, which means it can have side effects, if it takes too long to generate the hash. Try what best suits your needs, there is no one solution for all.</p>

<h2 id="implementingthepasswordhelper">Implementing the password helper</h2>

<p>We are going to use <code>crypto.pbkdf2()</code> method, which is a key derivation function. It uses an HMAC digest function, like SHA1, to create a derived key from the password using a salt in a number of iterations. </p>

<p>One important part is the number of iterations. The method uses iterations to create the derived key, which will make it expensive as computing time. If in time the hardware to compute hashes improves we can increase the number of iterations to generate the hash.</p>

<p>We are going to create a file called <code>app/helpers/password.js</code> and add the following content:</p>

<pre><code class="language-javascript">'use strict';

var LEN = 256;  
var SALT_LEN = 64;  
var ITERATIONS = 10000;  
var DIGEST = 'sha256';

var crypto = require('crypto');

module.exports.hash = hashPassword;

function hashPassword(password, salt, callback) {  
  var len = LEN / 2;

  if (3 === arguments.length) {
    crypto.pbkdf2(password, salt, ITERATIONS, len, DIGEST, function(err, derivedKey) {
      if (err) {
        return callback(err);
      }

      return callback(null, derivedKey.toString('hex'));
    });
  } else {
    callback = salt;
    crypto.randomBytes(SALT_LEN / 2, function(err, salt) {
      if (err) {
        return callback(err);
      }

      salt = salt.toString('hex');
      crypto.pbkdf2(password, salt, ITERATIONS, len, DIGEST, function(err, derivedKey) {
        if (err) {
          return callback(err);
        }

        callback(null, derivedKey.toString('hex'), salt);
      });
    });
  }
}
</code></pre>

<p>The <code>hashPassword()</code> function takes three argmunts: a password, an optional salt and a node.js style callback function. The salt is optional, because we can use this function in two scenarios. </p>

<p>First scenario is, when we want to hash the user's password for the first time, the salt does not exists in this case, and we will generate a random salt using <code>crypto.randomBytes()</code> method to generate a cryptographically strong, pseudo-random string.</p>

<p>The second scenarios will occur, when we already have a user in the database, and a salt exists for that user. In this scenario we are going to use the same salt to generate a hash for the input, to get the same hash as output.</p>

<h2 id="passportlocalauthenticationstrategy">Passport local authentication strategy</h2>

<p>We are going to use Passport.js to authenticate users. Passport has many strategies already implemented. First we are going to configure passport for our needs, create a file called <code>config/passport.js</code>, and add the following content:</p>

<pre><code class="language-javascript">'use strict';

var passport = require('passport');  
var mongoose = require('mongoose');  
var User = mongoose.model('User');

module.exports.init = function(app) {  
  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findById(id, done);
  });

  // load strategies
  require('./strategies/local')();
};
</code></pre>

<p>Secondly, we are going to implement the local strategy, by creating the following file, <code>config/strategies/local.js</code>:</p>

<pre><code class="language-javascript">'use strict';

var passport = require('passport');  
var LocalStrategy = require('passport-local').Strategy;  
var mongoose = require('mongoose');  
var User = mongoose.model('User');

module.exports = function() {  
  passport.use('local', new LocalStrategy({
      usernameField: 'email',
      passwordField: 'password'
    },
    function(email, password, done) {
      User.authenticate(email, password, function(err, user) {
        if (err) {
          return done(err);
        }

        if (!user) {
          return done(null, false, { message: 'Invalid email or password.' });
        }

        return done(null, user);
      });
    }
  ));
};
</code></pre>

<p>As you can see we are using a custom <code>.authenticate()</code> method from our mongoose <code>User</code> model. Do not worry, we will implement this method shortly. Passport let's us define a middleware to mount a strategy, we are going to call it 'local'. We created a new instance of Passport's local strategy and added our own callback when the strategy is called.</p>

<h2 id="mongooseusermodel">Mongoose User model</h2>

<p>We are using MongoDB to persist data, to ease things we are going to use <a href="http://blog.robertonodi.me/node-authentication-series-email-and-password/mongoosejs.com">mongoose</a> to define collections and communicate with Mongo. Create a file called <code>app/models/user.js</code>, and add the following lines of code:</p>

<pre><code class="language-javascript">'use strict';

var mongoose = require('mongoose');  
var passwordHelper = require('../helpers/password');  
var Schema = mongoose.Schema;  
var _ = require('lodash');

var UserSchema = new Schema({  
  email:  {
    type: String,
    required: true,
    unique: true
  },
  name: {
    type: String
  },
  password: {
    type: String,
    required: true,
    select: false
  },
  passwordSalt: {
    type: String,
    required: true,
    select: false
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

// compile User model
module.exports = mongoose.model('User', UserSchema);
</code></pre>

<p>The schema is fairly simple, so no explanation is required. One thing to note is that we added <code>{ select: false }</code> property to the <code>password</code> and <code>passwordSalt</code> fields. This will prevent them from showing in query results. </p>

<p>Next we are going to add the authentication method, by appending it to the model file after the <code>UserSchema</code>:</p>

<pre><code class="language-javascript">UserSchema.statics.authenticate = function(email, password, callback) {  
  this.findOne({ email: email }).select('+password +passwordSalt').exec(function(err, user) {
    if (err) {
      return callback(err, null);
    }

    // no user found just return the empty user
    if (!user) {
      return callback(err, user);
    }

    // verify the password with the existing hash from the user
    passwordHelper.verify(password, user.password, user.passwordSalt, function(err, result) {
      if (err) {
        return callback(err, null);
      }

      // if password does not match don't return user
      if (result === false) {
        return callback(err, null);
      }

      // remove password and salt from the result
      user.password = undefined;
      user.passwordSalt = undefined;
      // return user if everything is ok
      callback(err, user);
    });
  });
};
</code></pre>

<p>Before in the user schema we set the <code>password</code> and <code>passwordSalt</code> field to be hidden from the query output. But this time we explicitly request them, so that we can construct the hash using the persisted salt. Afterwards we check if the persisted password hash matched the one generated on the fly.</p>

<h3 id="authenticationcontroller">Authentication controller</h3>

<p>We are going to create a controller file called, <code>app/controllers/authentication.js</code>, which is going to consume the local strategy from passport. Add the following lines of code:</p>

<pre><code class="language-javascript">'use strict';

var passport = require('passport');

module.exports.signin = signinUser;

function signinUser(req, res, next) {  
  // add validation before calling the authenicate() method

  passport.authenticate('local', function(err, user, info) {
    if (err || !user) {
      return res.status(400).send(info);
    }

    req.logIn(user, function(err) {
      if (err) {
        return next(err);
      }

      // you can send a json response instead of redirecting the user
      //res.status(200).json(user);

      res.redirect('/');
    });
  })(req, res, next);
};
</code></pre>

<p>The controller exports a <code>.signin()</code> method that calls the local strategy, and redirects the user to the root path of the application, in case of a successful sign in. We could add validation before executing the local strategy, but we are going to keep it simple as possible for now.</p>

<h3 id="definingtheauthenticationroute">Defining the authentication route</h3>

<p>In order for everything to work we need to expose an endpoint, create a file called <code>app/routes/authentication.js</code>:</p>

<pre><code class="language-javascript">'use strict';

var express = require('express');  
var router = express.Router();  
var authCtrl = require('../controllers/authentication');

router.post('/signin', authCtrl.signin);

module.exports = router;
</code></pre>

<p>I'm using the <code>Router</code> class from Express to create a new route instance and later on mount it to the main express application. This way you can easily reuse defined routes and add prefixes as desired.</p>

<p>A simple way to mount the preceding route in your Express app, is with the following code:</p>

<pre><code class="language-javascript">app.use('/', require('./app/routes/authentication'));
</code></pre>

<h2 id="considerationsforsessionstorage">Considerations for session storage</h2>

<p>Passport requires to be initialized and also call the <code>passport.session()</code> method to persist sessions. This method requires the express session to be present. For the express session I use mainly two configurations, one for development and one for production.</p>

<p>The reason why I use two is because by default session information is stored in memory, you don't want this for a production environment, because of memory leaks. Another reason for this could be shared sessions states, when you run your node application in cluster mode.</p>

<p>A simple solution would be to use a persistent storage, because we already use MongoDB, we could simply use it for our session store. There is a very nice implementation called <a href="https://github.com/kcbanner/connect-mongo">connect-mongo</a>. An alternative solution would be to use <a href="https://github.com/tj/connect-redis">connect-redis</a> to store sessions in Redis.</p>

<p>Sample of implementaion found in <code>config/express.js</code>:</p>

<pre><code class="language-javascript">  var sessionOpts = {
    secret: config.session.secret,
    key: 'skey.sid',
    resave: false,
    saveUninitialized: false
  };

  switch(env) {
    case 'production':
      sessionOpts.store = new MongoStore({
        url: config.mongodb.uri
      });
    case 'staging':
    case 'test':
    case 'development':
    default:
      app.use(session(sessionOpts));
  }

  /**
   * Use passport session
   */
  app.use(passport.initialize());
  app.use(passport.session());
</code></pre>

<p>The full source code can be found on <a href="https://github.com/robert52/express-starter">here</a>.</p>

<p>Thanks for reading.</p>]]></content:encoded></item><item><title><![CDATA[Managing files with Node.js and MongoDB GridFS]]></title><description><![CDATA[<p>I've been working for a while with a pretty small team on a large(ish) project ( and of course in node.js) and being a personal project we used and tested a few "new and fancy" things.</p>

<p>The technology stack was pretty simple, Nginx serving us on the front of</p>]]></description><link>http://blog.robertonodi.me/managing-files-with-node-js-and-mongodb-gridfs/</link><guid isPermaLink="false">ed63d326-3cd0-4950-bb29-62c57f2e7013</guid><category><![CDATA[nodejs]]></category><category><![CDATA[mongodb]]></category><category><![CDATA[gridfs]]></category><dc:creator><![CDATA[Robert Onodi]]></dc:creator><pubDate>Tue, 17 Feb 2015 14:50:12 GMT</pubDate><content:encoded><![CDATA[<p>I've been working for a while with a pretty small team on a large(ish) project ( and of course in node.js) and being a personal project we used and tested a few "new and fancy" things.</p>

<p>The technology stack was pretty simple, Nginx serving us on the front of the battle field and passing some of the requests to the node.js web server. For data storage we went with MongoDB, we hopped on the NoSQL wagon and just rolled with it. And as in many other projects we needed some sort of file management. Did some research and had to give a try to gridfs. So we used gridfs to manage and serve images (and in the future also other files too).</p>

<h2 id="whatsthisgridfs">What’s this GridFS</h2>

<p>To be short MongoDB can be used as a file system. </p>

<h4 id="fromthemanual">From the manual:</h4>

<blockquote>
  <p><a href="http://docs.mongodb.org/manual/reference/glossary/#term-gridfs">GridFS</a> is a specification for storing and retrieving files that exceed the BSON-document size limit of 16MB. Instead of storing a file in a single document, GridFS divides a file into parts, or chunks, and stores each of those chunks as a separate document. </p>
</blockquote>

<p>Probably now you ask yourself, can I store files smaller than 16MB? the answer is <strong>YES</strong>. You can store any size of files, all the files are going to be chopped up in chunks. Should I use gridfs if my files are under 16MB? It depends on your use case, I would suggest you do to some tests and research before using it, maybe it's enough to use the simple BSON model. </p>

<p>So for using gridfs the advantages are numerous, for example you can take advantage of load balancing and data replication features over multiple machines for storing files. Also your files are splitted in small chunks. So for example getting a portion of your video file should be fairly easy to do.</p>

<p>GridFS by default uses two collections: fs.files and fs.chunks to store the file's metadata and the chunks. Each entry in the chunks collection represents a small piece from a file. A document from the chunks collection contains the following fields:</p>

<pre><code class="language-javascript">{
  "_id" : &lt;ObjectId&gt;,
  "files_id" : &lt;ObjectId&gt;,
  "n" : &lt;num&gt;,
  "data" : &lt;binary&gt;
}
</code></pre>

<p>The files collection holds the parent file for the chunks. Applications may add additional fields to the document. An example document from the files collection could look like this:</p>

<pre><code class="language-javascript">{
  "_id" : &lt;ObjectId&gt;,
  "length" : &lt;num&gt;,
  "chunkSize" : &lt;num&gt;,
  "uploadDate" : &lt;timestamp&gt;,
  "md5" : &lt;hash&gt;,

  "filename" : &lt;string&gt;,
  "contentType" : &lt;string&gt;,
  "aliases" : &lt;string array&gt;,
  "metadata" : &lt;dataObject&gt;,
}
</code></pre>

<h2 id="nodejsintegration">Node.js integration</h2>

<p>As express.js is so popular I’m going to jump right ahead and show you a simple integration. I’m going to use some existing code from one of my previous posts about <a href="http://blog.robertonodi.me/simple-image-upload-with-express/">file upload</a></p>

<p>I’m going to use <a href="http://mongoosejs.com/">mongoose</a> as it’s a fairly familiar module for mongodb. Create a separate file <code>mongoose.js</code> for your mongoose configuration and DB connection. Also I’m going to use <a href="https://github.com/aheckmann/gridfs-stream">gridfs-stream</a> to stream files to and from mongo. </p>

<pre><code class="language-javascript">var mongoose = require('mongoose');  
var Grid = require('gridfs-stream');

// @param {Object} app - express app instance
module.exports.init = function(app) {  
  var Schema;
  var conn;

  Grid.mongo = mongoose.mongo;
  conn = mongoose.createConnection(‘mongodb://localhost/aswome_db’);
  conn.once('open', function () {
    var gfs = Grid(conn.db);
    app.set('gridfs', gfs);
    // all set!
  });

  app.set('mongoose', mongoose);
  Schema = mongoose.Schema;
  // setup the schema for DB
  require('../db/schema')(Schema, app);
};
</code></pre>

<p>Now you can use it in a controller of your choice. Let’s create a file <code>file_controller.js</code> this will upload a file to the server write it into the database and delete the temporary file from the disk. The best part is that you can use streams to write into the database.</p>

<pre><code class="language-javascript">var shortId = require('shortid');

// @param {Object} app - express app instance
module.exports = function(app) {  
  // get the gridfs instance
  var gridfs = app.get('gridfs');

  return {
    upload: function(req, res, next) {
      var is;
      var os;
      //get the extenstion of the file
      var extension = req.files.file.path.split(/[. ]+/).pop();
      is = fs.createReadStream(req.files.file.path);
      os = gridfs.createWriteStream({ filename: shortId.generate()+'.'+extension });
      is.pipe(os);

      os.on('close', function (file) {
        //delete file from temp folder
        fs.unlink(req.files.file.path, function() {
          res.json(200, file);
        });
      });
    } 
  };
};
</code></pre>

<p>Reading a file from gridfs should be fairly easy. Just add a new method to your controller. </p>

<pre><code class="language-javascript">getFileById: function(req, res, next) {  
      var readstream = gridfs.createReadStream({
        _id: req.params.fileId
      });
      req.on('error', function(err) {
        res.send(500, err);
      });
      readstream.on('error', function (err) {
        res.send(500, err);
      });
      readstream.pipe(res);
}
</code></pre>

<p>The best thing is that you can store additional information with the files. So for example file access policies should be straightforward to implement, and could be stored with your files inside the files collection.</p>

<h2 id="isgridfsfastandreliableenoughforproduction">Is GridFS fast and reliable enough for production?</h2>

<p>I came across this <a href="http://stackoverflow.com/questions/3413115/is-gridfs-fast-and-reliable-enough-for-production">stackoverflow</a> question, you also may find it usefull. From my perspective it’s a simpler way to implement file management systems as it’s straightforward gives you a lot of flexibility and out of the box features. And for some reasons I can live with the <em>slowness</em> it adds.</p>

<p>There is also a nice <a href="https://www.coffeepowered.net/2010/02/17/serving-files-out-of-gridfs/">article</a> about the performance of GridFS.</p>

<h4 id="whatcanbeimproved">What can be improved?</h4>

<p>If you are using nginx to serve static files then it could be nice to integrate it directly with gridfs to server the images and add caching to them. And as my earlier research showed me this can be done pretty fast and simple, but this could be a topic of  another post.</p>

<p>Thanks for reading.</p>]]></content:encoded></item><item><title><![CDATA[Authentication vs Authorization]]></title><description><![CDATA[<p>What is authentication and authorization? Why is it important to understand where and how to use them? They are quite easy to confuse, the two are frequently used in discussions and are often bound to key parts of system. In reality there are two different concepts, that can live completly</p>]]></description><link>http://blog.robertonodi.me/authentication-vs-authorization/</link><guid isPermaLink="false">6146dd0b-5266-413d-8434-fcac8778be1c</guid><category><![CDATA[security]]></category><dc:creator><![CDATA[Robert Onodi]]></dc:creator><pubDate>Mon, 23 Jun 2014 14:26:00 GMT</pubDate><content:encoded><![CDATA[<p>What is authentication and authorization? Why is it important to understand where and how to use them? They are quite easy to confuse, the two are frequently used in discussions and are often bound to key parts of system. In reality there are two different concepts, that can live completly decoupled. Authentication is a process where an individual confirms his identity. Authorization is a process that defines access policy to a resource for an identity.</p>

<h4 id="authentication">Authentication</h4>

<p>Authentication verifies <strong>who you are</strong>. For example, in reality, if you buy a ticket to a concert and present it at the entrace you are <strong>authenticaticating</strong> that you are the person who bought that ticket. In computer science you can authenticate to a unix server using <strong>ssh</strong>.</p>

<h4 id="authorization">Authorization</h4>

<p>Authorization verifies <strong>what you can do</strong>. Let's say you are stopped by a police car when driving home from work. He will eventually ask for your drivers licence, this will permit him to check if you are <strong>authorized</strong> to drive that car. Getting back to our unix server example, you are allowed to login to your system via ssh client, but you are not authorized to create a folder in another user's home directory, if you don't have access for that.</p>

<h3 id="authenticationfactors">Authentication factors</h3>

<p>From a security point of view an authentication call be categorized in three ways, this can be based on what the person <strong>knows</strong>, something the person <strong>has</strong>, and finally something the person <strong>is</strong>. The three categories are:</p>

<h4 id="knowledgefactors">Knowledge factors</h4>

<p>A user has to know something in order to authenticate him e.g., a password, a pass phrase, a response to a security question. In your day to day routine you will frequently enter your <strong>email</strong> and <strong>password</strong> in somekind of form. Or if you are familiar with <em>GIT</em>, when you setup your <em>ssh key</em> it will ask you for a optional <em>pass phrase</em>.</p>

<h4 id="ownershipfactors">Ownership factors</h4>

<p>The user possess something to validate. If you ever worked in a coorporate environment you had your <em>ID card</em>, this has the purpose to confirm your identity. We can associate this in a web service with a <em>security token</em>, let's say you want to use an API from your favourite product, in many cases you may authenticate yourself using a <em>security token</em>, attachet to your requested URL or adding it to the request header (this may defer from provider to provider).</p>

<h4 id="inherencefactors">Inherence factors</h4>

<p>In general inherence refers to a biometric identifier, such as a fingerprint or a signature. This factor may satisfy a multi-factor authentication. You can read more about inherence <a href="http://en.wikipedia.org/wiki/Multi-factor_authentication#Biometrics">here</a>.</p>

<h3 id="combiningthefactorstwofactorauthentication">Combining the factors. Two-factor authentication.</h3>

<p>In order to achieve a multi-factor authentication approach, one must use two or more of the three independent authentication factors (describer above). To call it a successful authentication, each factor must be validated by the other party. In many cases when you want to login to your <em>homebanking</em> account you need to provide a password (knowledge factor) and security token from your digipass (ownership factor). Two factor authentication is not standardized, there are many process to choose from in order to achive it.</p>

<p>Thanks for reading, until the next time.</p>]]></content:encoded></item><item><title><![CDATA[Why add node modules to your versioning]]></title><description><![CDATA[<p>You are probably using <em>package.json</em> for your dependencies and running <code>npm install</code> on your production server. That’s a very convenient way to do it, <strong>STOP DOING IT NOW!</strong></p>

<h4 id="why">Why ?</h4>

<p>Here are a few things why you should reconsider your strategy:</p>

<ol>
<li><p>You’re relying on npm to serve you</p></li></ol>]]></description><link>http://blog.robertonodi.me/why-add-node-modules-to-your-versioning/</link><guid isPermaLink="false">d3e10f66-672b-405b-8e43-323844513e44</guid><dc:creator><![CDATA[Robert Onodi]]></dc:creator><pubDate>Mon, 31 Mar 2014 09:51:41 GMT</pubDate><content:encoded><![CDATA[<p>You are probably using <em>package.json</em> for your dependencies and running <code>npm install</code> on your production server. That’s a very convenient way to do it, <strong>STOP DOING IT NOW!</strong></p>

<h4 id="why">Why ?</h4>

<p>Here are a few things why you should reconsider your strategy:</p>

<ol>
<li><p>You’re relying on npm to serve you the same version of code compatible with your development including all sub-dependencies, because this might not be happening if the dependencies versions are not locked down, read more about <a href="https://www.npmjs.org/doc/shrinkwrap.html">npm shrinkwrap</a>.</p></li>
<li><p>You’re 100% sure that <em>npm</em>  or the <em>online repository</em> will always be available to server the exact packages you want, well it’s not always true.</p></li>
<li><p>You’re using it despite of npm <a href="https://www.npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git">advice</a> of not using it:</p>

<blockquote>
  <p>Use npm to manage dependencies in your dev environment, but not in your deployment scripts.</p>
</blockquote></li>
</ol>

<h4 id="yourcodeisyourresponsibility">Your code is your responsibility!</h4>

<p>Remember that your repository is the history of your development process, you should be able to roll-back to an older version if something goes wrong and everything should be working as before.</p>

<p><strong>Minimize risk.</strong> Bad things can happen, but you better be prepared, you should not make yourself vulnerable to every little problem, try to solve them from the beginning and rise your defence.</p>

<p>Thanks for reading.</p>

<p>You can leave comments on <a href="https://news.ycombinator.com/item?id=7500541">hackernews</a>.</p>]]></content:encoded></item><item><title><![CDATA[How to use Geospatial Indexing in MongoDB with Express and Mongoose]]></title><description><![CDATA[<p>For a couple of months I worked on a project that needed check-ins as a feature and location service. So I have decided to use as a database Mongo because of it’s very useful <a href="http://docs.mongodb.org/manual/core/geospatial-indexes/">geospatial indexing</a>. Foursquare is using MongoDB to power their location-based data queries, you can read</p>]]></description><link>http://blog.robertonodi.me/how-to-use-geospatial-indexing-in-mongodb-using-express-and-mongoose/</link><guid isPermaLink="false">b965afbd-dd7e-474c-b8b1-844ad4efd73d</guid><category><![CDATA[express]]></category><category><![CDATA[nodejs]]></category><category><![CDATA[mongodb]]></category><dc:creator><![CDATA[Robert Onodi]]></dc:creator><pubDate>Fri, 28 Mar 2014 23:57:57 GMT</pubDate><content:encoded><![CDATA[<p>For a couple of months I worked on a project that needed check-ins as a feature and location service. So I have decided to use as a database Mongo because of it’s very useful <a href="http://docs.mongodb.org/manual/core/geospatial-indexes/">geospatial indexing</a>. Foursquare is using MongoDB to power their location-based data queries, you can read more about his <a href="http://www.mongodb.com/customers/foursquare">here</a>.</p>

<p>The app is available on <a href="https://github.com/robert52/simple-geolocation">Github</a> - please take a look for the full codebase.</p>

<p>As for this tutorial I will keep the back-end logic simple and write an API in node.js using <a href="http://expressjs.com/">Express 3.0</a> to query the Mongo <em>location</em> collection. There are a few things to cover so before starting might get handy to read through the <a href="http://docs.mongodb.org/manual/core/geospatial-indexes/">official documentation</a></p>

<p>Let’s take a quick look on what we will cover:</p>

<ul>
<li>Setting up the API initial structure</li>
<li>Defining the Schema for our collections</li>
<li>Adding an index to our database</li>
<li>Getting location(s) using our API</li>
</ul>

<h3 id="setup">Setup</h3>

<p>You should add the following dependencies to your <em>package.json</em>:</p>

<pre><code class="language-javascript">"dependencies": {
    "express": "3.5.0",
    "mongoose": "3.8.8",
    "async": "0.2.10"
}
</code></pre>

<ul>
<li><a href="http://mongoosejs.com/">Mongoose</a> is an ORM wrapper for talking to MongoDB.</li>
<li><a href="http://expressjs.com/">Express</a> web application framework for node.</li>
<li><a href="https://github.com/caolan/async">async</a> is an utility module.</li>
</ul>

<h3 id="preparethemongoose">Prepare the Mongoose</h3>

<p>I am going to store location in Mongo, for this tutorial our location schema is going to be simple. This code assumes you have Mongo running on your local machine, with default settings.</p>

<p>Connecting to Mongo with Mongoose is simple:</p>

<pre><code class="language-javascript">mongoose.connect('mongodb://localhost/geospatial_db', function(err) {  
        if (err) throw err;

        // do something...
});
</code></pre>

<p>First we need to create a schema. The <a href="http://docs.mongodb.org/manual/core/geospatial-indexes/#store-location-data">docs</a> give us some examples on how to store geospatial data. We are going to use the legacy format for our example. It’s recommended to store the longitude and latitude in an array. The docs warn use about the order of the values, longitude comes first. </p>

<h5 id="notethatyoushouldalwaysstorelongitudefirst">Note that you should always store longitude first!</h5>

<pre><code class="language-javascript">var LocationSchema = new Schema({  
    name: String,
    loc: {
    type: [Number],  // [&lt;longitude&gt;, &lt;latitude&gt;]
    index: '2d'      // create the geospatial index
    }
});
</code></pre>

<p>Locations are going to have a <em>name</em> and a <em>loc</em> property. The <em>loc</em> is going to be an array holding the values for the coordinates [ <longitude> , <latitude> ]. Next we are going to tell Mongo to create a geospatial index for the <em>loc</em>. For this example we are going to use a <em>2d</em> index, you can read more about index <a href="http://docs.mongodb.org/manual/applications/geospatial-indexes/">here</a>.</latitude></longitude></p>

<p>Create a location object which we can use to query for specific locations.</p>

<pre><code class="language-javascript">// register the mongoose model
mongoose.model('Location', LocationSchema);  
</code></pre>

<h3 id="grabbinglocations">Grabbing locations</h3>

<p>First you can create a method in your controller that can look something like this:</p>

<pre><code class="language-javascript">findLocation: function(req, res, next) {  
    var limit = req.query.limit || 10;

    // get the max distance or set it to 8 kilometers
    var maxDistance = req.query.distance || 8;

    // we need to convert the distance to radians
    // the raduis of Earth is approximately 6371 kilometers
    maxDistance /= 6371;

    // get coordinates [ &lt;longitude&gt; , &lt;latitude&gt; ]
    var coords = [];
    coords[0] = req.query.longitude;
    coords[1] = req.query.latitude;

    // find a location
    Location.find({
      loc: {
        $near: coords,
        $maxDistance: maxDistance
      }
    }).limit(limit).exec(function(err, locations) {
      if (err) {
        return res.json(500, err);
      }

      res.json(200, locations);
    });
}
</code></pre>

<p>What this all means:</p>

<p>We are going to set a default 8 kilometers radius to search for locations within a set of coordinates:</p>

<pre><code>// get the max distance or set it to 8 kilometers
var maxDistance = req.query.distance || 8;  
</code></pre>

<p>One important thing to note here is that our query will use radians for distance, so we need to transform our distance to radians.</p>

<blockquote>
  <p>distance to radians: divide the distance by the radius of the sphere (e.g. the Earth) in the same units as the distance measurement. </p>
</blockquote>

<p>You should better follow up on this in the <a href="http://docs.mongodb.org/manual/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes/">docs</a>. </p>

<p>So to transform our distance to radians, we need to divide with 6371, the Earth’s radius approximately in kilometers. </p>

<pre><code class="language-javascript">// we need to convert the distance to radians
// the raduis of Earth is approximately 6371 kilometers
maxDistance /= 6371;  
</code></pre>

<p>Getting the coordinates in the right place:</p>

<pre><code class="language-javascript">// get coordinates [&lt;longitude&gt;,&lt;latitude&gt;]
var coords = [];  
coords[0] = req.query.longitude || 0;  
coords[1] = req.query.latitude || 0;  
</code></pre>

<h5 id="againnotethatlongitudecomesfirst">Again: Note that longitude comes first!</h5>

<p>Now for finding a location, we are going to use <a href="http://docs.mongodb.org/manual/reference/operator/query/near/#op._S_near">$near</a> operator, which is going to return the closest location first. This operator sorts the returned objects from the nearest to the farthest. In combination with the <a href="http://docs.mongodb.org/manual/reference/operator/query/maxDistance/#op._S_maxDistance">$maxDistance</a> operator, the results can be limited within a maximum distance to the specified point. Our query will look something like this:</p>

<pre><code class="language-javascript">// find a location
Location.find({  
    loc: {
        $near: coords,
        $maxDistance: maxDistance
    }
}).limit(limit).exec(function(err, locations) {
    if (err) {
        return res.json(500, err);
    }

    res.json(200, locations);
});
</code></pre>

<p>Having the full codebase we can test our small api by running this in the browser:</p>

<p><code>http://localhost:3000/api/locations?longitude=23.600800037384033&amp;latitude=46.76758746952729</code></p>

<p><em>* the sample application contains a mock data source which loads some locations to you database bye default *</em></p>

<pre><code class="language-javascript">[
  {
    "name": "Piaţa Cipariu",
    "loc": [
      23.600800037384033,
      46.76758746952729
    ],
    "_id": "5335e5a7c39d60402849e38f",
    "__v": 0
  },
  {
    "name": "Stația Piața Cipariu",
    "loc": [
      23.601171912820668,
      46.76771454984428
    ],
    "_id": "5335e5a7c39d60402849e3a5",
    "__v": 0
  },
  ...
]
</code></pre>

<p>As you can see the server will return a list of existing locations for the specified point within the default max distance.</p>

<p>Mongo also supports the <a href="http://docs.mongodb.org/manual/applications/geospatial-indexes/#geo-overview-location-data">GeoJSON</a> location data which is also a nice thing to check-out, there are a lots of interesting things related to the geospatial support, might be a good idea to read more about it in the docs.</p>

<p>Thank you for reading. Until next time.</p>

<p>You can leave comments on <a href="https://news.ycombinator.com/item?id=7490767">hackernews</a>.</p>]]></content:encoded></item><item><title><![CDATA[Simple image upload with Express]]></title><description><![CDATA[<p>Recently I have been working on a project that involved uploading images as a profile image for users. So I thought that I will share a simple way of uploading images in Express.</p>

<p>The app is available on <a href="http://github.com/robert52/simple-upload">Github</a> - please follow the setup instruction to run it on your</p>]]></description><link>http://blog.robertonodi.me/simple-image-upload-with-express/</link><guid isPermaLink="false">8ea44e44-17fb-42af-bd52-de84f5616a8e</guid><category><![CDATA[express]]></category><category><![CDATA[nodejs]]></category><dc:creator><![CDATA[Robert Onodi]]></dc:creator><pubDate>Tue, 18 Feb 2014 15:24:10 GMT</pubDate><content:encoded><![CDATA[<p>Recently I have been working on a project that involved uploading images as a profile image for users. So I thought that I will share a simple way of uploading images in Express.</p>

<p>The app is available on <a href="http://github.com/robert52/simple-upload">Github</a> - please follow the setup instruction to run it on your system.</p>

<p>Let’s take a simple flow for uploading an image for a user’s profile:</p>

<ul>
<li>User selects an image from the local disk.</li>
<li>Image gets uploaded through a form.</li>
<li>The application analyzes the data from the form and validates it. The image is uploaded to a temporary folder</li>
<li>We move the image from a temporary folder to a permanent path.</li>
<li>Respond with a success message to the user.</li>
</ul>

<p>First, let’s discuss the front-end component - for this I will use EJS to create my form’s markup. We will create a simple upload form, nothing fancy.</p>

<pre><code class="language-html">&lt;form action="/upload" method="post" enctype="multipart/form-data"&gt;  
  &lt;label for="file"&gt;Select your image:&lt;/label&gt;
  &lt;input type="file" name="file" id="file" /&gt;
  &lt;span class="hint"&gt;Supported files: jpg, jpeg, png.&lt;/span&gt;
  &lt;button type="submit"&gt;upload&lt;/button&gt;
&lt;/form&gt;
</code></pre>

<p>Now let’s get started with the application logic, we will start by defining our <a href="https://www.npmjs.org/doc/files/package.json.html">package.json</a> file. You should add to your package.json the following dependencies:</p>

<pre><code class="language-json">"dependencies": {
    "express": "latest",
    "ejs": "latest",
    "uid2": "latest",
    "mime": "latest"
}
</code></pre>

<p>We are using Express as our web application framework, the default view engine will be EJS, in other words we are going to use EJS to create our views. I have used <code>uid2</code> to create random names for the uploaded files. To determine the file type we can use <code>mime</code>, a practical little helper library.</p>

<p>Next step will be to create the <code>app.js</code> file, a starting point for the application, in larger applications a tend to name this file <code>server.js</code> and separate the app functionalities. I usually put my dependency and variable definition on top:</p>

<pre><code class="language-javascript">//Define variables &amp; dependencies

var express = require('express');  
var app = express();  
var server = require('http').createServer(app);  
var controllers = require('./controllers');
</code></pre>

<p>Next I will configure Express to meet my requirements, first I will set the default engine as stated before we are using ejs, so we are going to compile the <code>html</code> files. Second, we are going to define a default place for the views. And last, we are going to tell Express that our view files are going to have the default extension <code>.html</code>.</p>

<pre><code class="language-javascript">//Configure Express

app.engine('.html', require('ejs').__express);  
app.set('views', __dirname + '/views');  
// Without this you would need to
// supply the extension to res.render()
// ex: res.render('users.html')
app.set('view engine', 'html');  
</code></pre>

<p>We are going to set up a pretty default configuration:</p>

<pre><code class="language-javascript">app.configure(function() {  
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.static(__dirname + '/public'));
  app.use('/images', express.static(__dirname + '/writable'));
  app.use(app.router);
  app.engine('html', require('ejs').renderFile);
});
</code></pre>

<p>One thing to mention here is that I have used to static folders, one is <code>/public</code> where you can store your <code>css</code> and <code>js</code> files, and another one <code>/images</code> which will serve as our final path of the uploaded images. As you can see I am linking the <code>/images</code> route to a static folder <code>/writable</code>. </p>

<p>In order to access the upload functionality we are going to create two routes:</p>

<pre><code class="language-javascript">//Define routes
app.get('/', controllers.index);  
app.post('/upload', controllers.upload);  
</code></pre>

<p>The first <code>/</code> is going to serve us as our index route which will respond only to a <code>GET</code> request, and the second will be a <code>POST</code> on <code>/upload</code> path. As you can see I have separated the application logic into another file.</p>

<h4 id="finallywearegoingtostartourserver">Finally we are going to start our server:</h4>

<pre><code class="language-javascript">//Start the server
server.listen(3000, function() {  
  console.log("Express server up and running.");
});
</code></pre>

<p>The whole content of the file can be found <a href="https://raw.github.com/robert52/simple-upload/master/app.js">here</a>.</p>

<p>Initially I wanted to write all the application logic into a single file, but instead I separated it. I have created a new file called <code>controller.js</code>, first as usual I am going to declare my dependencies:</p>

<pre><code class="language-javascript">//Dependencies
var fs = require('fs');  
var path = require('path');  
var uid = require('uid2');  
var mime = require('mime');  
</code></pre>

<p>Also a good practice in order to define constants is to write them with capital letters to reflect their state so that their value’s should not be changed:</p>

<pre><code class="language-javascript">//Constants
var TARGET_PATH = path.resolve(__dirname, '../writable/');  
var IMAGE_TYPES = ['image/jpeg', 'image/png'];  
</code></pre>

<p>The <code>TARGET_PATH</code> is going to hold the final path of the uploaded images. In order to add some validation to file types, I have created an Array with accepted file types, in our case we are supporting only images.</p>

<p>To access the functionalities from <code>controller.js</code> file we need to export it, so that other files can use them. On easy way is to attach to the <code>modules.exports</code> ( or <code>exports</code> a shorter version ) what we want to export, in our case we are going to export a whole object:</p>

<pre><code class="language-javascript">module.exports = {  
  index: function(req, res, next) {
    // some logic
  },
  upload: function(req, res, next) {
    // some logic
  }
};
</code></pre>

<p>The <code>index</code> method is going to respond with the <code>index.html</code> file, so we are going to change it to something similar to this:</p>

<pre><code class="language-javascript">index: function(req, res, next) {  
    res.render('index');
},
</code></pre>

<p>Now the <code>upload</code> method is going to be a little bit more complex, as it has to deal with the upload functionality. You can access the uploaded files in the <code>req</code> variable’s <code>files</code> property in Express.</p>

<pre><code class="language-javascript">upload: function(req, res, next) {  
    var is;
    var os;
    var targetPath;
    var targetName;
    var tempPath = req.files.file.path;
    //get the mime type of the file
    var type = mime.lookup(req.files.file.path);
    //get the extension of the file
    var extension = req.files.file.path.split(/[. ]+/).pop();

    //check to see if we support the file type
    if (IMAGE_TYPES.indexOf(type) == -1) {
      return res.send(415, 'Supported image formats: jpeg, jpg, jpe, png.');
    }

    //create a new name for the image
    targetName = uid(22) + '.' + extension;

    //determine the new path to save the image
    targetPath = path.join(TARGET_PATH, targetName);

    //create a read stream in order to read the file
    is = fs.createReadStream(tempPath);

    //create a write stream in order to write the a new file
    os = fs.createWriteStream(targetPath);

    is.pipe(os);

    //handle error
    is.on('error', function() {
      if (err) {
        return res.send(500, 'Something went wrong');
      }
    });

    //if we are done moving the file
    is.on('end', function() {

      //delete file from temp folder
      fs.unlink(tempPath, function(err) {
        if (err) {
          return res.send(500, 'Something went wrong');
        }

        //send something nice to user
        res.render('image', {
          name: targetName,
          type: type,
          extension: extension
        });

      });//#end - unlink
    });//#end - on.end
  }
</code></pre>

<h5 id="breakingdownthemethod">Breaking down the method:</h5>

<p>We need to get the type of the file in order to validate it, we also need to store the extension of the file, later we will use the extension when renaming the file.</p>

<pre><code class="language-javascript">//get the mime type of the file
var type = mime.lookup(req.files.file.path);  
//get the extenstion of the file
var extension = req.files.file.path.split(/[. ]+/).pop();

//check to see if we support the file type
if (IMAGE_TYPES.indexOf(type) == -1) {  
    return res.send(415, 'Supported image formats: jpeg, jpg, jpe, png.');
}
</code></pre>

<p>Create a new name for the file, remember we added <code>uid2</code> to dependencies, we are going to use the <code>uid()</code> function in order to create a new random name for our file and concatenate the extracted extension.</p>

<pre><code class="language-javascript">targetName = uid(22) + '.' + extension;  
</code></pre>

<p>There are a few approaches regarding the moving of the file from a temporary place to a permanent place. One of the is to use <code>fs.rename()</code>:</p>

<pre><code class="language-javascript">fs.rename(tmpPath, targetPath, function(err) {  
    if (err) throw err;
    console.log('Done.');
});
</code></pre>

<p>This is pretty simple but, normally <code>/tmp</code> is in tmpfs, in ram and you cannot directly rename two files from different devices, it gives EXDEV error. Instead of using this method, I have created a read and write stream in order to accomplish the copy to a different path functionality.</p>

<pre><code class="language-javascript">//determine the new path to save the image
targetPath = path.join(TARGET_PATH, targetName);

//create a read stream in order to read the file
is = fs.createReadStream(tempPath);

//create a write stream in order to write the a new file
os = fs.createWriteStream(targetPath);

is.pipe(os);  
</code></pre>

<p>When the stream is done it will dispatch an <em>end</em> event to which we can attach our own callback:</p>

<pre><code class="language-javascript">//if we are done moving the file
is.on('end', function() {

    //delete file from temp folder
    fs.unlink(tempPath, function(err) {
        if (err) {
        return res.send(500, 'Something went wrong');
        }

        //send something nice to user
        res.render('image', {
            name: targetName,
            type: type,
            extension: extension
        });

    });//#end - unlink
});//#end - on.end
</code></pre>

<p>A good practice is to delete your temporary uploaded file after you moved it, for this we are going to use <code>fs.unlink()</code>, if everything goes well we can send a message to the user that the file has been successfully uploaded.</p>

<p>There is a lot more work that can be done here - especially when it comes to event handling and validation. A future improvement that I would like to add is to show a nice progress of the uploading to the user.</p>

<p>Thank you for reading. I hope you have found some useful information in this article. Until next time.</p>

<p>You can leave comments on <a href="https://news.ycombinator.com/item?id=7260867">hackernews</a>.</p>]]></content:encoded></item></channel></rss>