Monday, October 31, 2016

Authenticate user using JWTs(json web token) in Node.js

What is a JSON Web Token (JWT)?

JWT, access token, token, OAuth token.. what does it all mean??

Properly known as “JSON Web Tokens”, JWTs are a fairly new player in the authentication space. Being the cool new thing, everyone is hip to start using them. But are you doing it securely? In this article we’ll discuss user authentication best practices in Node.js using JWTs, while showing you how to use the nJwt library for creating and verifying JWTs in your Node.js application.


JWT is used to secure your application by randomly created the access key and secret. So the user’s client will supply the token on every subsequent request to your server. This allows the server to authenticate the request, without having to ask for credentials a second time (until the token expires, that is).

How to Create a JWT :

There are a few steps that you’ll to follow in order to create a JWT for a user, we’ll walk through each of these steps in detail:
  1. Generate the secret signing key
  2. Authenticate the user
  3. Prepare the claims
  4. Generate the token
  5. Send the token to the client
1- Generate the Secret Signing Key

To be secure, we want to sign our tokens with a secret signing key. This key should be kept confidential and only accessible to your server. It should be highly random and not guessable. In our example, we’ll use the node-uuid library to create a random key for us:


var secretKey = uuid.v4();

2- Authenticate the User

Before we can make claims about the user, we need to know who the user is. So the user needs to make an initial authentication request, typically by logging into your system by presenting a username and password in a form. It could also mean that they’ve presented an API key and secret to your API service, using something like the Authorization: Basic scheme.

In either situation, your server should verity the user’s credentials. After you’ve done this and obtained the user data from your system, you want to create a JWT which will “remember” the information about the user. We’ll put this information into the claims of the token.

3- Prepare The Claims

Now that we have the user data, we want to build the “claims” of the JWT. That will look like this:


var claims = {
  sub: 'user9876',
  iss: 'https://mytrustyapp.com',
  permissions: 'upload-photos'
}

Let’s discuss each of these fields. Technically speaking, you can create a JWT without any claims. But these three fields are the most common:

sub – This is the “subject” of the token, the person whom it identifies. For this field you should use the opaque user ID from your user management system. Don’t use personally identifiable information, like an email address.

iss – This is the “issuer” field, and it lets other parties know who created this token. This could be the URL of your website, or something more specific if your website has multiple applications with different user databases.


permissions – Sometimes you’ll see this as scope if the JWT is being used as an OAuth Bearer Token. This is simply a comma-seperated list of things that the user has access to do.

4- Generate the Token

Now that we have the claims and the signing key, we can create our JWT object :


var jwt = nJwt.create(claims,secretKey);

This will be our internal representation of the token, before we send it to the user. Let’s take a look at what’s inside of it:

console.log(jwt)


{
  header: {
    typ: 'JWT',
    alg: 'HS256'
  },
  body: {
    jti: '3ee9364e-8aca-4e39-8ba2-74e654c7e083',
    iat: 1434695471,
    exp: 1434699071,
    sub: 'user9876',
    iss: 'https://mytrustyapp.com',
    permissions: 'upload-photos'
  }
}

You’ll see the claims that you specified earlier, and many other properties. These are the secure defaults that our library is setting for you, let’s visit each one in detail:

alg – This declares how we’ve signed our token, in this case using the Hmac algorithm with a strength of 256 bits. If you want more security, you can bump this up to HS512

exp – This is the time that the token will expire, as a unix timestamp offset in seconds. By default our library sets this to 1 hour in the future. If you need to change this value, call jwt.setExpiration() and pass a Date object that represents the desired expiration time.

iat – This is the time that the token was created, as a unix timestamp offset in seconds.


jti – This is simply a random value, that is created for every JWT. We provide this in case you want to create a database of tokens that were issued. You may do this if you want to implement a token blacklist for tokens that you know have been compromised (i.e. a user tells you their account has been hacked into).

5- Send the Token to the Client

Now that we have the JWT object, we can “compact” it to get the actual token, which will be a Base64 URL-Safe string that can be passed down to the client.

Simply call compact, and then take a look at the result:

var token = jwt.compact();


console.log(token);

What you see will look like this:


eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyYWIzOWRhYS03ZGJhLTQxYTAtODhiYS00NGE2YmIyYjk3YWMiLCJpYXQiOjE0MzQ2OTY4MDEsImV4cCI6MTQzNDcwMDQwMX0.qRe18XcmNXB2Ily-U9dwF_8j9DuZOi35HJGppK4lpBw


