Solution: Add Authorization to a Route Handler
Understand how to apply the decorator pattern to add authorization in Node.js route handlers. Learn to separate authentication logic from business code by creating a wrapper that checks user roles and restricts access, ensuring cleaner and more maintainable endpoint handlers.
We'll cover the following...
We'll cover the following...
Solution explanation
Lines 2–4: We define
deleteUserHandler, a mock route handler that returns a confirmation string. It doesn’t know anything about authentication or roles—that’s intentional.Lines 7–16: We build the
withAuthorizationdecorator:It wraps the original function
fn.It checks whether the
userargument has a role of'admin'. ...