CSE316/final/server/auth/index.js

35 lines
794 B
JavaScript
Raw Permalink Normal View History

2022-05-23 06:22:34 -04:00
const jwt = require("jsonwebtoken")
function authManager() {
verify = function (req, res, next) {
try {
const token = req.cookies.token;
if (!token) {
req.userId = 'Guest';
}
else {
const verified = jwt.verify(token, process.env.JWT_SECRET)
req.userId = verified.userId;
}
next();
} catch (err) {
console.error(err);
return res.status(401).json({
errorMessage: "Unauthorized"
});
}
}
signToken = function (user) {
return jwt.sign({
userId: user._id
}, process.env.JWT_SECRET);
}
return this;
}
const auth = authManager();
module.exports = auth;