Optional
userIdParam: string = 'userId'Name of the URL parameter containing the resource owner's user ID
Express middleware function that validates resource ownership
// Protect user progress data
router.get('/users/:userId/progress',
authenticateToken,
requireOwnership('userId'),
progressController.getUserProgress
);
// Protect user profile updates
router.put('/users/:id/profile',
authenticateToken,
requireOwnership('id'),
userController.updateProfile
);
// Custom parameter name for ownership validation
router.get('/profiles/:profileUserId/settings',
authenticateToken,
requireOwnership('profileUserId'),
profileController.getSettings
);
// Admin override allows access to any resource
router.get('/users/:userId/progress',
authenticateToken,
requireOwnership('userId'), // Admins can access any user's progress
progressController.getUserProgress
);
// Typical usage pattern for user-specific endpoints
router.delete('/users/:userId/data',
authenticateToken,
requireOwnership('userId'),
(req, res) => {
// User can only delete their own data
// Admins can delete any user's data
deleteUserData(req.params.userId);
res.json({ success: true });
}
);
Resource Ownership Validation Middleware Factory
Creates middleware that enforces resource ownership by ensuring users can only access resources that belong to them. This middleware compares the authenticated user's ID with a user ID parameter in the request URL to validate ownership.
The middleware includes an admin override that allows administrators to access any resource regardless of ownership, providing necessary administrative capabilities while maintaining security for regular users.
This middleware is essential for protecting user-specific data such as progress tracking, personal profiles, and private content. It prevents users from accessing other users' sensitive information through URL manipulation.