Thursday, April 2, 2015

Kick start to NodeJS , Angular with sql server ( Part 1 )

NodeJS is there in industry from  a fairly long time though I didn't get much interests towards that. Probably Microsoft web api was good enough to develop  HTTP , REST / JSON services for me .
By the way , the special interest I have on scripting influenced me to touch up nodejs as server side language finally.
In this article I am focusing on creating a SPA(Single Page App), totally based on JavaScript. The front end of the SPA will be using angularJS as MVVM( Something little more than MVC). Finally deploying an app in cloud. I am gonna use heroku as PAAS ( Platform as a service.)
Later on ill be modifying same articles to make them more informative and clear for starters.
There are still lots of useful stuff out there in web for MEAN stack development. (Mongo,Express,Angular,Node). But I am pretty sure that there may still be lots of developers who want to connect to sql server other than mongodb. So this article also will suit for them and help to pass that barrier.
I would first say , developing an apps with Angular as a MVVM front and Node as a backend is surprisingly easy and straight forward. If you are scripting type developer who see the things without an IDE ( "Atom" or "Sublime" are the two good opensource  IDE s for scripting if you need.), this app would not take more than couple of hours in  a day to fully construct, understanding correct concepts.


NodeJS

One of the main interesting  reasons why people love Node is its behavior as a server. Yay! No big deal in server deployment.
A traditional web server handles client requests through a multiple threads.In other words a client request makes a new thread in a server . But Node claim they do not !! So client and server connect through a single thread , but yet they got a powerful event looper to deal with multiple requests behind the scene .
End of the day node says , they fast . Fair enough.(I  haven't benchmark though )

AngularJS

Okay so why angular for templating and as a frontend MVC ? Though the love I got to Jquery never fades , I would still move to Angular just because of following reason.
[easy two way binding].
Do you remember the old days we define  html tags  , read em through ids or whatever and change the display content , colors etc.
Jquery way,
<p id="msg">  </p>
$("#msg").html("Success");

Angular way,
<p > {{   model.msg  }}  </p>

The update automatically done  with angular.
What you update in client view , reflects in model and vise versa. Cool.
No more JS lines in AJAX callback function.
But remember ,  you still have to work with in "ng" scope , you still have ng-App ,  ng-controller , ng-model etc to achieve this functionality. They are so called default angular directives.
Now let us begin  a simple Sql server + Node + Angular app.
As a little heads up, How this combination works in highlevel.
  1. In SPA s as the title says there should be only one index html page. WHich could be your master template.
  2. NodeJS first loads up that page for angular to start up with its own routings.
  3. Node will responsible for writing RESTFULL api and ngular will connect with them with stateless http.
From now you are gonna deal with lots of commands to install development environment to settle with node.
Install nodejs msi from here. (Node versions with even numbers are stable releases)
https://nodejs.org/download/
Create a folder in your drive . Lets call it as  "node"
Create a js file , Rename it is "server.js" . Just keep it empty for now.
Open windows command prompt .(cmd)
Type a command,
[path_to_folder/root] > npm  install express

In a few moments you will see there will be a folder created in your app root call "node_modules". Open it, and there is "express" package folder. 
OK. Here is a small tip to get things clear from here.
We need lots of packages to be integrate with our apps to implement various tasks. 
eg:- routes, authentication, organize code etc etc. 
Just like our famous java packages or .NET namespaces.

To install server packages related to node you will be using "npm"( node package manager).
For client packages to be work with Angular you will use "bower".

In order to install bower packages for angular you would need "bower.json" file configure in root and then "packages.json" file to install server related packages.
Once you have bower.json and package.json, with all dependencies listed ,
Navigate to your directory in cmd,
then 'npm install'
or 'bower install'
Boom! you will get all dependencies install rightaway.


Express

What is express in node development? As any other framework in any other programming language , express makes developer's life easy, by adding more high level set of features(simplified) to construct the code easily.
Note
In SPA's ,we structure the server side of things in application with package.json file as mentioned above which also could contain set of commands requires to startup the application.
eg:- app start up command etc.
So, when you configure start command in package.json ,
like this "scripts": {"start": "node server.js"}
you may simply use following command to run it from directory.
npm start
Lets now go back to the server.js file and start modifying it to up and running a server.
var express  = require('express');
var app      = express(); //Create an app with express
var port   = process.env.PORT || 8080;

app.listen(port);
console.log("App listening on port " + port);

Once this is done open cmd again and navigate to folder
> node server.js ( If you do not have start command in package.json file)
You will see , " App listening on port 8080 ." in console.
Interesting fact about node / angular combination is you can write console.log statements in java script code and node write to cmd while angular write to browser console. Cool.
Great you just initiated node/angular SPA app.
Next step is to place a file in a folder and view it from a browser .
"Express" can do a magic for you to define api routes and simplifying a work.
Create a folder name "website" inside the root directory and place a html file with some content to display.
Before load a static index file in browser we need to tell node about our static file directory.
app.use(express.static(__dirname + '/website'));
"__dirname" is a global variable which gives root of current directory.
After define static directory we need to tell node about routes. To do that will create a seperate js file and name it routes.js.
Since our application should have well organized structure will make new directory call "app" in root and put the new file in.
So by now here is how your application structure looks like.




add bellow code in routes.js file.
module.exports = function(app) {
// Load index file-------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./registration/index.html'); // load the index from static files directory.
});
};
Well, '*'  is most abstract level api route we define to load very first file from server.
After constructing routes.js file do not forget to tell server.js about it by adding following line in server.js.
require('./app/routes.js')(app);
server.js and "app" is staying in same directory so the path starts with "./".
complete code in server.js.
var express = require('express');
var app = express();
var port = process.env.PORT || 86; 
app.use(express.static(__dirname + '/website'));
require('./app/routes.js')(app);

