Introduction
Nowadays we are spotting Node.Js everywhere in the software industry. The demand for Node.Js developers is increasing day by day. Node.Js is the most popular JavaScript framework and an open source server environment that allows you to run JavaScript on the server.
In this article, we will build a Xamarin.Android authentication app with the help of Node JS with Mongo DB. We will develop our backend API in Node.JS with No SQL database and then consume this REST'ful API in our client app Xamarin.Android. In this post, I will teach you how to build this app exactly with all frontend and backend-coding. So, let's get started.
Prerequisites
You are required to have basic knowledge of Node JS and intermediate level knowledge of Xamarin. Android and a basic idea of NoSQL databases like Mongodb.
In the initial stage, you must have installed mongodb and Node on your local PC. I am skipping the installation process of Node and Mongodb.
Backend API (Server Side Application)
Step 1 - Create Database
In this step, we will create a new database in Mongodb for storing user information. Open your Mongodb folder and copy the path. Go to -> C: drive and open your program files and search MongoDB and open this folder inside this open server folder and then go to the bin folder.
C:\Program Files\MongoDB\Server\4.2\bin
Open your command prompt as administrator and hit the follwing commands.
- enter -> cd /d C:\Program Files\MongoDB\Server\4.2\bin
- enter -> mongo
- enter -> use DatabaseName //Write database name in place of DatabaseName whatever you want.
- enter -> db.createCollection('user') //user is Collection Name (Like In SQL Table)
Step 2 - Create Node Project
Create a new folder with your project name and copy the path of your project. Hit the npm init command for creating your node project.
After creating your node project add the follwing npm packages to your node project.
- npm install mongodb //For mongodb connection
- npm install crypto //To encrypt user's password
- npm install express //To create RRSTFul API
- npm install body-parser //For parsing the user form
Open your project folder add a new js file with name index.js and the following code.
-
-
- var mongodb = require('mongodb');
- var ObjectID = mongodb.ObjectID;
- var crypto = require('crypto');
- var express = require('express');
- var bodyParser = require('body-parser');
-
-
-
-
-
- var generateRandomString = function(length){
- return crypto.randomBytes(Math.ceil(length/2))
- .toString('hex')
- .slice(0,length);
- };
-
- var sha512 = function(password, salt){
- var hash = crypto.createHmac('sha512',salt);
- hash.update(password);
- var value = hash.digest('hex');
- return{
- salt:salt,
- passwordHash:value
- }
- };
-
- function saltHashPassword(userPassword){
- var salt = generateRandomString(16);
- var passwordData = sha512(userPassword,salt);
- return passwordData;
- }
-
- function checkHashPassword(userPassword,salt){
- var passwordData = sha512(userPassword,salt);
- return passwordData;
- }
-
-
- var app = express();
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({extended:true}));
-
-
- var MongoClient = mongodb.MongoClient;
-
-
- var url = 'mongodb://localhost:27017' //27017 is default port
- MongoClient.connect(url,{useNewUrlParser:true, useUnifiedTopology:true},function(err, client)
- {
- if(err)
- {
- console.log('Unable to connect to MongoDB server.Error',err);
- }
- else
- {
-
- app.listen(3000,()=> {console.log('Connected to MongoDb server, Webservice running on on port 3000');
- });
- }
-
-
- app.post('/register',(request,response,next)=>
- {
- var post_data = request.body;
-
- var plain_password = post_data.password;
- var hash_data = saltHashPassword(plain_password);
-
- var password = hash_data.passwordHash;
- var salt = hash_data.salt;
-
- var firstname = post_data.firstname;
- var lastname = post_data.lastname;
- var mobile = post_data.mobile;
- var email = post_data.email;
-
- var insertJson = {
- 'firstname':firstname,
- 'lastname' : lastname,
- 'email': email,
- 'mobile' : mobile,
- 'password': password,
- 'salt': salt
- };
-
- var db = client.db('ahsannodejs');
-
-
- db.collection('user').find({'email':email}).count(function(err,number){
- if(number != 0){
- console.log('User Email already exist!');
- response.json('User Email already exist!');
- }else{
-
- db.collection('user').insertOne(insertJson,function(err,res){
- console.log('User Registeration Successful..');
- response.json('User Registeration Successful..');
- });
- }
- });
-
- });
-
-
- app.post('/login',(request,response,next)=>
- {
- var post_data = request.body;
-
- var email = post_data.email;
- var userPassword = post_data.password;
-
- var db = client.db('ahsannodejs');
-
-
- db.collection('user').find({'email':email}).count(function(err,number){
- if(number == 0){
- console.log('User Email not exist!');
- response.json('User Email not exist!');
- }else{
-
- db.collection('user').findOne({'email':email},function(err,user)
- {
- var salt = user.salt;
- var hashed_password = checkHashPassword(userPassword,salt).passwordHash;
- var encrypted_password = user.password;
- if(hashed_password == encrypted_password)
- {
- console.log('User Login Successful..');
- response.json('User Login Successful..');
- }else
- {
- console.log('Login Failed Wrong Password..');
- response.json('Login Failed Wrong Password..');
- }
- });
- }
- });
-
- });
-
- });
Step 3 - Build and Run
Copy your project path and run your command prompt as administrator and hit node index.js to Run your server.
Test Register Method
Test Login Method
Already Exist User Method
For simplicity, I am splitting the article into two parts. In the next part, I will consume this RESTFul API in Xamarin Android. So, please stay tuned for my next article of this series.