Taha Saif
Deploy Ecom Hub API backend (Express + Drizzle + Clerk + R2)
74bfb65
Raw History Blame Contribute Delete
984 Bytes
import { Router } from 'express';
import { clerkClient, getAuth } from '@clerk/express';
import { adminArticlesRouter } from './articles';
const router = Router();
// This guard applies to every current and future /api/admin endpoint.
router.use(async (req, res, next) => {
res.setHeader('Cache-Control', 'no-store');
const { userId } = getAuth(req);
if (!userId) {
res.status(401).json({ error: 'Sign in to continue.' });
return;
}
try {
const user = await clerkClient.users.getUser(userId);
if (user.publicMetadata.role !== 'admin') {
res.status(403).json({ error: 'This account does not have admin access.' });
return;
}
res.locals.admin = { role: 'admin', userId: user.id };
next();
} catch {
res.status(503).json({ error: 'Admin access could not be checked. Please try again.' });
}
});
router.get('/access', (_req, res) => {
res.json(res.locals.admin);
});
router.use(adminArticlesRouter);
export default router;