This is the compact JWT, it’s a three-part string (separated by periods). It contains the encoded header, body, and signature.

How you send the token to the client will depend on the type of application you are working with. The most common use case is a login form on a traditional website. In that situation you will store the cookie in an HttpOnly cookie, so you can simply set the cookie on the POST response.

For example, if you’re using the cookies library for Express:

res.cookie('access_token',token,{httpOnly: true,secure: true   // for your production environment});
res.cookie('secret',secretKey,{httpOnly: true,secure: true    // for your production environment});
  

Once the client has the token, it can use it for authentication. For example, if you’re building a single-page-app, the app will be making XHR requests of your server. When it does so, it will supply the cookie for authentication.


How to Verify JWTs :

When a client has a token it will use it to authenticate the user. The token can be sent to your server in a cookie or an HTTP header, such as the Authorization: Bearer header. 


Suppose you are sending the token using cookie so every time when you made a http request from client you have to send it in the header. If you are using angular js for handle the http request in client side then you don't need to do much just passing a httpProvider you can do it easily like below :


YourAppName.config(function($routeProvider,RestangularProvider,$locationProvider,$httpProvider){

$httpProvider.defaults.withCredentials = true;

});


Once you set up the $httpProvider.defaults.withCredential to true then in every client http request you seen the cookie is also send like below screen shot -



Now you need to authenticate the token that comes in the http request from client in node js like below :


app.use(function(req, res, next) {
 var token = req.cookies.access_token;
 var secretKey = req.cookies.secret;
 nJwt.verify(token, secretKey, function(err,token){
   if(err){
  res.status(500).send({error: "You have not rights to enter in this restricted area."});
  return false;
   }else{
  next();
   }
 });

});

In the above code i just verify that the token is valid or not if not then i simple return a 500 error code with the message "You have not rights to enter in this restricted area.". Thats It !! 
In my next post you will see how to handle error in client side in angular js.

Thank you for reading this article. If you are facing any challenges while using this so please leave a question in the comment box i will reply you back as soon as possible.

Chears 
Happy Coding :)

Sunday, October 30, 2016

Transfer file from local to server using pscp:

If you don't have access of the your server from ftp then pscp is the better way to transfer files from your local machine to server. Before going to use pscp command you need to download pscp from this link Click Here .After finish the download you need to install it and save it ppk file anywhere on your computer system. In my case i saved my ppk file on my desktop with the name "fp_app_famcom.ppk" and i want to transter my app.js file from my Desktop to "/var/www/html/app/client/app/sample" directory on server. So below is the command - 

Below is my files location:




Command Syntax :

pscp [options] sourcelocation user@host:targetlocation

Below is the example:


pscp -P 2222 -i fp_app_famcom.ppk app.js famcom@52.212.167.25:/var/www/html/app/client/app/sample


Steps :

1- Open the terminal by pressing Window+R key from keyboard and type cmd and press enter



2- Go to file where you saved your ppk file like below. In my case i saved it on desktop




3- Copy and paste the above command. Don't forgot to change the of ppk file name, sourcelocation, targetlocation and host name with your and press enter




If you like this post or having problem while using don't forgot to leave a comment.

Chears :)
Happy Coding..

Monday, October 24, 2016

Deteact internet explorer(IE) browser and its version in angular js

I need to deteact if my website user are using internet explorer browser and its version is less than 10 then i need to a message to my site visitors that "You are using unsupported browser version and the site may not function correctly" like below screen shot in angular js :





Below is my code that i write in my main file app.js :

var app = angular.module('clientApp', ['ngRoute', 'ngCookies']).run(function($rootScope,Restangular) {

var isIE = false || !!document.documentMode;

if(isIE && document.documentMode<10){
    $rootScope.iemsg = 'You are on an unsupported browser version and the site may not function correctly. Our site works best on IE10/FF/Safari/Chrome";
}

});


Below is my html code to display warning message using bootstrap:

<div class="alert alert-error" ng-if="iemsg"><i class="btn-icon-only icon-warning-sign"></i>{{iemsg}}</div>



Don't forgot to leave a comment if you like this post or having any trouble while using this code.

Chears :)
Happy Coding

Friday, October 21, 2016

Write data in existing excel using node js

Today i finally solve a big problem in my current node js project. Actually i have a requirement to write data in existing excel document. I already have an excel so i just need to open it and write some data and then save it. But unfortunately i unable to find a way to do this from a long time. After googling a lot i found a node module "xlsx-populate". Its fulfill my requirement. You can check the more detail about it from git hub link https://github.com/dtjohnson/xlsx-populate

Below is my server code of nodeJS  :


app.post('/writeEmployeeDataExcel',function(req,res){
 if(req.body.length>0){
  var data = req.body;
  var filename = "alkalmazottak.xlsx"; /**This is my new file name**/
  var newfilelocation = "../client/app/downloads/"+filename; /**This is new location of file**/
  var readexistingfile = "../client/app/downloads/employeeTemp.xlsx";/**This is existing doc that i want to read**/
  var workbook = Workbook.fromFile(readexistingfile, function (err, workbook){
   if (err) return res.status(500).send(err);
   var sheet = workbook.getSheet(0);
   var i=0;
   for (var rowNum = 2; rowNum < parseInt(data.length)+2; rowNum++) {
    var row = sheet.getRow(rowNum);
    var title = (data[i]['title']!='') ? data[i]['title'] : ''; 
    var lastname = (data[i]['last_name']!='') ? data[i]['last_name'] : '';
    var firstname = (data[i]['first_name']!='') ? data[i]['first_name'] : '';
    var email = (data[i]['email']!='') ? data[i]['email'] : '';
    for (var colNum = 2; colNum < 6; colNum++) {
     var cell = row.getCell(colNum);
     (colNum==2) ? cell.setValue(title) : '';
     (colNum==3) ? cell.setValue(lastname) : '';
     (colNum==4) ? cell.setValue(firstname) : '';
     (colNum==5) ? cell.setValue(email) : '';
    }
    i++;
   }
   workbook.toFileSync(newfilelocation);
   res.status(200).send({'name':filename});
   fs.exists("../client/app/downloads/"+filename, function(exists) {
    if (exists) {
     fs.unlink(newfilelocation);
    }
    workbook.toFileSync(newfilelocation);
    res.status(200).send({'name':filename});
    
   });
   
  });
 }
});


Preview :






Chears :)
Happy coding


