Auth and Middleware
All middleware lives in src/middleware/authMiddleware.js. Routes compose them depending on what access level they need.
The Three Middleware Types
Section titled “The Three Middleware Types”| Middleware | What it does |
|---|---|
protect | Verifies the JWT Bearer token. Rejects with 401 if missing or invalid. Attaches req.user. |
admin | Checks req.user.role === "admin". Returns 403 if the user is not an admin. |
publisher | Checks req.user.role === "publisher". Returns 403 for non-publishers. |
publisherGuard | Checks that the publisher record exists and is approved. Returns 403 if not yet approved. |
authenticateApiKey | Reads x-api-key header or api_key query param. Validates against process.env.API_KEY. |
How Routes Apply Middleware
Section titled “How Routes Apply Middleware”Routes chain middleware before the controller function. A typical protected admin route looks like this:
// Only admins can create articlesrouter.post("/", protect, admin, createArticle);
// Publisher can only update their own feedrouter.put("/me/feed", protect, publisher, publisherGuard, updateFeed);
// Child sites read via API key — no JWT neededrouter.get("/posts", authenticateApiKey, getPosts);Error Responses
Section titled “Error Responses”| Scenario | Status |
|---|---|
| Missing or invalid JWT | 401 Unauthorized |
| Valid JWT but wrong role | 403 Forbidden |
| Publisher not yet approved | 403 Forbidden |
| Invalid or missing API key | 403 Forbidden |