powr-sdk-api
Version:
Shared API core library for PowrStack projects
76 lines (68 loc) • 2.07 kB
JavaScript
;
const jwt = require("jsonwebtoken");
const generateToken = user => {
return jwt.sign({
userId: user.userId
}, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN || '24h'
});
};
const validateToken = async (req, res, next) => {
try {
let token;
// Check if token exists in headers
if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")) {
token = req.headers.authorization.split(" ")[1];
}
if (!token) {
return res.error("Not authorized to access this route", 401);
}
try {
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// // Get user from token
// const user = await User.findByPk(decoded.userId);
// if (!user) {
// return res.error('User not found', 401);
// }
// // Add user and userId to request object
// req.user = user;
req.userId = decoded.userId;
next();
} catch (error) {
return res.error("Not authorized to access this route", 401, error);
}
} catch (error) {
return res.error("Error authenticating user", 500, error);
}
};
const validateAuth = (options = {}) => {
const {
publicPaths = ["/auth", "/", "/status", "/swagger"],
publicMethods = ["OPTIONS"]
} = options;
return async (req, res, next) => {
// Skip auth validation for public paths
if (publicPaths.some(path => req.path.startsWith(path))) {
return next();
}
// Skip auth validation for public methods
if (publicMethods.includes(req.method)) {
return next();
}
// Use the original validateToken middleware for protected routes
return validateToken(req, res, next);
};
};
// exports.authorize = (...roles) => {
// return (req, res, next) => {
// if (!roles.includes(req.user.role)) {
// return res.error(`User role ${req.user.role} is not authorized to access this route`, 403);
// }
// next();
// };
// };
module.exports = {
validateAuth,
generateToken
};