Many applications require user registration and login so that individuals get separate experiences. In this post, we'll create a simple user login system that we'll build upon later to create a cloud-hosted document repository complete with user authentication, cloud storage, and user comments.

This is the first in a series of five tutorials (links to the complete series can be found below) in which we'll build a simple cloud application on the CenturyLink Cloud Platform that ties together several of our cloud products.

You can view screen shots of the completed application here:

In this tutorial, we'll use CenturyLink AppFog to deploy and host a Node.js application that uses CenturyLink Orchestrate to store and authenticate user credentials.

Tools Used

AppFog is our Platform-as-a-Service (PaaS) offering based on Cloud Foundry. It allows you to easily host cloud-native applications without worrying about provisioning and maintaining servers and separate services. AppFog applications deploy quickly and scale automatically while having access to the full range of CenturyLink Cloud products.

Orchestrate is our Database-as-a-Service (DBaas) system built for rapid application development. It’s a fast, efficient NoSQL solution with a REST API for access. With Orchestrate, applications have cloud-hosted storage that scales massively while offering redundancy and fault-tolerance.

Before We Start

If you don’t have a CenturyLink Cloud account yet, head over to our website and sign up for a free trial. You’ll need it to access AppFog. You also need an Orchestrate account. Visit the Orchestrate sign-up page and get a free trial account.

In addition, you'll need to install Node.js, Express, and the Cloud Foundry client tools on your development machine. Check with the documentation for your development environment to find out the best way to do this.

  • With Ubuntu, run the following commands to install the development tools and binaries:
    $ sudo apt-get install nodejs npm cf-cli
    $ sudo npm install express -g
        $ sudo npm install express-generator -g

Creating an Application in Orchestrate The first stage of the project is creating an Orchestrate application. This is equivalent to provisioning an Orchestrate database to store users and encrypted passwords. For more information, visit the Orchestrate documentation.

  1. Visit the Orchestrate Dashboard in your web browser and login to your Orchestrate account.

    Orchestrate Dashboard

  2. Click the New Application button. It prompts you for an application name. We suggest prefixing your application name with your company name. For example, “My Company: My Application”.

    Create New App

  3. Your new application has an API key that you need to configure your project. Record it for use in the next step.

    API Key

You now have an Orchestrate application ready to store and retrieve data.

Set Up the Node.js Project The next step is to create the Node.js project. We'll use the Express.js web application server framework that you installed earlier.

Note: If you want to follow along with our already-completed example, download the code for this project. It's located in the Git repository. The code for this part of the tutorial is in the "part1" tag.

Clone the Git repository with the following commands:

    $ git clone
    $ cd clc-nodejs-tutorial
    $ git checkout tags/part1

Initialize Your Express.js Project Use the Express command line tool to start your project. The express tool creates a new directory to host a project. You'll also use the --git flag to instruct the tool to initialize a new Git repository in the directory.

  • Run the following shell command:
    $ express --git <my-project-name>

Note: Replace <my-project-name> with the name of your project. It should be a valid Unix filename and cannot contain any spaces.

