Skip to main content

Command Palette

Search for a command to run...

Uncovering Flaws in User Authentication and Token Generation: A Deep Dive into Code Analysis and finding bug and Issues

Published
Uncovering Flaws in User Authentication and Token Generation: A Deep Dive into Code Analysis and finding bug and Issues
R

I'm Rudraksh Laddha — a DevOps engineer and emerging full-stack developer, passionate about building scalable, reliable systems that solve real-world problems.

With a solid foundation in cloud infrastructure automation using tools like Kubernetes, Docker, Terraform, and AWS, I thrive in environments where efficiency, resilience, and automation are key.

But my journey doesn't stop at infrastructure. I'm actively expanding into full-stack development, building dynamic applications using React, Node.js, and MongoDB. Whether it's designing cloud-native CI/CD pipelines or developing intuitive user interfaces, I enjoy creating end-to-end solutions — from server to screen.

Right now, I'm: 🧩 Building full-stack applications that merge DevOps reliability with engaging frontend experiences šŸ› ļø Contributing to open-source projects, learning through collaboration and real-world scenarios šŸš€ Growing Virendana Ui, my own UI library focused on expressive, clean design systems šŸš€ Growing Learn Virendana, where I share my personalized learning journey — from beginner to experienced šŸŽ® Developing side projects like 2048 Rush, blending product thinking with scalable infrastructure My long-term goal? To bridge DevOps and development — building products that are not just functional and fast, but also resilient, beautiful, and ready for scale.

This is my project on authentication, including the signup and login code structure. I have never found any flaws or mistakes. The problem arises when I sign up; it shows that your token is not generated in JSON. I noticed the mistake is that JWT is not forming the token, so I have included the main code where I might have made a mistake. Please explain what mistake I made.

routes/user.js

import express from "express";
import { handleUserLogin, userhandlesignup } from "../controller/user.js";
import { checkAuth } from "../middlewares/auth.js";

const router = express.Router();

router.post("/signup", userhandlesignup);
router.post("/login", handleUserLogin);


router.get("/dashboard", checkAuth, (req, res) => {
    res.render("dashboard"); 
});

export default router;

controller/user.js

import bcrypt from "bcrypt";
import NodeCache from "node-cache";
import { User } from "../models/User.js";
import { setUser } from "../service/auth.js"; 
const userCache = new NodeCache({ stdTTL: 3600 }); // Cache with 1-hour TTL

// Handle user signup
export const userhandlesignup = async (req, res) => {
    const { name, email, password } = req.body;
console.log("User Signup Request:", User);
    try {
        // Check if user already exists
        let user = await User.findOne({ email });
        if (user) {
            return res.status(400).json({ error: "User already exists" });
        }

        // Create new user
        const hashedPassword = await bcrypt.hash(password, 10);
        user = new User({ name, email, password: hashedPassword });
        await user.save();

        // Generate JWT Token
        const token = setUser(user); 

        // Set Cookie
        res.cookie("token", token, {
            httpOnly: true,
            sameSite: "Lax", 
            secure: false, 
            maxAge: 24 * 60 * 60 * 1000 // 1 day expiration
        });

        console.log("āœ… Token Set in Cookie:", token);
        res.status(201).json({ message: "User registered successfully", token });

    } catch (error) {
        console.error("Signup Error:", error);
        res.status(500).json({ error: "Internal Server Error" });
    }
};

// Handle user login
export const handleUserLogin = async (req, res) => {
    const { email, password } = req.body;

    try {
        const cachedUser = userCache.get(email);
        if (cachedUser) {
            res.cookie("token", cachedUser.token, { httpOnly: true });
            console.log("User logged in from cache:", email);
            return res.status(200).json({ message: "Login successful", token: cachedUser.token });
        }

        const user = await User.findOne({ email });
        if (!user) {
            console.log("User not found:", email);
            return res.status(404).json({ error: "User not found" });
        }

        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
            console.log("Invalid password for user:", email);
            return res.status(401).json({ error: "Invalid password" });
        }

        const token = setUser(user); // Create token using setUser
        userCache.set(email, { user, token });
        res.cookie("token", token, {
            httpOnly: true,
            sameSite: "None", 
            secure: true      
        });
        console.log("Cookie Set for", email, "Token:", token);
        console.log("User logged in and token set:", email);
        res.status(200).json({ message: "Login successful", token });
    } catch (error) {
        console.log("User login failed:", error);
        res.status(500).json({ error: "Failed to login" });
    }
};

// Handle user logout   
export const handleUserLogout = (req, res) => {
    const { email } = req.body;
    userCache.del(email);
    res.clearCookie("token");
    console.log("User logged out:", email);
    res.status(200).json({ message: "Logout successful" });
};

service/auth.js

import jwt from "jsonwebtoken";
const secret = process.env.JWT_SECRET || "Rudr$123@";
export const setUser = (user) => {
  console.log("Generating token for user:", user);


    return jwt.sign({
        userId: user._id,

    }, secret, { expiresIn: "24h" });
};

export const getUser = (token) => {
  console.log("Generated Token:", token);

  try {
    return jwt.verify(token, secret);
  } catch (error) {
    console.error("Token verification failed:", error);
    return null;
  }
};

middleware/auth.js

import { User } from "../models/User.js";
import { getUser } from "../service/auth.js";
export const checkAuth = async (req, res, next) => {
    console.log("Received Cookies in Middleware:", req.cookies); 
    console.log("User Signup Request:", req.body);

    const token = req.cookies?.token || req.headers.authorization?.split(" ")[1];
    console.log("Extracted Token:", token);
    if (!token) {
        console.log("No token found");
        return res.status(401).json({ error: "Your token is not generated" });
    }

    try {
        const decoded = getUser(token);
        req.user = await User.findById(decoded.userId);
        if (!req.user) {
            console.log("User not found");
            return res.status(401).json({ error: "User not found" });
        }
        console.log("User authenticated:", req.user.email);
        next();
    } catch (error) {
        console.log("Token verification failed:", error);
        res.status(401).json({ error: "Token verification failed" });
    }
};

export const restrictToLoggedUserOnly = (req, res, next) => {
    if (!req.user) {
        return res.status(401).json({ error: "login failure" });
    }
    next();
};