Initial commit
This commit is contained in:
43
server/middleware/authMiddleware.js
Normal file
43
server/middleware/authMiddleware.js
Normal file
@@ -0,0 +1,43 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const User = require('../models/User');
|
||||
const { errorResponse } = require('../utils/apiResponse');
|
||||
|
||||
const protect = async (req, res, next) => {
|
||||
let token;
|
||||
|
||||
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
|
||||
token = req.headers.authorization.split(' ')[1];
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
return errorResponse(res, 'Not authorized to access this route', [], 401);
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'guitar_ecommerce_super_secret_jwt_key_2026');
|
||||
req.user = await User.findById(decoded.id).select('-password');
|
||||
if (!req.user) {
|
||||
return errorResponse(res, 'User account no longer exists', [], 401);
|
||||
}
|
||||
next();
|
||||
} catch (error) {
|
||||
return errorResponse(res, 'Not authorized, token failed or expired', [], 401);
|
||||
}
|
||||
};
|
||||
|
||||
const authorize = (...roles) => {
|
||||
return (req, res, next) => {
|
||||
if (!req.user || !roles.includes(req.user.role)) {
|
||||
return errorResponse(
|
||||
res,
|
||||
`User role '${req.user ? req.user.role : 'Guest'}' is not authorized to access this resource`,
|
||||
[],
|
||||
403
|
||||
);
|
||||
}
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = { protect, authorize };
|
||||
|
||||
Reference in New Issue
Block a user