-
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathmiddleware.ts
More file actions
55 lines (50 loc) · 1.66 KB
/
middleware.ts
File metadata and controls
55 lines (50 loc) · 1.66 KB
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
import muid from 'uuid-mongodb'
import { Request } from 'express'
import { AuthUserType } from '../types.js'
import { verifyJWT } from './util.js'
import { logger } from '../logger.js'
export interface CustomContext {
user: AuthUserType
token?: string
}
const EMTPY_USER: AuthUserType = {
isBuilder: false,
roles: [],
uuid: undefined
}
/**
* Create a middleware context for Apollo server
*/
export const createContext = async ({ req }: { req: Request }): Promise<CustomContext> => {
try {
return await validateTokenAndExtractUser(req)
} catch (e) {
logger.error(`Can't validate token and extract user ${e.toString() as string}`)
throw new Error('An unexpected error has occurred. Please notify us at support@openbeta.io.')
}
}
async function validateTokenAndExtractUser (req: Request): Promise<CustomContext> {
const { headers } = req
// eslint-disable-next-line @typescript-eslint/dot-notation
const authHeader = String(headers?.['authorization'] ?? '')
if (authHeader.startsWith('Bearer ')) {
const token = authHeader.substring(7, authHeader.length).trim()
try {
const payload = await verifyJWT(token)
return {
user: {
isBuilder: payload?.scope?.includes('builder:default') ?? false,
roles: payload?.['https://tacos.openbeta.io/roles'] ?? [],
uuid: payload?.['https://tacos.openbeta.io/uuid'] != null ? muid.from(payload['https://tacos.openbeta.io/uuid']) : undefined
},
token
}
} catch (e) {
logger.error(`Can't verify JWT token ${e.toString() as string}`)
throw new Error("Unauthorized. Can't verify JWT token")
}
}
return {
user: EMTPY_USER
}
}