Objective: In this article, you will know jsonwebtoken, mongoose model, how to create user using node, router.
Pre-requisite Prior to completing this article, you should have already installed all pre-requisite tooling including: Visual Studio Code, Node Package Manager (NPM), Node, Postman, Mongo Compass.
Create a Model (ProfileModel.js)
const mongoose = require('mongoose')
const DataSchema = mongoose.Schema({
FirstName : {type: String},
LastName : {type: String},
EmailAddress : {type: String},
MobileNumber : {type: String},
City : {type: String},
UserName : {type: String},
Password : {type: String}
});
const ProfileModel = mongoose.model('Profile', DataSchema)
module.exports = ProfileModel;
Create a Controller (ProfileController.js)
At first import ProfileModel. Declare a variable reqBody to store body data. Then create user using ProfileModel model
Install jsonwebtoken
using this command npm i jsonwebtoken
. Then declare into ProfileController.js file
const ProfileModel = require("../models/ProfileModel");
var jwt = require('jsonwebtoken');
exports.CreateProfile = (req, res) => {
let reqBody = req.body;
ProfileModel.create(reqBody, (err, data) => {
if(err){
res.status(400).json({status: "Failed to user create", data: err})
}else{
res.status(200).json({status: "Successfully user created", data: data})
}
})
}
exports.UserLogin = (req, res) => {
let UserName = req.body['UserName'];
let Password = req.body['Password'];
// res.status(200).json({status: "Success", data: Password})
ProfileModel.find({UserName, Password}, (err, data) => {
if(err){
res.status(400).json({status: "Failed to login", data: err})
}else{
if(data.length > 0){
// create auth token
let Payload = {
exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60),
data: data[0]
}
var token = jwt.sign(Payload, 'SecretKey123456789');
res.status(200).json({status: "Successfully Login", token: token, data: data})
}else{
res.status(401).json({status: "Unauthorized"})
}
}
})
}
exports.SelectProfile = (req, res) => {
let UserName = req.headers['username']
ProfileModel.find({UserName}, (err, data) => {
if(err){
res.status(400).json({status: "Failed", data: err})
}else{
res.status(200).json({status: "Success", data: data})
}
})
}
The find() function is used to find particular data from the MongoDB database
GetUserName
from middleware (AuthVerifyMiddleware) header
Extra two thing added from normal login. Like Payload and SecretKey. Also pass the token into response token: token
let Payload = {
exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60),
data: data[0]
}
var token = jwt.sign(Payload, 'SecretKey123456789');
Default configuration (app.js)
// Basic import
const express = require('express');
const router = require('./src/routes/api')
const app = new express();
const bodyParser = require('body-parser')
// Database lib import
const mongoose = require('mongoose')
// Body parser implement
app.use(bodyParser.json())
// MongoDB database connection
let uri = 'mongodb://127.0.0.1:27017/PracticeDB'
let options = {user: '', pass: ''}
mongoose.connect(uri, options, (err) => {
if(err){
console.log(err)
}else{
console.log('Database Connection Success')
}
})
// Routing Implement
app.use('/api/v1', router)
// Undefined Route Implement
app.use("*", (req, res) => {
res.status(404).json({status: "Failed", data: "Not Found"})
})
module.exports = app;
Routes configuration (api.js)
const express = require('express');
const ProfileController = require('../controller/ProfileController')
const AuthVerifyMiddleware = require('../middleware/AuthVerifyMiddleware')
const router = express.Router();
router.post('/CreateProfile', ProfileController.CreateProfile)
router.post('/UserLogin', ProfileController.UserLogin)
router.get('/SelectProfile', AuthVerifyMiddleware, ProfileController.SelectProfile)
module.exports = router;
Added middleware AuthVerifyMiddleware into SelectProfile router
Index file (index.js)
const app = require('./app')
app.listen(5000, function(){
console.log('Server run at @5000 port')
})
Middleware (AuthVerifyMiddleware.js)
var jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
let token = req.headers['token-key']
jwt.verify(token, "SecretKey123456789", (err, docoded) =>{
if(err){
res.status(401).json({status: "Unauthorized"})
}else{
// get username from docoded token & add with req header
let username = docoded['data']['UserName']
req.headers.username = username;
next();
}
} )
}
Now open the Postman. Then login a user giving basic information and click Send Button.
Taken token key and insert into header token field
After that going SelectProfile then click to Send Button
Thanks for reading. Happy journey.
Reference
User create using NodeJS
Login without JWT
jsonwebtoken
Mongoose find() Function
User login by JWT
Top comments (0)