app.listen(port);
console.log("App listening on port " + port);
Please note I set port to 86 as I got plenty of things running on famous ports. 
lets start your server and then view your work.
open cmd and go to the directory
cd path
node server.js
Now go to the browser and request
Yay! You will see your first website starter files loaded on browser.
We will speak little more further on following posts to make it better and better.
Here is a sample which I am writing on.
https://hasinodeapp.herokuapp.com/

Thursday, February 5, 2015

Token based Authentication for REST design

One main challenge in distributed application development is security . In older days application had front-end and backend together , used to host in same server . We used various authentication methods , like DB based user/pass verification , LDAP authentication etc .
There is a different between loosely coupled/distributed app arichitecture and old bundled app designs. That is Distributed applications use service oriented architecture (SOA) . Simply facebook /twitter has that kind of design, means they expose their application functions as services . Some of them can be public where as anyone can access , and some of them are secured and restricted with in particular app domain .
So what are the advantages here ? Flexibility and Scalability .
Since we have separately hosted functions (services) , any external party can use those functional pieces and deliver, creative end product by capturing related user requirements . Google has huge services API . How many products they have , maps / news / search etc .Imagine the scope of their services and how strong authentication mechanism they got ?
That is a background .
Security is a major concern in this design. How can we make a strategy to ensure the security .Ill take REST based services api for this example. Remember old days , developing applications with session. Web Server allocates one session per each user login . Developers uses cookies to keep the relationship between client and server session. But REST is stateless . That is REST functions do not care who is accessing it . So that client app has to manage user session by app it self . No support from server .
Assume we have domain/employee resource (service). Since the services API hosted independently in some other server , many parties can access it .
Client A -> GET  domain /Employee/1
Client B -> GET  domain / Employee/ 1
But we only need our services allow to access by Client A. How can we make it ? We can pass identity with each and every request send from the client , as query string(GET request) or attached with request header ( Any request type POST/PUT/DELETE)
domain /Employee?Auth=Identity
header={
Authentication: Prefix Identity
}

Note

Identity is a token .
Concepts
  • To get access to services api , user should have a valid account . Eg:- To access google maps user should have google account
  • Once the user account authenticated (LDAP or Password table) ,User obtain a shared secret(between api and valid user) with the response of authentication method.
E.g.-:
POST             http://domain/Public/api/v1/Authenticate
Response        {Secret : "b5afcadd-0001-4a85-9feb-c17c8eb5425e}

Note

Web service stores the secret in their store with user id as key
Identifying Request Elements
  • User Id - Each request token must contain the access key ID of the identity use to send the request.
  • Signature - Each request token must contain a valid request signature, or the request is rejected.
Token Calculation

  • Authentication = "Basic " + Token
  • Signature = HMAC-SHA1(UserId , UTF-8-Encoding-Of( StringToSign ) )
  • StringToSign = SharedSecret+HTTP-Verb + Content-Type +URI
  • Token = base64 (userid: Signature )
Non revertible hmac-sha1 hash string not allow others to see the contents over transfer.

After receive the token from service end

Note

Web Service create a same mechanism to create the request token .
  • 1. Get shared secret from store using use rid
  • 2. Construct request signature using incoming request properties
  • 3. Use hmac-sha1 and generates a non revertible hash string
รข€¢ Compare both string values . If matches , it allows to do operations, else return 401 unauthorized status code.