Edit the Package Configuration

  1. In your project directory, open the package.json file in your favorite text editor. Edit the file to look like this:

      "name": "<my-project-name>",
      "version": "0.1.0",
      "config": {
            "datacenter": ""
      "description": "Get started with Node.js on CenturyLink AppFog",
      "private": true,
      "scripts": {
            "prestart": "npm install",
            "start": "node ./bin/www"
      "dependencies": {
            "bcryptjs": "^2.3.0",
            "body-parser": "~1.13.2",
            "cookie-parser": "~1.3.5",
            "debug": "~2.2.0",
            "express": "~4.13.1",
            "express-session": "^1.12.1",
            "jade": "~1.11.0",
            "morgan": "~1.6.1",
            "serve-favicon": "~2.3.0"
  2. Set the name attribute to your project name. The name can’t contain any spaces. Note that because AppFog uses a global project namespace, this needs to be unique.

  3. Set the config.datacenter value to the hostname from the datacenter you selected in “Creating an Application in Orchestrate” earlier in this tutorial.

Note: See the Orchestrate Datacenter list for all datacenter hostnames.

Data Center List

Configure the Web Server Since you're using AppFog to deploy the application, it’s important that it understands how to read configuration values from AppFog’s environment.

  1. Open the bin/www file with your favorite text editor.
  2. Locate the line that begins var port = normalizePort
  3. Replace that block with the code below:
     * Get the port from the environment. Note that the VCAP_APP_PORT is
     * used by CenturyLink AppFog to specify which port this should run
     * on. Otherwise, fall back to port 3000.
    var port = normalizePort(process.env.VCAP_APP_PORT || '3000');
    app.set('port', port);
    ##Your Project Should now be Properly Configured and Ready for Development.

Running Your Application Your configuration only serves a single route at the moment, but this is a good time to make sure that everything is working correctly.

  1. Run the following command in your project directory.

    $ npm start
  2. You'll see all of your dependencies checked and updated. The local server will begin serving your application. Checked and Updated

    Note: When you see the node ./bin/www line, your application is running.

  3. Visit http://localhost:3000/ to verify.

Deploying Your Application to AppFog At this point, we configure AppFog in your CenturyLink Cloud account and prepare your app for deployment. To get a good understanding of AppFog, you should read the Getting Started Guide. For now we'll just cover the basics.

Enable AppFog First, enable AppFog in your CenturyLink Cloud control panel.

  1. Go to the Control Panel and log in.
  2. Select AppFog from the pull-down menu. Control Panel Appfog
  3. Select the same region that you picked for your Orchestrate application earlier. Control Panel Region

Log in to AppFog using the Cloud Foundry Tools Once AppFog is set up in your CenturyLink Cloud account, you need to login to AppFog using the Cloud Foundry CLI. The Control Panel gives you an exact command from the Overview tab.

  1. Find the cf login command on your AppFog control panel. It will look similar to this:

    cf login -a -o C007 -u your.username

    Appfog CF Login

  2. Run the command in your project directory.

  3. Enter your CenturyLink Cloud password when prompted. Cloud Password

  4. Select the Dev application space. Dev App Space

    Note: To learn more about logging into AppFog using the Cloud Foundry command-line tools, read this article from our Knowledge Base.

Deploy Your Application

After the initial configuration and login, deployment is just one command.

  • Run the following command in your project directory, replacing <my-project-name> with the name of your project.
    $ cf push <my-project-name>

A successful deployment will produce a lot of output and looks similar to this when it finishes: App Started

Note: To learn more about deploying Node.js applications, read about it here in our Knowledge Base.

Authentication with Passport and Orchestrate Our application uses Passport to authenticate against user information stored in Orchestrate. Passport is authentication middleware for Node.js and makes for simple, fast development of different backend methods, which it calls “strategies.” The approach used in our application is based on the Orchestrate strategy outlined by Jhenna Voorhis on our Developer Center Blog.

Install Additional Libraries We will now install the additional libraries needed to add Passport and Orchestrate support to our application. The npm tool is the package manager for Node.js. The --save flag adds the installed library to the dependencies in your project's package.json file.

  • Run the following commands:
    $ npm install orchestrate --save
    $ npm install passport --save
    $ npm install passport-local --save
    $ npm install q --save

Create a Private Configuration Next, we'll create config.js, a file to store private configuration values, such as API keys. Because it’s private, don’t add config.js to your Git repository! For now, it will contain only the Orchestrate API key that you saved during Step 3 of "Creating an Application in Orchestrate" earlier in the tutorial.

  1. Create a file called config.js in your project directory.
  2. Edit the file to look like the following example, replacing <your-orchestrate-api-token> with your unique Orchestrate API Token:
    // config.js
    // This file contains private configuration details.
    // Do not add it to your Git repository.
    module.exports = {
      "orchestrate_token": "<your-orchestrate-token>"

Create Passport Strategy In this step, you create a Passport strategy that uses Orchestrate to store user credentials.

  1. Create a new file in your project directory called functions.js
  2. Edit the file to contain the following code:
    // functions.js
    // Handle setup of Passport configuration and user authentication
    var bcrypt = require('bcryptjs'),
            Q = require('q'),
            config = require('./config.js');

    // Orchestrate connection
    var oio = require('orchestrate');
    var db = oio(config.orchestrate_token, process.env.npm_package_config_datacenter);

    // Register a new user, failing if that user already exists
    exports.localReg = function (username, password) {
      var deferred = Q.defer();
      var hash = bcrypt.hashSync(password, 8);
      var user = {
            "username": username,
            "password": hash,
            "note": "Created by CenturyLink Cloud test application"
      console.log("CHECKING ON: " + username);

      // Check if username is already present in Orchestrate
      db.get('local-users', username)
            .then(function (result){ //case in which user already exists in db
              console.log('USERNAME ALREADY EXISTS');
              deferred.resolve(false); //username already exists
            .fail(function (err) {
              // User doesn't exist. Register the user.
              console.log("USERNAME AVAILABLE");
              db.put('local-users', username, user)
                .then(function () {
                .fail(function (err) {
                  console.log("PUT FAIL:" + err.body.message);
                  deferred.reject(new Error(err));
      return deferred.promise;

    // Check for the existence of a username.
    // Use bcrypt.compareSync to check encrypted password.
    exports.localAuth = function (username, password) {
      var deferred = Q.defer();
      db.get('local-users', username)
            .then(function (result){
              var hash = result.body.password;
              console.log("FOUND USER: " + username);
              if (bcrypt.compareSync(password, hash)) {
              } else {
                console.log("AUTHENTICATION FAILED");
            .fail(function (err){
              if (err.body.message == 'The requested items could not be found.'){
                console.log("USER NOT FOUND: " + username);
              } else {
                deferred.reject(new Error(err));

      return deferred.promise;

    // End functions.js

Add Passport to the Application Now that we have a Passport strategy that uses Orchestrate, it’s time to modify the app.js file, which is the heart of the Express web application.

Near the top of the file, you need to make sure that functions.js is loaded. You also need to load some additional required libraries, such as Passport and Express-session.

  1. Open app.js in your text editor.
  2. Find the block of code at the beginning of the file that starts with var express and ends with var users.
  3. Edit that section so it looks like this:
    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var session = require('express-session');
    var routes = require('./routes/index');
    var users = require('./routes/users');

    // Load our functions.
    var funct = require('./functions.js');

    // Passport Libraries
    var passport = require('passport'),
        LocalStrategy = require('passport-local');

Integrate Passport into Session Object Next, just after the Passport libraries are loaded, you need to tell Passport how to integrate into the web session object and how to use your Orchestrate strategy.

  1. Find the point in app.js after the libraries have been loaded.
  2. Add the following code:
    // Passport session integration functions.
    passport.serializeUser(function(user, done) {
      done(null, user);

    passport.deserializeUser(function(obj, done) {
      done(null, obj);

    // Use the LocalStrategy within Passport to login/”signin” users.
    passport.use('local-signin', new LocalStrategy(
      {passReqToCallback : true}, //allows us to pass back the request to the callback
      function(req, username, password, done) {
            delete req.session.success;
            delete req.session.error;

            funct.localAuth(username, password)
            .then(function (user) {
              if (user) {
                console.log("LOGGED IN AS: " + user.username);
                req.session.success = 'You are successfully logged in ' + user.username + '!';
                done(null, user);

              if (!user) {
                console.log("COULD NOT LOG IN");
                req.session.error = 'That username and password combination is not valid!';
                done(null, user);
            .fail(function (err){

    // Use the LocalStrategy within Passport to register/"signup" users.
    passport.use('local-signup', new LocalStrategy(
      {passReqToCallback : true}, //allows us to pass back the request to the callback
      function(req, username, password, done) {
            delete req.session.success;
            delete req.session.error;

            console.log("TRYING TO REGISTER: " + username);
            funct.localReg(username, password)
              .then(function (user) {
                if (user) {
                  console.log("REGISTERED: " + user.username);
                  req.session.success = 'You are successfully registered and logged in ' + user.username + '!';
                  done(null, user);
                if (!user) {
                  console.log("COULD NOT REGISTER");
                  req.session.error = 'That username is already in use, please try a different one.';
                  done(null, user);
              .fail(function (err){

Enable Passport Middleware Finally, you need to enable the Passport middleware so Express knows when to use it.

  1. Find the line in the app.js file that begins app.use(express.static
  2. After that line, add the following code:
    // Enable Passport middleware
    app.use(session({secret: 'binarystar', saveUninitialized: true, resave: true}));

Note: Be sure to change the secret parameter to something other than binarystar.

Add Views to the Application Now you need to add views, so your application actually gives you something to look at. While Voorhis’s example used Handlebars templates, yours will use Jade. We picked Jade because it’s the default template engine for Express.

  1. Open the views/index.jade file in your text editor.
  2. Edit the contents to look like the following code:
    extends layout
    block content
      h1= title
            | This example shows you how to authenticate against an
            a(href='') Orchestrate
            |  database.
        if user
                strong Welcome back, #{user.username}!
                a(href='/logout') Logout
            p You have never been here before.
                a(href='/signin') Please sign in

This template accesses #{user.username}, which contains a valid record if a login was successful. You'll see how this is passed to the template when you build your routes in the next step.

Create Login Screen View You also need to create a view to contain the template with the login and account creation forms.

  1. Create views/signin.jade with your text editor.
  2. Edit the contents to look like the following code:
    extends layout
    block content
      h1= title
      p Please sign in using the form below.
      form(method='post', action='/login')
            label Username:
                input(type='text', name='username', size='20')
            label Password:
                input(type='password', name='password', size='20')
            input(type='submit', value='Login')
      h2 If you don't have an account, please make one
      form(method='post', action='/local-reg')
            label New username:
                input(type='text', name='username', size='20')
            label New password:
                input(type='password', name='password', size='20')
            input(type='submit', value='Create account')

Create Application Routes Express uses “routes” to map URIs to functions, like other web frameworks. For the application, you need to significantly rewrite routes/index.js in order to integrate the Passport functions you need.

  1. Open routes/index.js in your text editor.
  2. Replace the contents with the following code:
    var express = require('express');
    var router = express.Router();
    var passport = require('passport');

    /* GET home page. */
    router.get('/', function(req, res, next) {
      var tpl = { title   : 'CenturyLink Cloud Example',
                  user    : req.user,
                  session : req.session };

      res.render('index', tpl);

    router.get('/signin', function(req, res, next) {
      res.render('signin', { title   : 'Please sign in',
                             session : req.session });

    // Sends the request through our local signup strategy, and if
    // successful takes user to homepage, otherwise returns then to signin
    // page'/local-reg', passport.authenticate('local-signup', {
        successRedirect : '/',
        failureRedirect : '/signin'

    // Sends the request through our local login/signin strategy, and if
    // successful takes user to homepage, otherwise returns then to signin
    // page'/login', passport.authenticate('local-signin', {
        successRedirect : '/',
        failureRedirect : '/signin'

    // Logs user out of site, deleting them from the session, and returns to homepage
    router.get('/logout', function(req, res){
        delete req.session.notice;
        delete req.session.error;
        if (!req.user) {
    var name = req.user.username;
    console.log("LOG OUT: " + name)
      req.session.success = "You have successfully been logged out " + name + "!";

    module.exports = router;

Your application should now be ready to run.

Authenticating with Enterprise Applications Using Passport, an application can authenticate against more than 300 different services. In addition, as the example shows, adding custom authentication sources is relatively simple. You can write authentication modules to check login credentials against enterprise directory services such as Active Directory or other LDAP-based databases.

Running Your Application After configuring your application and looking at how Passport and Orchestrate work together, it’s time to run it and test it.

  1. Run the following command in your project directory.

       $ npm start
  2. You will see all of your dependencies checked and updated. The local server will begin serving your application.

    Local Server

    Note: When you see the node ./bin/www line, your application is running.

  3. Visit http://localhost:3000/ and click Please sign in.
  4. Create a new account.

    Local Host

  5. Create a user account with your new web application.

Deploying Your Changes to AppFog After you're satisfied that your application is working correctly, it’s time to deploy your changes to AppFog.

  • Run the following command in your project directory to deploy to the cloud. Replace <your-project-name> with the name of your project.
        $ cf push <your-project-name>

Your updated application is now deployed.

The Next Step: Object Storage

In our next tutorial, we'll cover adding enterprise-grade cloud object storage to our Node.js application using CenturyLink Object Storage. Our object storage solution is S3-compatible and more efficient than hierarchical file systems. We'll demonstrate how to use Orchestrate and Object Storage together to provide fast, reliable access to documents and files.

Links to the Complete Tutorial Series

  • Part 1 - Store and Authenticate User Credentials
  • Part 2 - Build a Document Storage System
  • Part 3 - Include Powerful Search Capabilities
  • Part 4 - Add a Customized PDF Viewer and Comment System
  • Part 5 - The Next Step for Your Web Application