Thursday, October 20, 2016

Password Match form validation in AngularJS

I am stuck in a form validation to change password where i need to take a specific length of password (like combination of special characters, alphabets and numbers) from user and confirm it by re-enter password. Actually i am using the ng-pattern property of angular js to match the password of both input boxes but the problem is ng-pattern is only match if your are passing simple string. It don't work to match the string with the special charecters.
See example-

Not Working :

<input type="password" name="password" class="span4" ng-model="user.password" ng-pattern="/^(?=(?:[^A-Z]*[A-Z]){2})(?=[^!@#$&*\%\^\)\(]*[!@#$&*\%\^\)\(])(?=(?:[^0-9]*[0-9]){2}).{8,}$/">
<input type="password" name="password2" class="span4" ng-model="user.password2" ng-pattern="user.password">

Working :

<input type="password" id="password" name="password" ng-model="user.password" ng-pattern="/^(?=(?:[^A-Z]*[A-Z]){2})(?=[^!@#$&*\%\^\)\(]*[!@#$&*\%\^\)\(])(?=(?:[^0-9]*[0-9]){2}).{8,}$/">
<input type="password" name="password2" class="span4" ng-model="user.password2" pw-check="password">


So to match the password of both text boxes input i created a simple directive (pwCheck) below is my compleate code :

Below is my directive :


.directive('pwCheck', [function () {
 return {
   require: 'ngModel',
   link: function (scope, elem, attrs, ctrl) {
  var firstPassword = '#' + attrs.pwCheck;
  elem.add(firstPassword).on('keyup', function () {
    scope.$apply(function () {
   var v = elem.val()===$(firstPassword).val();
   ctrl.$setValidity('pwmatch', v);
    });
  });
   }
 }
}]);


Below is my html code :

