Skip to content

Update validateTokenHandler.js #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 23 additions & 17 deletions middleware/validateTokenHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,30 @@ const asyncHandler = require("express-async-handler");
const jwt = require("jsonwebtoken");

const validateToken = asyncHandler(async (req, res, next) => {
let token;
let authHeader = req.headers.Authorization || req.headers.authorization;

if (!authHeader || !authHeader.startsWith("Bearer")) {
res.status(401);
throw new Error("User not authorized or token missing");
}

let token;
let authHeader = req.headers.Authorization || req.headers.authorization;
let storedToken = req.cookies?.jwt; // Handle token from cookies

// Check if the token is in the authorization header or cookies
if (authHeader && authHeader.startsWith("Bearer")) {
token = authHeader.split(" ")[1];

jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
res.status(401);
throw new Error("User not authorized!");
}
req.user = decoded.user;
next();
});
} else if (storedToken) {
token = storedToken;
}

// If no token is found, respond with an error
if (!token) {
return res.status(401).json({ message: 'User is not authorized or token is missing' });
}

// Verify the token
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
return res.status(401).json({ message: 'User is not authorized' });
}
req.user = decoded.user;
next();
});
});

module.exports = validateToken;