Xamarin.Android - Working With Node.js And MongoDB - Part One

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
 
Xamarin.Android - Working With Node.js And MongoDB
 
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)
Xamarin.Android - Working With Node.js And MongoDB
 
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.
 
Xamarin.Android - Working With Node.js And MongoDB 
 
After creating your node project add the follwing npm packages to your node project.
  1. npm install mongodb          //For mongodb connection  
  2. npm install crypto               //To encrypt user's password
  3. npm install express            //To create RRSTFul API
  4. 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.
  1. //Import Packages  
  2.   
  3. var mongodb = require('mongodb');  
  4. var ObjectID = mongodb.ObjectID;  
  5. var crypto = require('crypto');  
  6. var express = require('express');  
  7. var bodyParser = require('body-parser');  
  8.   
  9.   
  10. //Password Utils  
  11. //Create Function to Random Salt  
  12.   
  13. var generateRandomString = function(length){  
  14.     return crypto.randomBytes(Math.ceil(length/2))  
  15.     .toString('hex'/* Convert to hexa formate */  
  16.     .slice(0,length);  
  17. };  
  18.   
  19. var sha512 = function(password, salt){  
  20.     var hash = crypto.createHmac('sha512',salt);  
  21.     hash.update(password);  
  22.     var value = hash.digest('hex');  
  23.     return{  
  24.         salt:salt,  
  25.         passwordHash:value  
  26.     }  
  27. };  
  28.   
  29. function saltHashPassword(userPassword){  
  30.     var salt = generateRandomString(16);  
  31.     var passwordData = sha512(userPassword,salt);  
  32.     return passwordData;  
  33. }  
  34.   
  35. function checkHashPassword(userPassword,salt){  
  36.     var passwordData = sha512(userPassword,salt);  
  37.     return passwordData;  
  38. }  
  39.   
  40. //Create Express Service  
  41. var app = express();  
  42. app.use(bodyParser.json());  
  43. app.use(bodyParser.urlencoded({extended:true}));  
  44.   
  45. //Create MongoDB Client  
  46. var MongoClient = mongodb.MongoClient;  
  47.   
  48. //Connection URL  
  49. var url = 'mongodb://localhost:27017' //27017 is default port  
  50. MongoClient.connect(url,{useNewUrlParser:true, useUnifiedTopology:true},function(err, client)  
  51. {  
  52.     if(err)  
  53.     {  
  54.         console.log('Unable to connect to MongoDB server.Error',err);  
  55.     }  
  56.     else  
  57.     {  
  58.         //Start Web Server  
  59.         app.listen(3000,()=> {console.log('Connected to MongoDb server, Webservice running on on port 3000');  
  60.     });  
  61.     }  
  62.   
  63.     //Register   
  64.     app.post('/register',(request,response,next)=>  
  65.     {  
  66.         var post_data = request.body;  
  67.   
  68.         var plain_password = post_data.password;  
  69.         var hash_data = saltHashPassword(plain_password);  
  70.   
  71.         var password = hash_data.passwordHash;  
  72.         var salt = hash_data.salt;  
  73.   
  74.         var firstname = post_data.firstname;  
  75.         var lastname = post_data.lastname;  
  76.         var mobile = post_data.mobile;  
  77.         var email = post_data.email;  
  78.   
  79.         var insertJson = {  
  80.             'firstname':firstname,  
  81.             'lastname' : lastname,  
  82.             'email': email,  
  83.             'mobile' : mobile,  
  84.             'password': password,  
  85.             'salt': salt  
  86.         };  
  87.   
  88.         var db = client.db('ahsannodejs');  
  89.   
  90.         //Check Already Exist Email  
  91.         db.collection('user').find({'email':email}).count(function(err,number){  
  92.             if(number != 0){  
  93.                 console.log('User Email already exist!');  
  94.                 response.json('User Email already exist!');  
  95.             }else{  
  96.                 //Insert data  
  97.                 db.collection('user').insertOne(insertJson,function(err,res){  
  98.                     console.log('User Registeration Successful..');  
  99.                     response.json('User Registeration Successful..');  
  100.                 });  
  101.             }  
  102.         });  
  103.   
  104.     });  
  105.   
  106.     //Login  
  107.     app.post('/login',(request,response,next)=>  
  108.     {  
  109.         var post_data = request.body;  
  110.   
  111.         var email = post_data.email;  
  112.         var userPassword = post_data.password;  
  113.   
  114.         var db = client.db('ahsannodejs');  
  115.           
  116.         //Check Already Exist Email  
  117.         db.collection('user').find({'email':email}).count(function(err,number){  
  118.             if(number == 0){  
  119.                 console.log('User Email not exist!');  
  120.                 response.json('User Email not exist!');  
  121.             }else{  
  122.                 //Insert data  
  123.                 db.collection('user').findOne({'email':email},function(err,user)  
  124.                 {  
  125.                     var salt = user.salt;  
  126.                     var hashed_password = checkHashPassword(userPassword,salt).passwordHash; //Hash Password with Salt  
  127.                     var encrypted_password = user.password; //Get Password from user  
  128.                     if(hashed_password == encrypted_password)  
  129.                     {  
  130.                         console.log('User Login Successful..');  
  131.                         response.json('User Login Successful..');  
  132.                     }else  
  133.                     {  
  134.                         console.log('Login Failed Wrong Password..');  
  135.                         response.json('Login Failed Wrong Password..');  
  136.                     }  
  137.                 });  
  138.             }  
  139.         });  
  140.   
  141.     });  
  142.   
  143. });  
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 
 
Xamarin.Android - Working With Node.js And MongoDB 
 
Test Login Method 
 
Xamarin.Android - Working With Node.js And MongoDB 
 
Already Exist User Method 
 
Xamarin.Android - Working With Node.js And MongoDB
 
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.


Similar Articles