Introduction
In this article, we make a simple user login register system. Them, we apply authorization for it using a middleware.
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
- {
- "name": "auth",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "author": "",
- "license": "ISC",
- "dependencies":{}
- }
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-parser: extracts 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.
- {
- "name": "auth",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "keywords": [],
- "author": "",
- "license": "ISC",
- "dependencies": {
- "body-parser": "^1.19.0",
- "express": "^4.17.1",
- "express-session": "^1.17.0",
- "mongoose": "^5.8.11"
- }
- }
Add New Folder
Now add 3 new folder in the project
Models
- Add a new file and name it user.js
- var mongoose = require('mongoose');
-
-
- var userSchema = new mongoose.Schema({
- email:String,
- password:String,
- role:String
- });
-
- 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
- var userModel = require('../models/user');
-
- var authorize = (role)=>{
- return (req,res,next)=>{
- if(req.session.uid){
- userModel.find({$and:[{'_id':req.session.uid},{'role':role}]},(err,data)=>{
- if(err){
- res.json({error:err});
- }else{
- if(data!=''){
- req.user= data;
- next();
- }else{
- res.json({msg:'you dont have access to it'});
- }
- }
- });
- }else{
- req.json({msg:'user is not logged in'});
- }
- }
- }
-
- 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.
- var express = require('express');
- var userModel = require('../models/user');
- var auth = require('../config/authorize');
-
- var router = express.Router();
-
- router.post('/register',(req,res)=>{
- var user = new userModel({
- email:req.body.email,
- password:req.body.password,
- role:req.body.role
- });
- user.save((err,data)=>{
- if(err){
- res.json({error:err});
- }else{
- if(data!=''){
- res.json({userdata:data,msg:'user registered'});
- }else{
- res.json({msg:'user not registered.try again'});
- }
- }
- });
- });
-
- router.post('/login',(req,res)=>{
- userModel.find({$and:[{'email':req.body.email},{'password':req.body.password}]},(err,data)=>{
- if(err){
- res.json({error:err});
- }else{
- if(data!=''){
- //here we create uid session
-
- req.session.uid=data[0]._id;
- res.json({msg:'user is logged in'});
- }else{
- res.json({msg:'user is not regisered'});
- }
- }
- });
- });
-
-
- router.get('/adminprofile',auth('admin'),(req,res)=>{
- res.json({data:req.user});
- });
-
- 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
- var express = require('express');
- var mongoose = require('mongoose');
- var session = require('express-session');
- var bodyParser = require('body-parser');
-
-
- mongoose.connect('mongodb://localhost:27017/authorizee',{useNewUrlParser:true})
- .then(()=>console.log('connected to db'))
- .catch((err)=>console.log('error',err))
-
-
- var app = express();
-
-
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({extended:false}));
-
-
- app.use(session({
- secret:'THISISmykey12345',
- resave:false,
- saveUninitialized:false
- }));
-
-
- app.use('/user',require('./routes/users'));
-
-
- var port = process.env.PORT || 3000;
- app.listen(port,()=>console.log('server run at '+port));
Now open the package.json file and in scripts add "start ":"node app.js"
- {
- "name": "auth",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1",
- "start": "node app.js"
- },
- "keywords": [],
- "author": "",
- "license": "ISC",
- "dependencies": {
- "body-parser": "^1.19.0",
- "express": "^4.17.1",
- "express-session": "^1.17.0",
- "mongoose": "^5.8.11"
- }
- }
Output