Applying Authorization in Node

Introduction

 
In this article, we make a simple user login register system. Them, we apply authorization for it using a middleware. 
 
Prerequisites
What is authorization? 
 
Authorization is a security mechanism to determine access levels or user/client privileges related to system resources including files, services, computer programs, data and application features. This is the process of granting or denying access to a network resource that allows the user access to various resources based on the user's identity. 
  
 
Project Structure 
 
  |----------config
  |                    |------- authorize.js  
  |
  |----------models 
  |                    |--------- user.js 
  |
  |----------routes
  |                    |-------- users.js         
  |  
  |----------app.js
  |
  |----------package.json 
 
 
Setup Folder 
 
Create a new folder  for the project
  • To open the console, type the following command followed by the folder name
      # mkdir auth
  • Change to the current folder
      # cd auth
 
Setup Node In-Folder
  • we can setup node in our folder by the following command
     #  npm init  -y
  • This command will generate a package.json file which shows that node is set up in our environment.
  • The file will look like this  
  1. {  
  2.   "name""auth",  
  3.   "version""1.0.0",  
  4.   "description""",  
  5.   "main""index.js",  
  6.   "scripts": {  
  7.     "test""echo \"Error: no test specified\" && exit 1"  
  8.   },  
  9.   "author""",  
  10.   "license""ISC",
  11.   "dependencies":{}
  12. }  
 This File will contain all the metadata related to our project.
 
Install Packages 
  • We can install package for the application using the following command
     # npm install body-parser express express-session mongoose
 
Some info about packages
  • body-parserextracts the entire body portion of an incoming request stream and exposes it on req.body.
  • express: it is a web framework for node.js.The complete application is built on it.
  • express-session: used for creating a session in node.
  • mongoose: mongoose is an object data modeling (ODM) library for mongodb and node.js.It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in mongodb.
After the packages are installed, the package.json will look like this.
  1. {  
  2.   "name""auth",  
  3.   "version""1.0.0",  
  4.   "description""",  
  5.   "main""index.js",  
  6.   "scripts": {  
  7.     "test""echo \"Error: no test specified\" && exit 1"  
  8.   },  
  9.   "keywords": [],  
  10.   "author""",  
  11.   "license""ISC",  
  12.   "dependencies": {  
  13.     "body-parser""^1.19.0",  
  14.     "express""^4.17.1",  
  15.     "express-session""^1.17.0",  
  16.     "mongoose""^5.8.11"  
  17.   }  
  18. }   
 
Add New Folder 
Now add 3 new folder in the project 
  • config
  • model 
  • routes
Models
  • Add a new file and name it user.js
  1. var mongoose    = require('mongoose');  
  2.   
  3.   
  4. var userSchema = new mongoose.Schema({  
  5.     email:String,  
  6.     password:String,  
  7.     role:String  
  8. });  
  9.   
  10. module.exports = mongoose.model('user',userSchema);  
  • mongoose.schema() : this will contain the collection(table)schema and defines the shape of the documents within that collection.
  • mongoose.mode() : there we will provide the name to our collection(table).

Config
 
Add a file and name it authorize.js 
  • authorize.js 
  1. var userModel = require('../models/user');  
  2.   
  3. var authorize = (role)=>{  
  4.     return (req,res,next)=>{  
  5.         if(req.session.uid){  
  6.             userModel.find({$and:[{'_id':req.session.uid},{'role':role}]},(err,data)=>{  
  7.                 if(err){  
  8.                     res.json({error:err});  
  9.                 }else{  
  10.                     if(data!=''){  
  11.                         req.user= data;  
  12.                         next();  
  13.                     }else{  
  14.                         res.json({msg:'you dont have access to it'});  
  15.                     }  
  16.                 }  
  17.             });  
  18.         }else{  
  19.             req.json({msg:'user is not logged in'});  
  20.         }  
  21.     }  
  22. }  
  23.   
  24. module.exports = authorize;  
  • In this function, we will check if the user is logged in by checking its session req.session.uid.
  • if the user is logged in, then we match his ID and role to his profile.if id and role match then we put his data in req.user.else users don't have access to a particular route.
 
