I am a newbie in MERN stack. I am building a forum and I want only logged in user to like and comment post. But I keep getting jsonwebtokenError: jwt malformed.
please help I don't know what to do again as I am totally confused. below is the middleware
import jwt from "jsonwebtoken";
const auth = async (req, res, next) => {
try {
console.log(req.headers)
const token = req.headers.authorization.split('')[1];
const isCustomAuth = token.length < 500;
let decodedData;
if(token && isCustomAuth) {
decodedData = jwt.verify(token, "TEST");
req.userId = decodedData?.id;
} else {
decodedData = jwt.decode(token);
req.userId = decodedData.sub;
// console.log("hello")
}
next();
}
catch (error) {
console.log(error)
}
}
export default auth;
Below is the code for signin and signup
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import User from "../models/user.js";
export const signin = async (req, res) => {
const { email, password } = req.body;
try {
const existingUser = await User.findOne({ email });
if(!existingUser) return res.status(404).json({ message : "User doesn't exist"});
const isCorrectPassword = await bcrypt.compare(password, existingUser.password);
if(!isCorrectPassword) return res.status(400).json({ message: "Invalid credentials"});
const token = jwt.sign({ email: existingUser.email, id: existingUser._id}, "TEST", {expiresIn: "1h"});
res.status(200).json({result: existingUser, token})
} catch (error) {
res.status(500).json({message: 'Something Went wrong'})
}
}
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName} = req.body;
try {
const existingUser = await User.findOne({ email });
if(existingUser) return res.status(404).json({ message : "User already exist"});
if(password !== confirmPassword) return res.status(404).json({ message : "Password do not match"});
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({ email, password: hashedPassword, firstName, lastName});
const token = jwt.sign({ email: result.email, id: result._id}, "TEST", {expiresIn: "1h"});
res.status(200).json({result, token})
} catch (error) {
console.log('error', error)
res.status(500).json({message: 'Something Went wrong'});
}
}
The error am getting is below
{
host: 'localhost:5000',
connection: 'keep-alive',
'sec-ch-ua': '"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
accept: 'application/json, text/plain, */*',
authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im9kdW5AZ21haWwuY29tIiwiaWQiOiI2MzFlMzk3NDRhZmQ5YjBjMmZhZjllM2QiLCJpYXQiOjE2NjI5MzEwODUsImV4cCI6MTY2MjkzNDY4NX0.MD6kwkHc7tMo7G_o7N6Do8i3SFGD6mb8JVp3ePSdTMw',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
'sec-ch-ua-platform': '"Windows"',
origin: 'http://localhost:3000',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:3000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9'
}
JsonWebTokenError: jwt malformed
at Object.module.exports [as verify] (C:\Users\user\Desktop\TemmyProject\Inspiredformen\server\node_modules\jsonwebtoken\verify.js:63:17)
at auth (file:///C:/Users/user/Desktop/TemmyProject/Inspiredformen/server/middleware/auth.js:12:27)