feat: added authetication middleware

This commit is contained in:
Sathishkumar Krishnan
2021-12-24 00:08:06 +05:30
parent e368a91630
commit 26c4c54114
4 changed files with 40 additions and 4 deletions

View File

@@ -0,0 +1,25 @@
const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("./env");
const User = require("./../models/User");
const authenticate = async (token) => {
const decodedToken = jwt.verify(token, JWT_SECRET);
if (decodedToken) {
return await User.findById(decodedToken.id);
}
};
module.exports = {
AuthenticateMiddleware: async (req, res, next) => {
try {
const token = req.headers.authorization || "";
if (token) {
const user = authenticate(token);
res.locals.user = user;
next();
}
} catch (error) {
res.status(401).send({ success: false, error: "Authentication Failed!" });
}
},
};