In this lesson, you will learn how to implement "Resource Ownership Logic" to ensure that users can only access or modify data that belongs to them.
The Principle of Ownership
When building multi-user applications, it isn't enough to check if a user is logged in (Authentication) or has the right role (Authorization). You must also verify if the user has a proprietary relationship with the specific database record they are trying to access. Without this, a user could manipulate another user's data simply by changing an ID in an API request—a common security vulnerability known as Insecure Direct Object Reference (IDOR).
Implementing the Guard
The most robust place to enforce this logic is within your Service Layer. By the time a request reaches your business logic, you should have the user's userId (via your Request Context Propagation) and the requested entityId.
Instead of fetching the resource by ID alone, you fetch it by a composite filter that includes the owner:
// Service Layer Implementation
async function getOrderDetails(orderId, currentUserId) {
// Use the Repository Pattern to enforce ownership at the database level
const order = await orderRepository.findOne({
id: orderId,
ownerId: currentUserId // The "Guard" logic
});
if (!order) {
// Standardized Error Mapping prevents leaking existence of other users' records
throw new Error('RESOURCE_NOT_FOUND');
}
return order;
}
Why This Matters
By embedding ownership checks directly into your query logic, you eliminate the possibility of data leakage. Even if a user attempts to guess an orderId that belongs to someone else, the repository will return null because the database query strictly requires that the ownerId match the authenticated user. This approach keeps your security concerns tightly coupled to your data retrieval, ensuring that privacy is enforced at the source rather than as an afterthought in your routes or controllers.
Key Takeaway: Never fetch a resource by ID without simultaneously validating that the resource's owner matches the current authenticated user identity.