Problem: Add Authorization to a Route Handler
Problem statement
You’re working on a mock Express-like route handler that should only allow admin users to access certain endpoints. Currently, every handler performs the same manual check, cluttering your business logic. You’d want to refactor this so the role validation happens outside the handler, using a decorator. This keeps our core handler clean while centralizing authorization rules.
Goal
Create a withAuthorization decorator that:
Takes a handler function as input.
Checks whether the
userobject passed in has aroleof'admin'.If authorized, runs the original handler.
If not, logs
[AUTH] Access deniedand returns{ status: 403, message: 'Forbidden' }.
Constraints
Do not modify the original route handler.
Do not add the authorization logic inside the handler.
The decorator must return a new function.
Assume each handler receives a
userobject as its first argument.
Sample output
The examples below illustrate what the output should look like:
const adminHandler = withAuthorization(deleteUserHandler);console.log(adminHandler({ role: 'admin' }, 5)); // should succeed/* Expected output[AUTH] Access granted to admin[OK] User 5 deleted */console.log(adminHandler({ role: 'guest' }, 5)); // should be forbidden/* Expected output[AUTH] Access denied{ status: 403, message: 'Forbidden' } */
Good luck trying the problem! If you’re unsure how to proceed, check the “Solution” tab above.
Problem: Add Authorization to a Route Handler
Problem statement
You’re working on a mock Express-like route handler that should only allow admin users to access certain endpoints. Currently, every handler performs the same manual check, cluttering your business logic. You’d want to refactor this so the role validation happens outside the handler, using a decorator. This keeps our core handler clean while centralizing authorization rules.
Goal
Create a withAuthorization decorator that:
Takes a handler function as input.
Checks whether the
userobject passed in has aroleof'admin'.If authorized, runs the original handler.
If not, logs
[AUTH] Access deniedand returns{ status: 403, message: 'Forbidden' }.
Constraints
Do not modify the original route handler.
Do not add the authorization logic inside the handler.
The decorator must return a new function.
Assume each handler receives a
userobject as its first argument.
Sample output
The examples below illustrate what the output should look like:
const adminHandler = withAuthorization(deleteUserHandler);console.log(adminHandler({ role: 'admin' }, 5)); // should succeed/* Expected output[AUTH] Access granted to admin[OK] User 5 deleted */console.log(adminHandler({ role: 'guest' }, 5)); // should be forbidden/* Expected output[AUTH] Access denied{ status: 403, message: 'Forbidden' } */
Good luck trying the problem! If you’re unsure how to proceed, check the “Solution” tab above.