const userModel = require('../models/UsersModel')
const express = require('express')
const routes = express.Router()
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
require('dotenv').config()
routes.post('/signup', async(req, res) => {
try {
const salt = await bcrypt.genSalt()
const hashedPassword = await bcrypt.hash(req.body.password, salt)
const newUser = new userModel({username: req.body.username, password: hashedPassword})
await newUser.save()
res.status(201).send(newUser)
} catch (error) {
res.status(500).json({message: error.message})
}
})
routes.post('/login', async (req, res) => {
const user = await userModel.find({"username": req.body.username})
console.log(user)
if (user == null) {
return res.status(400).json({"status": false, "message": "Invalid username and password"})
}
try {
if (await bcrypt.compare(req.body.password, user[0].password)) {
const accessToken = jwt.sign(req.body.username, process.env.ACCESS_TOKEN_SECRET)
res.status(200).json({"status": true, "message": "Login successful", accessToken: accessToken})
} else {
res.send('Not Allowed')
}
} catch (error) {
res.status(500).json({message: error.message})
}
})
module.exports = routes
How would I authenticate my employee routes using the json token thats generated in user routes login? Having trouble getting it to work? In the second code snippet I have to only allow users that have been authenticated and have recieved a token.
const employeeModel = require('../models/EmployeesModel')
const express = require('express')
const routes = express.Router()
const userRoutes = require('./UserRoutes')
const jwt = require('jsonwebtoken')
require('dotenv').config()
routes.post('/employees', async(req, res) => {
const newEmployee = new employeeModel(req.body)
try{
await newEmployee.save()
res.status(201).send(newEmployee)
}catch(err){
res.status(500).json({message: err.message})
}
})
CodePudding user response:
You can use middleware for this:
Create middleware file say check-auth.js:
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
if (req.method === "OPTIONS") return next();
try {
const token = req.headers.authorization.split(" ")[1];
if (!token)
return res.status(200).json({ message: "Authentication Failed!" });
const decodedData = jwt.verify(token, process.env.JWT_KEY);
req.userData = decodedData;
next();
} catch (error) {
console.log(error);
return res.status(200).json({ message: "Authentication Failed!" });
}
};
In your routes file:
const checkAuth = require("path of middleware file");
const employeeModel = require('../models/EmployeesModel')
const express = require('express')
const routes = express.Router()
const userRoutes = require('./UserRoutes')
const jwt = require('jsonwebtoken')
require('dotenv').config()
routes.post('/employees',checkAuth, async(req, res) => {
const newEmployee = new employeeModel(req.body)
try{
await newEmployee.save()
res.status(201).send(newEmployee)
}catch(err){
res.status(500).json({message: err.message})
}
});