Thursday, October 30, 2014

nodejs - secured server with https connections

Previous post


Checkout the code at github
If you can use command below for checkout and run the app.

vanduc@VGN-FZ290E:~/test2$ git clone --depth=10
vanduc@VGN-FZ290E:~/test2$ cd nodejs-example/
vanduc@VGN-FZ290E:~/test2/nodejs-example$ git checkout -f 4-https
vanduc@VGN-FZ290E:~/test2/nodejs-example$ npm install
vanduc@VGN-FZ290E:~/test2/nodejs-example$ node index.js

HTTPS configuration 

For configuration HTTPS connection we need a key and self signed certification to make the SSL work.

Creating key/certificate pair very easy with only one line, if you already installed OpenSSL

openssl req -subj '/CN=localhost/O=mycompany/C=VN' -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout server.key -out server.crt

Code for HTTPS connection:

var options = {
  key: fs.readFileSync('./ssl/server.key'),
  cert: fs.readFileSync('./ssl/server.crt')
var server = https.createServer(options,app).listen(serverConfigure.sslPort, function () {
 var address,
        host = ? : 'localhost',
        port = serverConfigure.sslPort;
    address = host + ':' + port;
    console.log('HTTPS server is listenning on localhost:3443');

We will create HTTPS server by add option, the option is about the path of key and certificate,
the server will create with the option for SSL connection , express server by app variable.

HTTPS auto redirection

In order to protect our server (users still can access our server by HTTP connection). We need to redirect the user request to HTTPS connection.

There is some ways to make HTTP auto redirection
  1. inside nodejs code.
  2. configure firewall to auto forward.
We can simply configure inside nodejs code

function requireHTTPS(req, res, next) {
    if (! {
        var addressSSL,
            host = ? : 'localhost',
            port = serverConfigure.sslPort;
        addressSSL = host + ':' + port;
        return res.redirect('https://' + addressSSL + req.url);
if (serverConfigure.httpsAutoRedirection) {

If the option httpsAutoRedirection in serverConfigure file is true,  we will check every request to the server and redirect the request to HTTPS port.

Tuesday, October 21, 2014

NODEJS - Basic Access Authentication

Previous Post

This article is about how to do basic authentication with NodeJS.

Checkout my project on GitHub. For one who never checkout my project before.

vanduc@VGN-FZ290E:~/test2$ git clone --depth=10
vanduc@VGN-FZ290E:~/test2$ cd nodejs-example/
vanduc@VGN-FZ290E:~/test2/nodejs-example$ git checkout -f 3-basic-auth
vanduc@VGN-FZ290E:~/test2/nodejs-example$ npm install
vanduc@VGN-FZ290E:~/test2/nodejs-example$ node index.js

For one who already checked out my project.

vanduc@VGN-FZ290E:~/test2/nodejs-example$ git pull
vanduc@VGN-FZ290E:~/test2/nodejs-example$ git checkout -f 3-basic-auth
vanduc@VGN-FZ290E:~/test2/nodejs-example$ npm install
vanduc@VGN-FZ290E:~/test2/nodejs-example$ node index.js

You can login with username and password is  admin:123456

The code require authentication on server side:

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var app = express();
 secret: '1234567890QWERTY',
    saveUninitialized: true,
    resave: true}));
var realm = 'localhost';
function unauthorized(res, realm) {
    res.statusCode = 401;
    res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
    res.setHeader('Content-Type', 'text/html');
    res.end("This request requires HTTP authentication");
function checkLogin(username, password, callback){
 if(username =='admin' && password =='123456')
  callback('worng user name',username);
app.use(function (req, res, next) {
    var authorization = req.headers.authorization;
    var session = req.session;
    if (req.user) {
        console.log('User already stored in request : ' + req.user);
        return next();

    if (!authorization) {
        return unauthorized(res, realm);
    var parts = authorization.split(' ');
    if (parts.length !== 2) return next(error(400));
    var scheme = parts[0]
        , credentials = new Buffer(parts[1], 'base64').toString()
        , index = credentials.indexOf(':');
    if ('Basic' != scheme || index < 0)
     return next(error(400));
    var user = credentials.slice(0, index)
        , pass = credentials.slice(index + 1);
 if(session.user_id != ''&&session.user_id == user){
        return next();
    //async check authentication
    checkLogin(user, pass, function (err, username) {
        if (err != null) {
            req.user = req.remoteUser = null;
            return unauthorized(res, realm);
        req.user = req.remoteUser = user;
        session.user_id = user;

Then we use the tricky code for doing the logout basic authentication:

                var xmlHttp;
                if (window.XMLHttpRequest) {
                    xmlHttp = new XMLHttpRequest();
                // code for IE
                else if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                if (window.ActiveXObject) {
                    // IE clear HTTP Authentication
                } else {
          "GET", window.location, true, "logout", "logout");
                    xmlHttp.onreadystatechange = function () {
                        if (xmlHttp.readyState == 4) {
                return false;

In order to secured your site with basic access authentication, You must provide SSL connection.
Otherwise it is not good solution.
Some disvantages of basic-auth is you cant modify the login pop-up, It depends on the browser provider.
The user credentials will store on browers cache .... :( very bad

Next Post

Saturday, October 18, 2014

Restore grub2 after install windows

The problem is after you install linux and then you install a windows 

For example after install Ubuntu 9.10 and then I install Windows operating system along with Ubuntu. The windows will override Master Boot Record on Hard driver , so from now when your computer boot up, you only can see Windows.

To solve the problem:

We need to have a CD version of Ubuntu 9.10. Boot our PC with live mode of Ubuntu 9.10
.Open Terminal ( Applications  > Accessories > Terminal)

(We suppose that the Ubuntu already installed on  partition sda3 of sda)

sudo -i (change user to  root user).

mount /dev/sda3 /mnt

grub-install --root-directory=/mnt/ /dev/sda

mount --bind /proc /mnt/proc

mount --bind /dev /mnt/dev

mount --bind /sys /mnt/sys

chroot /mnt update-grub

umount /mnt/sys

umount /mnt/dev

umount /mnt/proc


Reboot your computer and enjoy !

Setting Global Environment Variables in LINUX

The easiest way to set an environment variable in CentOS is to use export as in :

vanduc@VGN-FZ290E:~/Downloads$export JAVA_HOME=/usr/lib/java/jdk1.7.0_71

vanduc@VGN-FZ290E:~/Downloads$export PATH=$PATH:$JAVA_HOME

However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots.

In such cases, you need to set the variables within the system wide profile

In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile.

For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case:
Create a new file called

vanduc@VGN-FZ290E:~/Downloads$ sudo vi /etc/profile.d/

Within this file, initialize the necessary environment variables

export JAVA_HOME=/usr/lib/java/jdk1.7.0_71

export JRE_HOME=$JAVA_HOME/jre

export PATH=$PATH:$JRE_HOME/bin

export PATH=$PATH:$JAVA_HOME/bin

Now when you restart your machine, the environment variables within will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded) .

If you want to load the environment variables within without having to restart the machine, you can use the source command as in:

vanduc@VGN-FZ290E:~/Downloads$ source /etc/profile.d/

Test command:

vanduc@VGN-FZ290E:~/Downloads$ java -version

java version "1.7.0_71"

Java(TM) SE Runtime Environment (build 1.7.0_71-b14)

Java HotSpot(TM) Server VM (build 24.71-b01, mixed mode)


P/S : some common commands use to setup java environment

vanduc@VGN-FZ290E:~/Downloads$ cd Downloads/
vanduc@VGN-FZ290E:~/Downloads$ ls
google-chrome-stable_current_i386.deb jdk-7u71-linux-i586.tar.gz sublime-text_build-3065_i386.deb
vanduc@VGN-FZ290E:~/Downloads$ tar -zxvf jdk-7u71-linux-i586.tar.gz
vanduc@VGN-FZ290E:~/Downloads$ sudo mkdir /usr/lib/java
vanduc@VGN-FZ290E:~/Downloads$ mv jdk1.7.0_71/ /usr/lib/java/

Monday, October 13, 2014


About NodJs

One of the great things about Node.js is that it has a built in HTTP server. This means you don't need Apache or nginx. This means serving a static site can be done in few lines of code. This article goes into how this can be achieved.

Express Static Middleware

Express has become the defacto Node.js web framework and it has great built in capabilities to serve static content. The nice thing is that not only can you serve static content you can also gzip compress it and cache it. But let's just start with the required package.json and a basic static server.

Let's start

1. Set up package.json file

Use command $npm init for creating package.json file

D:\static>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install  --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (static) static-server
version: (0.0.0) 0.0.1
description: this is an example how to create static server with nodejs
entry point: (index.js)
test command:
git repository:
author: ducnguyen
license: (ISC)
About to write to D:\static\package.json:

  "name": "static-server",
  "version": "0.0.1",
  "description": "this is an example how to create static server with nodejs",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "ducnguyen",
  "license": "ISC"

Is this ok? (yes) yes


After init we will have the contain of package.json file

  "name": "static-server",
  "version": "0.0.1",
  "description": "this is an example how to create static server with nodejs",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "ducnguyen",
  "license": "ISC"

2. Install express module

Using command $npm install expess

Add contains for index.js file:

var express = require('express');
var app = express();
var http = require('http');
app.use(express.static(__dirname + '/public'));
var server = http.createServer(app).listen(3000, function () {
 console.log('server is listenning on localhost:3000');

The above code is very simple, it creates an Express server, adds the static middleware and finally starts listening on port 3000 .

The static middleware handles serving up the content from a directory. In this case the 'public' directory is served up and any content (HTML, CSS, JavaScript) will be available. This means if the public directory looks like:

Then you can request the root route '/' and you'll get index.html file and the index.html also load the css and js file of boostrap. This is all expected from a static server.
Now just start the server by type command in command line promt $node index.js, and go to bowser hit http://localhost:3000/

We can also specify the url of static server:

app.use('/static',express.static(__dirname + '/public'));

Now  instead of type http://localhost:3000/ we will have our static page at http://localhost:3000/static/

Command for checkout :

vanduc@VGN-FZ290E:~/test2$ git clone --depth=10
vanduc@VGN-FZ290E:~/test2$ cd nodejs-example/
vanduc@VGN-FZ290E:~/test2/nodejs-example$ git checkout -f 1-static
vanduc@VGN-FZ290E:~/test2/nodejs-example$ npm install
vanduc@VGN-FZ290E:~/test2/nodejs-example$ node index.js

1. You will clone my repository at depth=10 means you will get last 10 commits
2. Change your directory working directory nodejs-example
3. Change the checkout to the 1-static, this was the tags with for static version.
4. Installing nodejs module need to run my application.
5. Start the application and enjoy.

Next Post