-
Notifications
You must be signed in to change notification settings - Fork 8
/
middleware.ts
57 lines (48 loc) · 1.62 KB
/
middleware.ts
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { TokenPayload } from "./index";
import { TEST_USER } from "./helpers";
const whitelist = [
{ method: 'GET', route: '/proposals' },
{ method: 'GET', route: '/health' },
];
async function clerkAuth(req: Request, res: Response, next: NextFunction) {
// Bypass token auth for tests
if (process.env.NODE_ENV === 'test') {
req.user = TEST_USER;
return next();
}
const token = req.headers.authorization?.replace("Bearer ", "");
const base64Key = process.env.CLERK_JWT_KEY as string;
const publicKey = Buffer.from(base64Key, 'base64').toString('ascii');
const isWhitelisted = whitelist.some(
(item) => item.method === req.method && item.route === req.path
);
if (isWhitelisted && !token) {
req.user = {} as TokenPayload;
return next();
}
if (token === undefined) {
return res.status(401).json({ message: "not signed in" });
}
try {
const decoded = jwt.verify(token, publicKey) as TokenPayload;
req.user = decoded;
next();
} catch (error) {
return res.status(400).json({ error });
}
}
async function logRequest(req: Request, res: Response, next: NextFunction) {
if (process.env.LOG_REQUESTS) {
console.log(`
${req.method} /${req.url}
Body: ${JSON.stringify(req.body, null, 2)}
`);
}
if (process.env.LOG_REQ_HEADERS === 'true') {
console.log(`Headers: ${JSON.stringify(req.headers, null, 2)}`);
}
next()
}
export { logRequest, clerkAuth };