(_?: never)
| 24 | } |
| 25 | |
| 26 | export default function integrationMiddleware(_?: never) { |
| 27 | return async (req: AuthedRequestWithTenant, _: any, next: NextFunction) => { |
| 28 | try { |
| 29 | const internalApiKeyRaw = getInternalApiKey(req); |
| 30 | const apiKeyRaw = getApiKey(req); |
| 31 | if (!internalApiKeyRaw && !apiKeyRaw) { |
| 32 | return next(new Unauthorized()); |
| 33 | } |
| 34 | |
| 35 | if (internalApiKeyRaw) { |
| 36 | if (!process.env.INTERNAL_API_KEY) { |
| 37 | return next(new Error()); |
| 38 | } |
| 39 | if (process.env.INTERNAL_API_KEY !== internalApiKeyRaw) { |
| 40 | return next(new Unauthorized()); |
| 41 | } |
| 42 | return next(); |
| 43 | } |
| 44 | |
| 45 | if (apiKeyRaw) { |
| 46 | const apiKey = await ApiKeysService.getAccountByApiKey({ |
| 47 | apiKey: apiKeyRaw, |
| 48 | }); |
| 49 | if (!apiKey) { |
| 50 | return next(new Unauthorized()); |
| 51 | } |
| 52 | // we could validate scope here |
| 53 | req.tenant = apiKey.account; |
| 54 | if (!req.tenant) { |
| 55 | return next(new Forbidden()); |
| 56 | } |
| 57 | req.tenant_api = { |
| 58 | id: apiKey.id, |
| 59 | name: apiKey.name, |
| 60 | scope: apiKey.scope || {}, |
| 61 | }; |
| 62 | return next(); |
| 63 | } |
| 64 | |
| 65 | return next(new Error()); |
| 66 | } catch (error) { |
| 67 | console.error(stringify(error)); |
| 68 | return next(new Unauthorized()); |
| 69 | } |
| 70 | }; |
| 71 | } |
no test coverage detected