14

Node Express CRUD with Mongoose,JWT authentication,authorization

 3 years ago
source link: https://dev.to/tanzimibthesam/node-express-crud-with-mongoose-jwt-authentication-authorization-3ogk
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Node Express CRUD with Mongoose,JWT authentication,authorization

Aug 23

・7 min read

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

It will create a pacakge.json file for you on the left hand side

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

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

These are the thigs you will initially write in app.js file here you will initialize express
go to terminal type node app.js

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

noe if we want to use nodemon we can use the scripts in package.json file

Now we can go to your terminal and run npm start

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

If you click connect you can see

It will look something like this

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

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

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

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

In app.js file

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 seperate route file now if we create router.js

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

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

Test in Postman
Make sure in headers Content type is set to application/json

Testing post request

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

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

Postman test

If we also check in Robo 3T

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

Test in Postman
Here you can get id from databse using Robo3T or just by using get requests to get all posts

Now we see from where we can get the id and get a single post

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

In controller/Posts.js

Testing in postman
The same way we get id like shown with getting id of a single post

DELETE
In router.js
//Delete a post
router.delete('/posts/:id',PostsController.deletePost);

In controller/Posts.js

Testing in postman

We will get the individual post and delete
While Updating you most likely will get an warning

For resolving the warning go to app.js
useFindAndModify: false

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

Here we are including email,password and token.
We need to

In controller folder we will create a new file called Auth.js

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
On Top of Auth.js

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

As we see the password is hashed and status is ok
Signin Route
In router.js
router.post('/signin',AuthController.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

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

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

Here if we try to access this route without token we get this error 401 forbidden means without token you cant access this route.

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
If you go to jwt and test your jwt you will see you get all your info
. 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK