Applications used this time:
- vscode
- postman
- XAMPP (for windows) / LAMPP (for linux)
- node js / npm
before starting to program we have to install the jsonwebtoken package by writing the code in the terminal like this
npm i jsonwebtoken
in the .env file create a variable named SECRETE_TOKEN and fill it with your secret token as below:
# for JSON WEB TOKEN
SECRET_TOKEN=ThISIsSeCrEtETOkEN
3. Create New Token on Controller
previously import the jsonwebtoken package that was installed earlier and call the .env file like this
const jwt = require("jsonwebtoken");
require("dotenv").config();
in the userController we create a variable with the result of data encryption to which we will add the token we created and the expiration period
const token = await jwt.sign(
{
username: req.body.username,
password: req.body.username,
},
process.env.SECRET_TOKEN,
{
expiresIn: "24h",
}
);
4. Replace Token in Query Database
After creating the token variable, we replace the token in the database with req.body.username+req.body.password into the token variable that we created earlier, it looks like this:
Create New User
await model.user.create({
username: req.body.username,
password: req.body.password,
token: token,
})
.then((result) => {
res.status(201).json({
message: "user successful created",
data: {
username: req.body.username,
password: req.body.password,
token: token,
},
});
});
Update User
await model.user.update(
{
username: req.body.username,
password: req.body.password,
token: token,
},
{ where: { id: req.body.id } }
);
res.status(200).json({
message: "update successful",
data: {
id: req.body.id,
username: req.body.username,
password: req.body.password,
token: token,
},
});
5. Test On Postman
Create New User
Update User
after creating a token with JWT in this article it will be easier for us to create authentication with middleware which we will discuss in the next article
See You ~~~