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