Consuming JWT API with MongoDB and Node.js part-2# User Validation, Create token.
utopian-io·@alfarisi94·
0.000 HBDConsuming JWT API with MongoDB and Node.js part-2# User Validation, Create token.
#### What Will I Learn? - Create a route for API login - Make Validation - Create Token #### Requirements - Install node.js - Install Express.js - Install Postman - Basic node.js, javascript es6 - Basic Mongoose - Watch [part1](https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api) #### Difficulty - Intermediate ### Create Validation Auth This tutorial is a continuation of the previous tutorial that is [Consuming JWT API with MongoDB and Node.js](https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api). We will make auth with the help of **JWT(JSON Web Token)**. But before we create the **JWT** token, we need to create a routing **API**to login and validate the login. - **Create route API login** To make the API routing more neat. we can make a prefix ***/api***, to differentiate routing API and other routing. example: <pre> <code> // make prefix app.use('/api',router); router.post('/login',function(req, res){ }); </code> </pre> - app.use('/api',router): We can create a prefix with the ***use ()*** function, **the first parameter is the name of the prefix** and **the second is the initialization that will be in use**. to replace app. - router.post(): to post we can use the ***post ()*** function on the route. <br> - **Make Validation Login** We will create a login consisting of **email** and **password**. The first step that we do is matching email in the database with email data in **POST** by a user. We can use the function of the mongoose. That is **findOne ()**. Example: <pre> <code> user.findOne({ email: req.body.email }, function(err,user){ //you can see the result in this section }) </code> </pre> - findOne(): **findOne()** has two objects. the first object is the data to be in match with the database, and the second object is a function that has two parameters**( error , resultdata )**. - function(err,user): This function has two uses. to see errors if data does not match. and for if the data will be thrown into the second parameter. **err** and **user**are just the name of a parameter. - **Handle validation result** We can validate the user parameters in the function (err, user). As already described above. This function has the first two parameters containing the error, and the second is the user data. If an error occurs we can directly ***throw*** <code>if (err) throw err</code>. **Example :** <pre> <code> function(err,user){ if(err) throw err; if(!user){ res.json({ success: false, message: 'User not found' }) } }) </code> </pre> - if (err) throw err; : With err parameter. if an error occurs we can throw error. - if (! user) {}: with user parameter we can validate if user does not exist (! user) - res.json (): we can give respone in **JSON** form, with res.json () and make object as its parameter **{key1: value1, key2: value2}**. - **Handle Password not match** We can do further validation if the user is found. we can match the password in the user input with the password in the database. Example: <pre> <code> Example: if(!user){ res.json({ success: false, message: 'User not found' }) }else{ if(user.password != req.body.password){ res.json({ success: false, message: 'Wrong password' }) } } </code> </pre> - **if (user.password! = req.body.password)**: We can get user passwords that are on user parameters. And on the user.password object key, then matching with the password in input by the user who is on req.body.password. ! = this means if the password in the database does not match the password in the user input. If the result does not match it will be **true**, and we can give a response **res.json ({success: false, message: 'Wrong password'})**. - **Create Token** After the email and password from the user has successfully passed the validation. we can just straighten the **JWT** token in the **{else}** section of if (user.password! = req.body.password) {}. We can create a token with the sign () method of **JWT**. Example: <pre> <code> Example: if(user.password != req.body.password){ res.json({ success: false, message: 'Wrong password' }) }else{ // create token var token = jwt.sign(user, app.get('secretKey'),{ expiresIn: "24h" }); // return token res.json({ success : true, message : 'Token has been created', token : token }) } </code> </pre> - **jwt.sign()** : We can create a token with this method. **jwt.sign() has 3 parameters** . 1. **Data**: Data to be generated. in terms of this tutorial the data to be generated is the user. 2. **SecretKey**: SecretKey will be used as a combination of token generate. In this case, the secretkey gets from app.get ('secretKey'). 3. **Options** : Options in **object {}**. We can create an expired token that we created by using key **expiresIn**, in this tutorial expiresIn: "24h". 24h this means 24 hours. Then we can save the token in a variable in this tutorial that variable is **var token**. Once we have succeeded to parse the token we can see it with the return token in **JSON**. <pre> <code> res.json({ success : true, message : 'Token has been created', token : token }) </code> </pre>   - **FULL CODE** <pre> <code> var express = require('express'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var jwt = require('jsonwebtoken'); var app = express(); var router = express.Router(); var cors = require('cors'); var config = require('./app/config'); var user = require('./app/models/user'); var port = 3000; app.use(bodyParser.urlencoded({extended:false})); app.use(bodyParser.json()); mongoose.connect(config.database); app.set('secretKey', config.secret); app.use(cors()); // make prefix app.use('/api',router); router.post('/login',function(req, res){ user.findOne({ email: req.body.email }, function(err,user){ if(err) throw err; if(!user){ res.json({ success: false, message: 'User not found' }) }else{ if(user.password != req.body.password){ res.json({ success: false, message: 'Wrong password' }) }else{ // create token var token = jwt.sign(user, app.get('secretKey'),{ expiresIn: "24h" }); // return token res.json({ success : true, message : 'Token has been created', token : token }) } } }) }); app.listen(3000); </code> </pre> We have successfully validated the user and managed to get the token. in the next tutorial I will use a token to verify the user who is logged in and get the user data. <br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-2-validate-user-create-token">Utopian.io - Rewarding Open Source Contributors</a></em><hr/>
👍 anharismail, ayay, zcool, aafeng, yuxi, leir, yuxid, openanimus, yorkchinese, statsexpert, ubg, iqbalhood, clayjohn, cifer, thinkingmind, jaff8, loshcat, greenorange, utopian-1up, dyancuex, helo, mahdiyari, ronimm, simonluisi, thinkkniht, onos, jesdn16, stoodkev, luisrod, ansonoxy, eastmael, jamesbarraclough, espoem, moorkedi, kslo, nathalie13, not-a-bird, bitopia, berkaytekinsen, evilest-fiend, navx, family.app, varja, maphics, sebastiengllmt, phgnomo, zlatkamrs, amosbastian, proffgodswill, sweeverdev, kodeblacc, isacastillor, jerybanfield, rhotimee, deejee, rsteem, lemony-cricket, yeswanth, petvalbra, photohunter1, photohunter3, photohunter4, photohunter5, howtosteem, roj, nightdragon, flinter, opulence, ilyastarar, flauwy, inquiringtimes, elbleess, jfuenmayor96, instantania.cat, harshallele, xtramedium, maneki-neko, gotgame, steaknsteem, kimaben, eleonardo, zohaib715, naideth, checkthisout, handfree42, ilovekrys, not-a-cat, carsonroscoe, mountainjewel, xplore, solomon507, patatesyiyen, onin91, isabella394, emailbox19149, videosteemit, cheesom, saifannur-mzy, orlandumike, exploreand, hmctrasher, livsky, raoul.poenar, andiepumpgun, aderemi01, sampath94, killbill73, amirdesaingrafis, fai.zul, reazuliqbal, aliyu-s, mwfiae, masjenk, javapoint, nikema, carlitojoshua, donjyde, nonsqtr, crispycoinboys, bluestorm, jayo, sugandhaseth, pepememes, knot, ahmad097, animesukidesu, lsanek, lykia, realness, flugbot, ernoldlvb, kryptogermany, gydronium, clevershovel, nazmulrana, truthtrader, editorspicks, cryptocopy, artsyunicorn, steemfunder, femidada, polash66129, ongolodesire, lemcriq, studytext, downtempo, ewuoso, esme-svh, biplob12, odesanya, camillius, toninux, salahudeen, odibezeking, wealth4good, liveran, jdc, devilonwheels, abbyrich, solpaman, ankapolo, steemassistant, bargolis, phasma, carloniere, idlebright, adhew, jrmiller87, kaking, gwapoaller, saksham, techmojo, shenoy, thescholarlyowl, azwarrangkuti, utopian-io, amn,