Implement Resource Ownership Checks

A common security mistake is assuming that any authenticated user can access any resource.

For example, if John is logged in, he should not automatically be allowed to update Sarah's profile.

This is an object-level authorization problem.

The backend must verify whether:

  • The authenticated user owns the requested resource.
  • Or the authenticated user has an administrator role.

For user-specific operations, compare req.user._id with the requested resource ID.

Never rely on frontend visibility controls to enforce authorization.

Prevent Insecure Direct Object References

Always verify resource ownership on the server. Knowing another user's MongoDB ID must never be enough to access or modify their private information.

Ownership Authorization Middleware
import { AppError } from '../utils/app-error.js';

export function authorizeUserOrAdmin(req, res, next) {
  const isOwner = req.user._id.toString() === req.params.id;
  const isAdmin = req.user.role === 'admin';

  if (!isOwner && !isAdmin) {
    return next(new AppError('Access denied', 403));
  }

  next();
}

Allows access when the authenticated user owns the resource or has the administrator role.

Key Takeaways
  • Authentication does not guarantee resource access.

  • Verify resource ownership for user-specific operations.

  • Enforce authorization on every protected endpoint.