Search⌘ K
AI Features

Solution: Enforce Role-Based Access on Service Methods

Understand how to implement role-based access control on service methods by using the Proxy pattern in Node.js. This lesson teaches you to wrap an existing service with a Proxy that intercepts method calls, enforcing permissions for admin-only actions while allowing unrestricted access to other methods, improving security without altering the original service code.

Solution explanation

  • Lines 2–10: We define the UserService class, which exposes two methods: getUser() for general data access, and deleteUser() for administrative actions.

    • This represents a real backend service with both safe and restricted operations.

    • Our goal is to protect certain methods without editing this class.

  • Lines 13–33: The createSecureService() function creates a Proxy that enforces method-level access control.

    • The variable restrictedMethods defines which methods require admin privileges. ...