2024-09-12 08:11:07 +00:00
|
|
|
import jwt from "jsonwebtoken";
|
|
|
|
import UserModel from "../models/user.js"
|
|
|
|
import dotenv from "dotenv";
|
|
|
|
|
|
|
|
dotenv.config();
|
|
|
|
|
|
|
|
const secret = process.env.SECRET_KEY
|
|
|
|
|
|
|
|
const auth = async (req, res, next) => {
|
|
|
|
try {
|
2024-09-15 08:11:03 +00:00
|
|
|
|
|
|
|
// Check if the authorization header exists
|
|
|
|
if (!req.headers.authorization) {
|
|
|
|
return res.status(401).json({ message: "Authorization header missing" });
|
|
|
|
}
|
|
|
|
|
2024-09-12 08:11:07 +00:00
|
|
|
const token = req.headers.authorization.split(" ")[1];
|
|
|
|
const isCustomAuth = token.length < 500;
|
|
|
|
let decodedData;
|
|
|
|
if (token && isCustomAuth) {
|
|
|
|
decodedData = jwt.verify(token, secret);
|
|
|
|
req.userId = decodedData?.id;
|
|
|
|
} else {
|
|
|
|
decodedData = jwt.decode(token);
|
|
|
|
// const googleId = decodedData?.sub.toString();
|
|
|
|
// const user = await UserModel.findOne({ googleId });
|
|
|
|
// req.userId = user?._id;
|
|
|
|
req.userId = decodedData?.id;
|
|
|
|
}
|
|
|
|
next();
|
|
|
|
} catch (error) {
|
|
|
|
console.log(error);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
export default auth;
|