This is second tutorial of Node.js. Previously, we got familiar with Node.js. Here we will do something interesting with node. In this tutorial, we will build an authentication module to verify usernames and passwords using cloud-based NoSQL technology. Broadly, cloud based NoSQL technology is built for handling large scale structured and unstructured data. Companies such as Microsoft, Google, Amazon, and Facebook make extensive use of NoSQL technology to house the vast quantities of data generated by their users.
Table of Contents
What we are going to build?
Application for authenticating usernames and passwords from server-side.
OR
Node authentication using express.js module to verify usernames and passwords using cloud-based NoSQL technology (Amazon EC2 @ MongoLab)
Things you need
- MongoDB (Database)
This is our NoSQL database, don’t worry if you don’t know about it. MongoDB is mature and scalable document-oriented database being used in enterprise environments. Document-oriented database is a database where the traditional database row is replaced with a less structured document, such as XML or JSON. - MongoLab (Cloud)
This is our cloud provider for stock monitoring application. I have chosen MongoLab cloud because it offers free hosting plan in place. - Express.js icon-external-link (web application framework)
It is web application framework for Node.js - GIT Bash
We will be using this command line instead of windows command prompt because coding here is easy and same for mac and unix. - A cup of tea (optional)
Creating MongoDB with MongoLab using Amazon EC2
- Goto MongoLab and create an account then verify your account.
- After verifying your account, click on create New button
- Next create FREE DB like this using Amazon EC2:
How to install Express.js in Node
Lets install express.js in node, express is third-party module, you know how to install third party modules. Don’t know ? check previous tutorial and come back. Ok now open GIT bash (which you have downloaded & installed from here)and write in git bash:
npm install -g express@2.5.8
Code Explanation: This is how to install express.js in node. -g says its a global module. express@2.5.8 says install express version of 2.5.8. Thats all for installing express.
Creating project in Node.js
Explanation: I have tagged above pic with numbers which represents code entered by me. The code is written in GIT BASH (not command prompt). So Tag 1 says that, change directory to Desktop (watch the case sensitivity). Tag 2 says that, now you are at desktop, make a folder and name it hfarazm. Tag 3 says that, change directory from desktop to hfarazm (newly created folder). Tag 4 says that, create a basic default express application named as authentication in hfarazm folder. Tag 5 says that, here we are installing dependencies (modules which our application will require). we change directory/folder from hfaraz to authentication then said install node package manager. question is how we gonna know about dependencies? well if you take a deeper look at couple of lines above step 5 of above pic you will see the exact line which i have written at step 5. but where these dependencies are defined? these dependencies are defined in root of your project folder within package.json file. Tag 6 says, start the app. write after step 6, it shows us that application can be accessed at localhost:3000 in your browser. when you open the application in browser.
By typing localhost:3000 your express.js app will look like this:These are errors. Now lets fix this, I have highlighted some text in above pic. Goto the highlighted file hfarazm > authentication > views > layout.jade and replace the code in layout.jade with the following:
doctype html // just replaced !!! with doctype html html head title= title link(rel='stylesheet', href='/stylesheets/style.css') body!= body
Now go back to localhost:3000 in your browser and reload the page. Wola, it says Welcome to Express. so basically what was wrong with layout.jade? in line 1 of layout.jade !!! is deprecated so I replaced it with doctype html and everything is now running fine. You must be watching this message in your browser at localhost:3000: Project Dependencies
Talking about dependencies, the application we are developing is for authenticating usernames and passwords, which will have some dependencies such as specific versions of jade and mongoose. Lets see how we can add these dependencies of specific version to our application:
Goto root folder of your application i.e authentication folder and open package.json file and add following code to it(this is where you specify your project dependencies): Explanation: Tag 1 says that, write the exact version of jade as written by me. Tag 2 says that, add another dependency named as mongoose and specify it version to be 2.6.5. Now that you have update package.json with dependencies you need for this application. Are they updated in project? answer is no. So how you check dependencies are also update in NPM(node package manager)? goto GIT BASH and while you are in authentication directory(which we created earlier – your project root directory) write:
npm ls // this will give you list of installed dependencies local to your project and will through error if any dependency is mismatch or not updated according to package.json file of your project.
Now you will get errors. saying jade and mongoose as INVALID. This means you need to install both these modules. you know how to install them right? ok here is how:
//for jade installation version 0.26.1, write following (you must be in your project folder while working in GIT BASH) npm install jade@0.26.1 //for mongoose installation version 2.6.5, write following (you must be in your project folder while working in GIT BASH) npm install mongoose@2.6.5
now again check the installed modules for your project using: npm ls. you will get no error. good to go. start your app now using: node app. Now you have created your project. Its difficult for the first time and a piece of cake for second time.
Creating form to post data to the server
Now your application is setup, time to create a form that will get username and password and post it to the server. If you remember, Node.js is deliberately minimalist, with very little that is done automatically. If you need to read a file from disk, you need to explicitly program it. so if your application is running then press CTRL+C to stop your local server and then goto your application folder which in our case is authentication folder. You will find an app.js file open it up and add the following code (having highlighted line numbers) to it (or you can copy/paste code from here to your app.js file):
/** * Module dependencies. */ var express = require('express') , routes = require('./routes') , fs = require('fs') // I have added fs dependency to allow reading from the file system , User = require('./models/User.js'); //will create this User.js file in a moment var app = module.exports = express.createServer(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); app.get('/form', function(req, res) { //handles all the routing to /form. Whenever anybody makes a request to localhost:3000/form // req and res are dependency injections they are for respond and request respectively fs.readFile('./form.html', function(error, content) { // reading form.html from the file system and serve the HTML file. Will create this file in a moment. if (error) { res.writeHead(500); res.end(); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(content, 'utf-8'); } }); }); app.post('/signup', function(req, res) { // this is for form submission var username = req.body.username; // get username var password = req.body.password; // get password User.addUser(username, password, function(err, user) { // add user to database if (err) throw err; res.redirect('/form'); }); }); // Routes app.get('/', routes.index); app.listen(3000); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
Talking about highlighted line numbers, You just told express.js that I m gonna read some file from the disk and if user moves to /form URL then you must take him to specified file or in case of error throw him error. secondly, line 48-56 is handling submission, when user clicks on SIGN UP button. We shall create file that is specified at line 8 shortly. Talking about Line 35: it says ok when the URL is like localhost:3000/form, then goto form.html file. So lets create form.html file at root of your project i.e hfarazm/authentication/form.html like this:
<html> <body> <form action="/signup" method="post"> <div> <label>Username:</label> <input type="text" name="username"/><br/> </div> <div> <label>Password:</label> <input type="password" name="password"/> </div> <div><input type="submit" value="Sign Up"/></div> </form> </body></html>
its just simple html form. Question is, how user is handled and database works? It comes from the users module, check the Interacting database heading below, but first lets just work with database like this:
The database
In order to create a users module, we’ll write a db module. Add the following code into a file called db.js in a directory called lib:
var mongoose = require('mongoose'); var Schema = mongoose.Schema; module.exports.mongoose = mongoose; module.exports.Schema = Schema; // Connect to cloud database var username = "hfarazm" //use your username here var password = "hfarazm.com"; //use your password var address = '@ds035240.mongolab.com:35240/nockmarket'; // use your address (make sure you copy the same structure link) connect(); // Connect to mongo function connect() { var url = 'mongodb://' + username + ':' + password + address; mongoose.connect(url); } function disconnect() {mongoose.disconnect()}
Line 6-10: Its just a simple DB connection where you specify your username, password and db address. The following picture show you how to get your username, password and db address from mongoLab:
Now go back to MongoLab website and create a user like this: Explanation: Tag 1: click on database that you created at the start of this tutorial. Tag 2: now click USER. Tag 3: now add your desired database username and password and click create. Tag 4: copy the highlighted URL (not this but yours) . Open db.js that you created a step before and replace text in highlighted line numbers with your mongoLab credentials and url that you copied. This is how we tell express about database. easy enough. Now we have created a user that have access to database, time for interacting with DB.
Interacting with database:
To interact with database we need to have its schema(a way to define the structure of a collection), that schema can be placed in “User.js” file under “models” directory like this:
var db = require('../lib/db'); var UserSchema = new db.Schema({ username : {type: String, unique: true } , password : String }) var MyUser = db.mongoose.model('User', UserSchema); // Exports module.exports.addUser = addUser; // Add user to database function addUser(username, password, callback) { var instance = new MyUser(); instance.username = username; instance.password = password; instance.save(function (err) { if (err) { callback(err); } else { callback(null, instance); } }); }
Code Explanation: This file is about handling user input. It requires a db connection at line 1. Then it tells the schema i.e how to take usernames and passwords. Finally, it tells about what to do when instance of object is successful/failed. Thats all folks.
Testing your app
- Start your app using GIT Bash, by navigating to your project directory then type: node app
- goto browser type: localhost:3000/form you will see this:
- enter information and click signup
- where is data goin? Goto mongoLab > click database > select collections > click your collection > under document you will see your entered data. It will look like this:
Done. Kindly Share 🙂 and Wait for next tutorial.
//
8 Responses
Awesome tut thanks!
Thanks. Kindly share my work 🙂
Welcome. Kindly share
Awesome tut thanks!
Thanks. Kindly share my work 🙂
Welcome. Kindly share
Awesome tut thanks!
Welcome. Kindly share