slicing Bearer from the prepend of the token if it exists
This commit is contained in:
@@ -1,18 +1,24 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const verifyToken = (req, res, next) => {
|
||||
const token = req.header("Authorization");
|
||||
let token = req.header("Authorization");
|
||||
|
||||
if (!token) {
|
||||
return res.status(403).send("A token is required for authentication");
|
||||
return res.status(403).json({ error: "A token is required for authentication" });
|
||||
}
|
||||
|
||||
if (token.startsWith("Bearer ")) {
|
||||
token = token.slice(7, token.length);
|
||||
}
|
||||
|
||||
try {
|
||||
const jwtSecretKey = process.env.JWT_SECRET_KEY || "default_secret_key";
|
||||
const decoded = jwt.verify(token.replace("Bearer ", ""), jwtSecretKey);
|
||||
|
||||
const decoded = jwt.verify(token, jwtSecretKey);
|
||||
req.user = decoded;
|
||||
|
||||
} catch (err) {
|
||||
return res.status(401).send("Invalid Token");
|
||||
return res.status(401).json({ error: "Invalid token" });
|
||||
}
|
||||
|
||||
return next();
|
||||
|
||||
Reference in New Issue
Block a user