| 43 | * @returns {Promise<{isValid: boolean, apiKey?: ApiKey}>} |
| 44 | */ |
| 45 | export const validateAPIKey = async (req: Request): Promise<{ isValid: boolean; apiKey?: ApiKey }> => { |
| 46 | const authorizationHeader = (req.headers['Authorization'] as string) ?? (req.headers['authorization'] as string) ?? '' |
| 47 | if (!authorizationHeader) return { isValid: false } |
| 48 | |
| 49 | const suppliedKey = authorizationHeader.split(`Bearer `).pop() |
| 50 | if (!suppliedKey) return { isValid: false } |
| 51 | |
| 52 | try { |
| 53 | const apiKey = await apikeyService.getApiKey(suppliedKey) |
| 54 | if (!apiKey) return { isValid: false } |
| 55 | |
| 56 | const apiKeyWorkSpaceId = apiKey.workspaceId |
| 57 | if (!apiKeyWorkSpaceId) return { isValid: false } |
| 58 | |
| 59 | const apiSecret = apiKey.apiSecret |
| 60 | if (!apiSecret || !compareKeys(apiSecret, suppliedKey)) { |
| 61 | return { isValid: false, apiKey } |
| 62 | } |
| 63 | |
| 64 | return { isValid: true, apiKey } |
| 65 | } catch (error) { |
| 66 | return { isValid: false } |
| 67 | } |
| 68 | } |