Nodejs

Let's build an API that will:

Getting Started

User Model

Connecting mongolab

mongodb://<dbuser>:<dbpassword>@ds037607.mongolab.com:37607/meanmachine

dbuser refers to the admin user created inside databse.

User Model

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');


// user schema

var UserSchema = new mongoose.Schema({
    name: String,
    username: {
        type: String,
        required: true,
        index: {
            unique: true
        }
    },

    password: {
        type: String,
        required: true,
        select: false // when we query the list of users , there will be no need to provide the password
    }
});

// Hash the password befoer the user is saved

UserSchema.pre('save', function(next){
    var user = this;

    // Hash the passworld only if the password has been changed or user is new
    if(!user.isModified('password')) return next();

    // generate the hash
    bcrypt.hash(user.password, null, null, function(err, hash) {
        if(err) return next(err);

        // change the password to the hash version
        user.password = hash;
        next();
    });
});

// Method to compare a given password with the database hash
UserSchema.methods.comparePassword = function(password) {
    var user = this;

    return bcrypt.compareSync(password, user.password);
}

// return the model
module.exports = mongoose.model('User', UserSchema);

Express Router and Routes

apiRouter.get('/', function(req, res){
    res.json( { message: "this is a json message"});
});

Middleware Uses Using middleware like this can be very powerful. We can do validations to make sure that everything coming from a request is safe and sound. We can throw errors here in case something in the request is wrong. We can do some extra logging for analytics or any statistics we’d like to keep. And the big usage is to authenticate the API calls by checking if a user has the correct token.

Authenticating Our Node.js API

  • A basic route(home page), which will be unauthenticated
  • Only API routes are authenticated
  • Route used to authenticate a user (login)
  • Pass in the token to have working auth

The main things we want to do here are:

  • Set up an authentication route tocheck a user and make sure that they have correct apssword

For handling authentication in Node, you won’t find a better package than PassportJS. This allows us to integrate authentication on our server with session based security, social based authentication, and what we’ve done in this chapter, JWT security.

There is even a package to handle checking the JWT and protecting routes called express-jwt. This package creates a middleware for us so that we don’t have to. It will allow us to set protected and unprotected routes.