<form name="registerForm" id="registerForm" ng-submit="editAccountPassword(user, registerForm)" class="form-horizontal" novalidate>
 <div class="modal-body">
  <div class="col-md-12">
  <span class="alert alert-danger ng-cloak" ng-show="registerForm.password2.$error.pwmatch && !registerForm.password.$error.pattern">Passwords should match !!</span>
  </div>
  <div class="col-md-12">
  <span class="alert alert-danger ng-cloak" ng-show="registerForm.password.$error.pattern">Password should be minimum 8 character long and it should contain 2 upper case letters, 1 special character, 2 digits & 1 lower case letter</span>
  </div>
  
  <div class="widget-content">  
   <div class="control-group">           
    <label for="password" class="col-md-4 col-sm-4 col-xs-12 field-name text-padding">New Password</label>
    <div class="col-md-8 col-sm-8 col-xs-12">
     <input type="password" id="password" name="password" class="span4" ng-model="user.password" required="" ng-pattern="/^(?=(?:[^A-Z]*[A-Z]){2})(?=[^!@#$&*\)\(]*[!@#$&*\)\(])(?=(?:[^0-9]*[0-9]){2}).{8,}$/">
    </div>   
   </div>
   
   <div class="control-group" ng-class="{'has-error': registerForm.password2.$invalid && registerForm.password2.$dirty}">           
    <label for="password" class="col-md-4 col-sm-4 col-xs-12 field-name text-padding">{{'Retype New Password' | translate}}</label>
    <div class="col-md-8 col-sm-8 col-xs-12">
     <input type="password" name="password2" class="span4" ng-model="user.password2"  required="" pw-check="password">
      </div>
    </div>   
   </div>
  </div>
 </div>
</form>

Preview :






Chears 
Happy Coding :)


Friday, September 23, 2016

Export and Import database in mongo db

Exporting from MongoDB :

To export the database, simply tell mongodump which database (or collection) you want to export, and where to export it to. Mine was the fairquid database, so my command looks like this:

mongodump -d fairquid -o fairquidbackup

This dumps the fairquid database into the fairquidbackup directory. Take a look at what we have in that directory now:

fairquid
├── users.metadata.json
└── users.bson
└── products.metadata.json
└── products.bson
└── companies.metadata.json
└── companies.bson
└── system.indexes.bson

0 directories, 2 files

Some of the collection in my fairquid database are users, products, companies etc, however you'll see a .bson and .json file for each collection in your database, plus the system indexes collection. It is up to you whether you want to take individual collections, or a whole database, but bear in mind that your choice will dictate whether you get information about indexes etc when you import the data elsewhere.

Importing to MongoDB :

To import, simply use the mongorestore command, which accepts either a single .bson file representing a collection, or a directory containing multiple files. Here's my example:

mongorestore -d fairquid /path/to/fairquid

You can specify any database name and path to files you like, so for taking backups or restoring additional copies of a database, this can be really handy. The mongo commands are well-documented and I found them easy to work with.
Hopefully this helps you work with them too!



Please don't forgot to leave a comment.

Chears :)
Happy Coding

Sunday, August 21, 2016

How to detect “no internet connection” in AngularJS

Today i need to show some message when internet connection lost. So I define this interceptor in httpProvider in my app.js file, so its return an error when a call does not happen successfully due to internet connection lost. This Interceptor return status= "-1" when ajax call is failed. So i set a variable online= true here and in my html i display a message if online=true. See below my html code as well


angular.module('YourAppName', []).config([
  '$httpProvider',
  function($httpProvider){
    $httpProvider.interceptors.push([
      '$q','$rootScope',
      function($q,$rootScope) {
        return {
            responseError: function(res){
                //Angular returns "success" by default, but we will call "error" if data were not obtained.
                if(res.data == null && res.status === -1 && res.statusText === ""){
      $rootScope.online = true;
                    return $q.reject(res) //callback error()
                }      
                return res //return default success()
            }
        };
      }
    ]);
  }
]);


Now i need to show some message when $rootScope.online = true;
Below i check that online variable is true then show a message "Your have lost your internet connection. Check your internet connection and reload your page again." other wise not.



<!--Below message is showing when internet connection is lost. --> 
<div class="alert alert-error" ng-if="online"><i class="btn-icon-only icon-warning-sign"></i>
 Your have lost your internet connection. Check your internet connection and reload your page again.<button ng-click="reloadRoute()"><i class="icon-refresh"></i> Reload</button>
</div>


If you see my above html there i also add a reload button to reload the page to do this i create a function and i call this on click of reload button Below is my function :


// This function Is use to reload the active page.
$rootScope.reloadRoute = function() {
   $route.reload();
}

Now in the last step you need to hide the above message automatically when internet connection is coming again to do this i just put $rootScope.online = false; when view content loaded like below :


// To set the view online message false.
$rootScope.$on('$viewContentLoaded', function() {
   $rootScope.online = false;
});



Preview :




If you like this post or you have any problem during implementation don't to leave a comment below i will definitely reply you back as soon as possible.



Chears :)

Happy coding