Skip to content

Auth and Middleware

All middleware lives in src/middleware/authMiddleware.js. Routes compose them depending on what access level they need.

MiddlewareWhat it does
protectVerifies the JWT Bearer token. Rejects with 401 if missing or invalid. Attaches req.user.
adminChecks req.user.role === "admin". Returns 403 if the user is not an admin.
publisherChecks req.user.role === "publisher". Returns 403 for non-publishers.
publisherGuardChecks that the publisher record exists and is approved. Returns 403 if not yet approved.
authenticateApiKeyReads x-api-key header or api_key query param. Validates against process.env.API_KEY.

Routes chain middleware before the controller function. A typical protected admin route looks like this:

// Only admins can create articles
router.post("/", protect, admin, createArticle);
// Publisher can only update their own feed
router.put("/me/feed", protect, publisher, publisherGuard, updateFeed);
// Child sites read via API key — no JWT needed
router.get("/posts", authenticateApiKey, getPosts);
ScenarioStatus
Missing or invalid JWT401 Unauthorized
Valid JWT but wrong role403 Forbidden
Publisher not yet approved403 Forbidden
Invalid or missing API key403 Forbidden