File size: 984 Bytes
74bfb65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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;