Wednesday, October 29, 2014

Passport Authentication For Local Strategy - Node.js With Express Framework & Mongoose Database

Registration/Login is famous part in Web Based Application to enable User Privacy and track their records and Changes made.This is Easy in PHP -where i have written already Three post regarding login system for web Application.However in node.js it is quite easy for us to implement in faster manner.Passport.js comes here to help us in different strategy for implementing authentication system and integrate with Database and Session.

Passport.js module is well matured module which is used to Authenticate existing user and create new user for corresponding Strategy is nothing but simply just a way of authentication using username/password.

Reference : Download |  Demo 

Installation :

Before starting this module, i would like to go through some of My Last post on basic articles in node.js
C:\> npm install passport -g

This will install passport module globally in your local machine.however there are lot of strategy.we are going to use local-strategy.

App structure :

App structure is general where we would have a ,

1) models [directory]  - contains models => models.js(structure of Database) 
2) config[directory] - contains database connection url and passport.js Logic and functions.
3) view[directory] - our Front end to parse messages and display written with Templating Language (we have used EJS template)

here we are going to use express.js for our convenience to manage routes.


Lets start with Passport.js logic and Working.Generally this is a strategy authenticating a user with Username and Passwords.where they are stored in a database.after successful authentication we are setting sessions and redirecting the user to the Dashboard/profile.And we maintain sessions wherever we need to protect the access.

 var Local = require('passport-local').Strategy;

 var User = require('../models/model');
  module.exports = function(passport) {
    passport.serializeUser(function(user, done) {
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);

In the Above Code we have just initialize user from model schema of Database and passport as Local strategy.
I have used the module.exports to make seperate files in order to easily maintain the code and understanding.however it is connected to the server.js where we export the module.
serialize and deserialize is commonly used to deal with sessions handling.Stackoverflow answer is easy to understand,what does the abvove two function does.check it here

Creating and Naming a LocalStrategy:

 passport.use('signup', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true 
    function(req, email, password, done) {

        User.findOne({ '' :  email }, function(err, user) {
            if (err)
                return done(err);
            if (user) {
                return done(null, false, req.flash('signupError', 'Email is already taken.'));
            else {
       var newUser            = new User();
          = email;
                newUser.users.password = password; 
                    if (err)
                        throw err;
                    return done(null, newUser);

By the above functionality we are creating a localstrategy named signup for user registration.Generally for basic Signup we need username/Email with password is allowed in passport.js but we could inspect additional parameters by passing to callback the req object,so when you submit the form the additional params can be obtained from req object.check for additional form fields passing for passport.js.Since we explicitly make the passReqToCallback : true option we could pass the req object and inspect it inside the passport.js function.

And the next step is to query the Database for the existing user and return either done with error or success message to set the session.

we are querying the user document and getting out the object as user and if it exist we pass it as an error to flash a Error message.Else create a new Object with the Database schema and populate the Database accordingly and invoke done with user object to set the session.

Login Strategy :

here we are just naming and creating a simple login functionality to authenticate the user to use the service and set the session.

  passport.use('login', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true 
    function(req, email, password, done) { 
        User.findOne({ '' :  email }, function(err, user) {
            if (err)
                return done(err);
            if (!user)
                return done(null, false, req.flash('loginError', 'No user found.try Again'));               if(user.users.password != password)
               return done(null, false, req.flash('loginError', 'Password Error.try Again')); 
            return done(null, user); 



In the above Strategy we defined as login and passing our Username/Email and Password,btw we could overrride and passreqcall back to use additional form fields via req object as said before.However here query on mongoose matters here.
we are finding only one record containing email/username and getting out the object as user as return from database.However we need to check the object because in mongoose,if no record is returned by database then the object would be null, so that we verify with if clause statements and Authenticate the user and set the session or flash the error message.

user.js(models) : 

 var mongoose = require('mongoose');
 var user = mongoose.Schema({
    users            : {
        email        : String,
        password     : String
  module.exports = mongoose.model('User', user);

A simple Mongoose scheme for Database.have a look below.Local for email and password.verify to check the user via Email.We would cover this Email Verfication for User later.

Define Routes Using Express : 

now let us create some Express route to handle the request from user and serve the view part.I am writing the Routes directly in Server.js file , you can to export the module and write and load as separate passport.authenticate function is called to take care of the verification strategy.

res.render("index.ejs",{ message: req.flash('loginError') });
  });"/login",passport.authenticate('login', {
successRedirect : '/profile', 
failureRedirect : '/',
failureFlash : true 

res.render("signup.ejs",{ message: req.flash('signupError') });
  });"/signup",passport.authenticate('signup', {
successRedirect : '/profile', 
failureRedirect : '/signup',
failureFlash : true 
res.render("profile.ejs",{user : req.user });


  app.get('/logout',isLoggedIn, function(req, res) {


  function isLoggedIn(req, res, next) {

if (req.isAuthenticated())
return next();

   function isLoggedIns(req, res, next) {

if (req.isAuthenticated())
return next();

Few Words About EJS and Connect-Flash : 

Connect flash is used to flash the Error/Success message between the Authentication Passport and User.just the Error message (user defined) to the User Display.
Ejs Template is generally used for displaying our views as HTML and parsing the values as JSON and displaying it in front end dynamically.Learn more about EJS here.
Sample view index.ejs to parse the Error in Login :

      <div class="col-sm-12">
    <% if (message.length > 0) { %>
        <div class="alert alert-danger"><%= message %></div>
    <% } %>

Database Connection and Establishment:

Learn Here to create Database and set up Remote Connection in my past post.

module.exports = {
   'url' : 'mongodb://' 

About Security and Validation : 

I haven't verified any SQL injection for this Above Post,however you can use some packages to verify SQL injections and Execution commands that lets the server to open to Attack.Generally when you use eval() command,it gives hackers a well opportunity to Down the server and Application.i have escaped all the inputs provided by the user here.

Download the Code provided and Work it out.The given Code doesn't suits for production mode,here you can do lot of development works and make ready for production mode.Security is more concern for node.js because of exec() command.try to validate the user inputs and escape it and use it in your operations and perform Database operation.

Note For Downloading code :
If your downloading the code,

  • update the Credentials of Database in database.js file.
  • npm install the packages in your folder using package.json file given.
  • I have used Express session ,you can change the Session secret to implement in your projects.
  • to run execute node server.js command once you get into directory.

For Errors/Suggestions/Clarification/improvements/bugs drop mail to .or connect/chat with me Facebook/twitter/G+ hangouts for errors/help/Bugs.Share is care.Do comments.

Wednesday, October 08, 2014

Create HTTPS over Express Node.js Server On LocalHost With OpenSSL

https connection was thought as More secured but After Heart Bleed.Probably http is more secure :p .And Recently you would heard that Google Prefers HTTPS connection for SEO boost up and Higher ranks on Google Search.Many guys switched over Https connections.However This is a Simple security for transferring of data with encrypted format.However both the Side have Public and Private Key to ensure safe transfer of data and Disallowing Hackers/Anonymous peoples to Access your data.

Reference : Download Demo 

Installation :

Before starting this module, i would like to go through some of My Last post on basic articles in node.js
Note : Here we are simply Creating Self Signed Certificate to create HTTPS connection.So,Browsers may Warn hackers could steal/compromise your Data.This is for Development purpose.For production purpose Buy SSL certificate from Godaddy or leading SSL providers and Set up in your server.

Procedure to generate SSL certificate:

1) Generate RSA key with Openssl

C:\> openssl genrsa 1024 > /path/to/key.pem
2) Execute the Below Command to Generate certificate SSL with your self signature.with passphrase

C:\> openssl req -new -key /path/to/key.pem -out csr.pem
C:\> openssl x509 -req -days 365 -in key.pem -signkey /path/to/file.pem -out /path/to/ssl.crt

Take these two files to your server directory (node project directory)

Server.js :

Set up connection with including https module and make it to listen to a port namely 443 for Secured connections.
with the help of fs module just provide the path of key.pem and ssl.crt,passphrase(optional)or else you will be requested in commandline when starting your server each time.

var fs = require('fs');
var https = require('https');
var express = require('express');
var app = express();

    app.get('/', function (req, res) {

      key: fs.readFileSync('key.pem'),
      cert: fs.readFileSync('ssl.pem')
    }, app).listen(443);

Now issue npm server and start your you will be prompted for passphrase and if it is correct your server is ready to take off!

now point to the browser and https://localhost:443/ will show some Error/Security message.simply accept it and test your server.note this happens because of creating self signed certificate.while going into production mode buy a commercial and register with certified SSL verifier.

Have a view at my secured https connection in localhost! with some message.just click advanced and proceed you may get your normal route.

Create HTTPS over Express Node.js Server On LocalHost With OpenSSL

Note : Here we are simply Creating Self Signed Certificate to create HTTPS connection.So,Browsers may Warn hackers could steal/compromise your Data.This is for Development purpose.For production purpose Buy SSL certificate from Godaddy or leading SSL providers and Set up in your server.

For Errors/bugs/suggestions ideas just comment below or mail me or connect with me in Facebook/Google+/Twitter for more details.Share is care.

Wednesday, October 01, 2014

Working With - Create RESTful WebService Documentation Much Easier

Creating RESTful WebService Doesn't matters here.It matters about how you Provide Documentation for your Users/Developers to consume your web service in Rightful manner.You Need to Create Your Best out of for Documentation and clearly explain with some kind of Demo or Else Developers may seek through Stackoverflow and other forums to resolve their Problem and May hinder development of provides default doc for every API project you create.

Learn Here to create RESTful Webservice using Node.js/Mongoose dB

Working With - Create RESTful WebService Documentation Much Easier

Getting Started :  Visit Demo

Create an Account at website and create a Domain in your favour and you can find sample coding for notes API.
Either you can simply Edit that API content and implement yours or else just follow below ideas/procedures to build a Successful API Documentation.

Host and Version For API :



Name your API with Short Description:

 # Film API
 Film API Web Service Done with Help of Node.js as Backend.

Create a group :

 # Group film
 This Route film can get recent films and post new films

Categorize Your API Routes :

 ## film Routes [/films]

This will automatically create as /film below for each route you define.

Define Each of Your Route :

Here indentation is more important to overcome Symantic Errors.Either 8 Space bar or two Tab key press.

 ### List popular film [GET]
 + Response 200 (application/json)

          "id": 1, "title": "Neethane En Ponvasantham","genre":"love"
        }, {
          "id": 2, "title": "Moonu - 3 Film","genre":love"


Actually above Hash(#) must be thrice for defining completely your route with a Name of the route with REQUEST TYPE in SQUARE BRACKET.

Next Step define your Response with HTTP Status code and with return type of Response.
and With Enter key followed with Two tab spaces start typing example results from server

POST request : 

 ### Create a film [POST]
 + Request (application/json)

        { "title": "Yaan","genre":"action" }

 + Response 201 (application/json)

        { "id": 3, "title": "Yaan","genre":"action" }

Routes With Parameters :

Generally Parameters are passed via URL(Actually here URI) to make a GET/DELETE/PUT must clearly specify the Data type and purpose of Parameters to be passed and gain expected data.

Define A specific Routes to categorize since the same uri can be used for GET , POST , PUT.

 ## Film By ID [/film/{id}]
 A single Film Details is performed here

 + Parameters
     + id (required, number, `1`) ... Numeric `id` is unique value given to the Each Film.

As like before follow the indentation here too.Either 8 spaces/two tabs.

Define Each Route Below.

### Retrieve a film  [GET]
+ Response 200 (application/json)

    + Header

            X-My-Header: The Value

    + Body

            { "id": 2, "title": "Neethane En Ponvasantham","genre":"love" }

### Remove a film [DELETE]
+ Response 204

Thus We have Define a Successful doc for our Successful API with,Just preview with Apiary and make changes.

Have a look at my Simple Film API snapshot : visit for full Demo here

Working With - Create RESTful WebService Documentation Much Easier

The Above Screenshot of My API service for film API.

Caution : 
Don't Follow above Example codes,those are not formatted with tabs/Spaces
The Sample will be working only if you add correct host,and make sure of CORS policy of Ajax to run sample properly.Indentation for Response,Request is more important.Either(8 spaces/2 Tabs).

For bugs/comments/suggestions/errors comment below or mail me or connect with me in Facebook/Twitter.Feel free to comment below.Share is care.