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
Difficulty
- Intermediate
Create Validation Auth
This tutorial is a continuation of the previous tutorial that is Consuming JWT API with MongoDB and Node.js. 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 APIto 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:
// make prefix
app.use('/api',router);
router.post('/login',function(req, res){
});
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.
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:
user.findOne({
email: req.body.email
}, function(err,user){
//you can see the result in this section
})
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 userare 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 if (err) throw err
.
Example :
function(err,user){
if(err) throw err;
if(!user){
res.json({
success: false,
message: 'User not found'
})
}
})
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:
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'
})
}
}
- 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:
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
})
}
- jwt.sign() : We can create a token with this method. jwt.sign() has 3 parameters .
- Data: Data to be generated. in terms of this tutorial the data to be generated is the user.
- SecretKey: SecretKey will be used as a combination of token generate. In this case, the secretkey gets from app.get ('secretKey').
- 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.
res.json({
success : true,
message : 'Token has been created',
token : token
})
- FULL 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);
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.
Posted on Utopian.io - Rewarding Open Source Contributors
Hey @alfarisi94
We're already looking forward to your next contribution!
Decentralised Rewards
Share your expertise and knowledge by rating contributions made by others on Utopian.io to help us reward the best contributions together.
Utopian Witness!
Vote for Utopian Witness! We are made of developers, system administrators, entrepreneurs, artists, content creators, thinkers. We embrace every nationality, mindset and belief.
Want to chat? Join us on Discord https://discord.me/utopian-io
Thank you for the contribution It has been approved.
Need help? Write a ticket on https://support.utopian.io.
Chat with us on Discord.
[utopian-moderator]
great:)