-
Notifications
You must be signed in to change notification settings - Fork 117
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #917 from haseebzaki-07/new_branch_6
Add Authentication checks for AGRO-rent services
- Loading branch information
Showing
4 changed files
with
39 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,31 @@ | ||
const jwt = require('jsonwebtoken'); | ||
const jwt = require("jsonwebtoken"); | ||
|
||
const authMiddleware = (req, res, next) => { | ||
const token = req.headers.authorization?.split(' ')[1]; | ||
if (!token) return res.status(403).json({ message: "No token provided" }); | ||
const token = req.headers.authorization?.split(" ")[1]; | ||
|
||
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => { | ||
if (err) return res.status(401).json({ message: "Unauthorized" }); | ||
if (!token) { | ||
console.error("Authorization token missing from request headers"); | ||
return res.status(403).json({ message: "No token provided" }); | ||
} | ||
|
||
req.user = decoded; | ||
next(); | ||
}); | ||
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => { | ||
if (err) { | ||
console.error(`JWT verification failed: ${err.message}`, { token }); | ||
|
||
if (err.name === "TokenExpiredError") { | ||
return res.status(401).json({ message: "Token has expired" }); | ||
} | ||
if (err.name === "JsonWebTokenError") { | ||
return res.status(401).json({ message: "Invalid token" }); | ||
} | ||
|
||
return res.status(401).json({ message: "Unauthorized" }); | ||
} | ||
|
||
req.user = decoded; | ||
|
||
next(); | ||
}); | ||
}; | ||
|
||
module.exports = authMiddleware; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters