jwt-middleware-auth 2.1.3 → 2.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +46 -1
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -364,6 +364,50 @@ function canModifyConfirmed(user) {
|
|
|
364
364
|
return ['admin', 'SuperManager', 'manager'].includes(user.role);
|
|
365
365
|
}
|
|
366
366
|
|
|
367
|
+
/**
|
|
368
|
+
* Custom middleware that verifies either ownership OR admin/manager roles
|
|
369
|
+
* Allows product owner OR users with manager, SuperManager, admin roles to perform actions
|
|
370
|
+
* @param {string} secret - JWT secret key
|
|
371
|
+
* @param {Function} getOwnerIdFn - Function to get the resource owner ID
|
|
372
|
+
* @returns {Function} Express middleware function
|
|
373
|
+
*/
|
|
374
|
+
const verifyOwnershipOrAdminRoles = (secret, getOwnerIdFn) => {
|
|
375
|
+
return async (req, res, next) => {
|
|
376
|
+
try {
|
|
377
|
+
const token = req.headers['token'];
|
|
378
|
+
if (!token) {
|
|
379
|
+
return res.status(401).json({ error: 'Access denied. No token provided.' });
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const decoded = jwt.verify(token, secret);
|
|
383
|
+
req.user = decoded;
|
|
384
|
+
|
|
385
|
+
// Check if user has admin roles
|
|
386
|
+
const adminRoles = ['manager', 'SuperManager', 'admin'];
|
|
387
|
+
if (adminRoles.includes(decoded.role)) {
|
|
388
|
+
return next();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Check ownership
|
|
392
|
+
const ownerId = await getOwnerIdFn(req);
|
|
393
|
+
if (decoded.id !== ownerId.toString()) {
|
|
394
|
+
return res.status(403).json({ error: 'Access denied. You do not have permission to perform this action.' });
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
next();
|
|
398
|
+
} catch (error) {
|
|
399
|
+
if (error.name === 'JsonWebTokenError') {
|
|
400
|
+
return res.status(401).json({ error: 'Invalid token.' });
|
|
401
|
+
}
|
|
402
|
+
if (error.name === 'TokenExpiredError') {
|
|
403
|
+
return res.status(401).json({ error: 'Token expired.' });
|
|
404
|
+
}
|
|
405
|
+
res.status(500).json({ error: error.message });
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
|
|
367
411
|
module.exports = {
|
|
368
412
|
verifyToken,
|
|
369
413
|
authorizeRoles,
|
|
@@ -378,5 +422,6 @@ module.exports = {
|
|
|
378
422
|
verifyAdmin,
|
|
379
423
|
verifyTokenAndAuthorization,
|
|
380
424
|
verifyManager,
|
|
381
|
-
canModifyConfirmed
|
|
425
|
+
canModifyConfirmed,
|
|
426
|
+
verifyOwnershipOrAdminRoles
|
|
382
427
|
};
|