Routes 
 
Add a file and name it users.js.
  •  user.js 
  1. var express     = require('express');  
  2. var userModel   = require('../models/user');  
  3. var auth        = require('../config/authorize');  
  4.   
  5. var router = express.Router();  
  6.   
  7. router.post('/register',(req,res)=>{  
  8.         var user = new userModel({  
  9.             email:req.body.email,  
  10.             password:req.body.password,  
  11.             role:req.body.role  
  12.         });  
  13.         user.save((err,data)=>{  
  14.             if(err){  
  15.                 res.json({error:err});  
  16.             }else{  
  17.                 if(data!=''){  
  18.                    res.json({userdata:data,msg:'user registered'});  
  19.                 }else{  
  20.                     res.json({msg:'user not registered.try again'});  
  21.                 }  
  22.             }  
  23.         });  
  24. });  
  25.   
  26. router.post('/login',(req,res)=>{  
  27.       userModel.find({$and:[{'email':req.body.email},{'password':req.body.password}]},(err,data)=>{  
  28.            if(err){  
  29.                res.json({error:err});  
  30.            }else{  
  31.                if(data!=''){  
  32.                     //here we create uid session
  33.                    //saving users id in session  
  34.                    req.session.uid=data[0]._id;  
  35.                    res.json({msg:'user is logged in'});  
  36.                }else{  
  37.                    res.json({msg:'user is not regisered'});  
  38.                }  
  39.            }  
  40.       });  
  41. });  
  42.   
  43. //here in auth we specify the role   
  44. router.get('/adminprofile',auth('admin'),(req,res)=>{  
  45.       res.json({data:req.user});  
  46. });  
  47.   
  48. module.exports = router;  
 
Add Entry Point 
  • Now add a file to the folder and name it app.js.
  • This will the start/entry point of our application.
app.js
  1. var express     = require('express');  
  2. var mongoose    = require('mongoose');  
  3. var session     = require('express-session');  
  4. var bodyParser  = require('body-parser');  
  5.   
  6. //connect to db  
  7. mongoose.connect('mongodb://localhost:27017/authorizee',{useNewUrlParser:true})  
  8. .then(()=>console.log('connected to db'))  
  9. .catch((err)=>console.log('error',err))  
  10.   
  11. //init app  
  12. var app = express();  
  13.   
  14. //fetch data from the request  
  15. app.use(bodyParser.json());  
  16. app.use(bodyParser.urlencoded({extended:false}));  
  17.   
  18. //session  
  19. app.use(session({  
  20.     secret:'THISISmykey12345',  
  21.     resave:false,  
  22.     saveUninitialized:false  
  23. }));  
  24.   
  25. //route  
  26. app.use('/user',require('./routes/users'));  
  27.   
  28. //assign port  
  29. var port = process.env.PORT || 3000;  
  30. app.listen(port,()=>console.log('server run at '+port));  
Now open the package.json file and in scripts add "start ":"node app.js"
  1. {  
  2.   "name""auth",  
  3.   "version""1.0.0",  
  4.   "description""",  
  5.   "main""index.js",  
  6.   "scripts": {  
  7.     "test""echo \"Error: no test specified\" && exit 1",  
  8.     "start""node app.js"  
  9.   },  
  10.   "keywords": [],  
  11.   "author""",  
  12.   "license""ISC",  
  13.   "dependencies": {  
  14.     "body-parser""^1.19.0",  
  15.     "express""^4.17.1",  
  16.     "express-session""^1.17.0",  
  17.     "mongoose""^5.8.11"
  18.   }  
Output 
 
 
 
  
 
 
 
 
Watch Video TutorialDownload code from here