estatesfunding/ef-api/middleware/auth.js

36 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2024-09-12 08:11:07 +00:00
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
dotenv.config();
2024-10-25 05:34:27 +00:00
const secret = process.env.SECRET_KEY;
2024-09-12 08:11:07 +00:00
const auth = async (req, res, next) => {
try {
2024-10-25 05:34:27 +00:00
// Check if the authorization header exists
if (!req.headers.authorization) {
2024-09-15 08:11:03 +00:00
return res.status(401).json({ message: "Authorization header missing" });
}
2024-10-25 05:34:27 +00:00
const token = req.headers.authorization.split(" ")[1]; // Extract the token from 'Bearer <token>'
const isCustomAuth = token.length < 500; // Check if it's a custom JWT or a third-party auth
2024-09-12 08:11:07 +00:00
let decodedData;
2024-10-25 05:34:27 +00:00
2024-09-12 08:11:07 +00:00
if (token && isCustomAuth) {
2024-10-25 05:34:27 +00:00
decodedData = jwt.verify(token, secret); // Verify the custom JWT
req.userId = decodedData?.id; // Set the user ID to request object
2024-09-12 08:11:07 +00:00
} else {
2024-10-25 05:34:27 +00:00
decodedData = jwt.decode(token); // Decode third-party tokens (e.g., Google OAuth)
req.userId = decodedData?.sub; // Usually for third-party tokens, user ID is in `sub`
2024-09-12 08:11:07 +00:00
}
2024-10-25 05:34:27 +00:00
next(); // Continue to the next middleware or route handler
2024-09-12 08:11:07 +00:00
} catch (error) {
console.log(error);
2024-10-25 05:34:27 +00:00
res.status(403).json({ message: "Authentication failed" });
2024-09-12 08:11:07 +00:00
}
};
export default auth;