DEV Community

Tanzim Ibthesam
Tanzim Ibthesam

Posted on • Updated on

Node Express CRUD with Mongoose,JWT authentication,authorization

Here we will make a CRUD with REST API along with its authentication.Express.js is unopinionated means everyone can have their own way of doing things which is quite different from a strict framework.
If you are using VS code and type Cntrl+` to open the terminal and write npm init -y
image
It will create a pacakge.json file for you on the left hand side
image
At first you need to install express and mongoose.
npm install express && npm install mongoose
If you go to package.json file you can see
image
In our depencies you have got your express and mongoose installed to check whether a package has been installed go package.json. These are pretty basic stuffs but will help a begiiner a lot.
you will create a file called app.js
in app.js
image
These are the thigs you will initially write in app.js file here you will initialize express
go to terminal type node app.js
image
Now we can see that the server is initialized on port 5000. The port can be anything 5000,6000,8000.
But the problem is we need to run it each and every single time when there is any change. As a result we need to install nodemon
npm install nodemon Then if we go to our package.json file we will see
image
noe if we want to use nodemon we can use the scripts in package.json file
image
Now we can go to your terminal and run npm start

image
Now you dont need to run node app.js nodemon will restart everytime there is a change
Connection with MongoDB through mongoose
If you dont have MongoDb installed on your system please install it first. Here you creating a new database we will use Robo3t here
if you go to Robo 3t you can see
image
If you click connect you can see
image

It will look something like this
image

From here you will see a modal like this you will named your databse and see create
image

If you have done everything correctly you will see name of the databse you have created on the left

We can use .env files for that we need to install a new package

image

image

If everything is alright we can now we can see it running

image
We can install npm install dotenv to keep database name in an env file
In .env file
image
In app.js file
image

This is not mandatory but a good practice
Router
Let us get the router fixed we need to create a new file called router.js you can set all routes inside app.js but its better to have a separate route file now if we create router.js

image

In app.js
const allRouter=require('./routes')
app.use('/',allRouter);

Now we need 2 parts 1 is the model and other is the controller
In Model part there will be the database and controller part will have the logic

Create a new folder model/Post.js
image
here we see we can that we want to add two fields to posts collection title and description

CRUD part
CREATE
In routes.js
Import PostsController
const PostsController=require("./controller/Posts");
Post route
router.post('/posts/create',PostsController.createPost);
Import Post Model on top
in controller/Posts.js
image
Test in Postman
Make sure in headers Content type is set to application/json
image
Testing post request
image

We can clearly see its successfull giving us a status code of 200

READ
In router.js
router.get('/posts',PostsController.getPost)
getpostimage

In controller/Posts.js

Postman test
image
If we also check in Robo 3T
image

Now we can say that it has been successfully inserted onto database.
** READING A SINGLE POST**
In router.js
router.get('/posts/:id',PostsController.findSinglePost)
In controller/Posts.js
image

Test in Postman
Here you can get id from databse using Robo3T or just by using get requests to get all posts
image
Now we see from where we can get the id and get a single post
image

UPDATE
In router.js
//Updating a single post
router.put('/posts/:id',PostsController.updatePost);

In controller/Posts.js
image
Testing in postman
The same way we get id like shown with getting id of a single post
image
DELETE
In router.js
//Delete a post
router.delete('/posts/:id',PostsController.deletePost);

In controller/Posts.js
image
Testing in postman
image
We will get the individual post and delete
While Updating you most likely will get an warning
Mongo Db update warning
For resolving the warning go to app.js
useFindAndModify: false
Mongo Update warning resolved

API Authentication,authorization with JWT
Now we will do authentication using email and password only. Remember JWT is used for authorization not authentication
Create a new model in model/User.js
IN User.js
In this case
model user
Here we are including email,password and token.

In controller folder we will create a new file called Auth.js
We need to import User model at the top
User Model

In router.js
//signup route
router.post('/signup',AuthController.signup) we need to import AuthController at the top
const AuthController=require("./controller/Auth")
In controller/Auth.js
We need to install a package called bcyrpt
Signup method in Auth.js
signuprevised

Here is signup we need to use bcrypt to hash the password as we all know passwords cant be stored in plain text
Testing in Postman
signuproute
As we see the password is hashed and status is ok
Signin Route
In router.js
router.post('/signin',AuthController.signin);
signin
In signin route after checking credentials a token needs to be generated.Remember Token is for authorization not authentication. We set the secret key on top the secret key can be set in .env file remember the secret key must be secret.
Testing in Postman
signinroutetesting

Authorization
We will use a pacakge named express-jwt for installing npm install express-jwt.
Creating a middleware
A middleware can be termed as something between a request and response.If we want to protect any route that users who only have token can enter those routers.
in controller/Auth.js
signedIn middleware
Route test with middleware
In router.js on top
const {isSignedIn}=require("./controller/Auth");
Route with isSignedIn
router.get('/testauthroute',isSignedIn,(req,res)=>{
res.send("A protected route")
res.json(req.auth)
})

Testing in Postman
testuthroute
Here if we try to access this route without token we get this error 401 forbidden means without token you cant access this route.
test with token

Here we need to go to header part of the token include Authorization in header.In value of authorization header we need to write Bearer give a space before the token and then copy and paste the token authorization value
If you go to jwt and test your jwt you will see you get all your info
jwt. Here header is the type which is JWT the signature is the token and payload is the email and id.So that's all for this blog. Hopefully you will be able to grasp the concepts of Node,Express,Jwt,authentication,authorization here.

Top comments (5)

Collapse
 
gochev profile image
Nayden Gochev

Super random question @tanzimibthesam but I noticed you are using windows.

However what is the FONT and SIZE you are using in the screenshots with the darkula theme.
For example res.cloudinary.com/practicaldev/im... ?

It looks good :) thanks for the info

Collapse
 
tanzimibthesam profile image
Tanzim Ibthesam • Edited

Thanks Nayden its not Dracula its known as Teacher theme Dark
The Font name is Consolas, 'Courier New', monospace
font-size:14
Here is the link of the theme:marketplace.visualstudio.com/items...

Collapse
 
gochev profile image
Nayden Gochev

my consoles size 14 doesn't look like that hmmmm but thanks :)

Collapse
 
rubenvidales profile image
Ruben Vidales Jacas

Hi, firstly nice work.
I have a doubt, I saw you add cookie-parser on Auth.js but I don't understand why you added it
Thanks

Collapse
 
tanzimibthesam profile image
Tanzim Ibthesam

As far as i can recall its a middleware used for dealing with jwt secret