Verifying paths using Jwt Token authentication

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

Struggling to implement authentication for employee routes using the generated JSON token from user login. How can I restrict access to only authenticated users with a valid 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})
    }

})

Answer №1

To ensure secure authentication, you can implement middleware in your Node.js application:

First, create a middleware file named 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, include the middleware:

const checkAuth = require("path to check-auth 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})
    }

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with MongoDB queries failing in live environments due to authentication problems

I'm currently developing a NodeJS application using Mongoose for database operations. Initially, I had no issues accessing my records in the "bears" database when authentication was disabled in Mongoose. However, upon enabling authentication and conf ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

What is the best way to create persistent cookies using node.js in conjunction with express-session?

I'm looking to implement persistent cookies in my app to avoid the need for users to log in every time they visit the website. The goal is to only require a login if they choose to log out. I'm curious if there's a way to set the maxAge of t ...

What is the process for retrieving a bad port (6666) in a Node.js application?

Currently, in node.js version v18.14.0, my task involves fetching data from port 6666 (the URL is just a placeholder in this instance): await fetch("http://placeholder.com:6666/secret-service", {"method": "GET"}); Upon attem ...

How can I implement a popup overlay on a redirected URL in Next.js?

Currently in the process of developing my own URL shortener, I'm looking to incorporate a Call To Action on the target URLs page. My tech stack includes NextJs, Tailwind, NodeJs, and Express. Something along these lines: example image If anyone has ...

Regular expressions for capturing login usernames

I recently worked on a web chat project where I utilized socket.io for real-time message sending and receiving. One of the requirements was to capture user logins if they were mentioned within the conversation. Though being a beginner, I attempted to use ...

Make sure to pass the req.user.username when redirecting to success in Passport.js

Upon successful user login, I aim to redirect them to a route that includes their username as a parameter: router.post("/login", checkNotAuthenticated, passport.authenticate("local", { successRedirect: "/dashboard/" + req. ...

Is it possible to identify which modules in the package.json file need to be compiled?

When deploying to Azure sites, issues may arise if one of your npm modules requires compilation. Is there a simple method to review the packages.json file in order to alert users not on Windows when they might encounter problems? ...

Vue specifies the location of the index.html file

I'm new to working with Vue and node, and I'm attempting to insert a global value in my project by placing my index.html in a public directory. After creating the project, I noticed that the public src folder was not generated, but I could still ...

Node.js communicates using commas instead of newlines

Whenever I use Express to generate a project, it outputs commas instead of newlines. For example: express my_project This generates everything in a single line ,/**, * Module dependencies., */,,var express = require('express'), , routes = ...

Difficulty encountered when transferring data between React frontend and Node Express backend (CORS and API endpoints)

Encountering an issue where submitting form data results in a 404 error stating the endpoint is not found. The server.js file can be reviewed for further details on how to set up sending an email from the node express server upon passing data through the b ...

Unable to connect executable "node": unable to locate library "libcrypto.so.3"

When using Termux (my_distro): $ pkg show openssl Package: openssl Version: 3.0.1-1 Maintainer: @termux Installed-Size: 6648 kB Depends: ca-certificates, zlib Conflicts: libcurl (<< 7.61.0-1) Breaks: openssl-tool (<< 1.1.1b-1), openssl-dev Repl ...

Using node.js to generate an object from a raw HTTP request string

I've got a raw HTTP request string that I need to convert into an object representation. Instead of trying to create something new, I was considering using the internal http parser to generate an instance of http.IncomingMessage Can it be done? I b ...

Implementing Security Measures for ExpressJS Static File Server

Recently, I set up an authentication system following a tutorial on express.js and passport.js. In the past, my express server setup used modRewrite as shown below: var express = require('express'); var modRewrite = require('connect-mod ...

Discord.js version 14 is throwing a TypeError that says it cannot read properties of undefined, specifically 'commands'

Lately, I've been working on a discord.js bot to refresh my JavaScript skills after a long break. I've been following a tutorial on reloading slash commands and events, but I encountered this error: TypeError: Cannot read properties of undefined ...

The Team Build process halts to allow the Gulp task to complete before moving forward

After successfully pushing my existing nodejs app to the VSTS repository, I incorporated three build tasks into the workflow. The first task, npm install, is running smoothly without any issues. However, when it comes to the Gulp task, which includes a ...

Can TCP Net and HTTP Server Crash in NodeJS when Errors Occur?

Currently, my NodeJS server is set up to operate on two different ports: One port for the net TCP server, which connects to telematics hardware devices sending data messages And another port for the HTTP server to manage the web app platform These funct ...

Inquiring about socket.io: How can an io emit its own signal?

I am currently working on implementing the emit event in an express router, and I'm attempting to pass a global.io variable. However, I've encountered an issue where despite adding the following code: io.emit('join','Tudis' ...

Transform node.js express application into executable binary file

I've been experimenting with compiling an express web API into a binary in order to protect my source code. While using nexe, I encountered some issues such as the modification of __dirname and __filename behavior. I can adjust my own code to work aro ...

Is it possible to utilize the Compute Engine API with NodeJS to make changes to the files on a Compute Engine virtual machine?

Currently, I am working on a project in Google Cloud that involves utilizing both their App Engine and Compute Engine services. Within the Compute Engine, there is a virtual machine instance named "instance-1", where a python file (file.py) resides: name ...