|
| 1 | +const Problem = require('api-problem'); |
| 2 | +const { validate: uuidValidate } = require('uuid'); |
| 3 | + |
| 4 | +const formService = require('../../../../forms/form/service'); |
| 5 | +const { parseBasicPair } = require('../../../../runtime-auth/security/auth/utils/basicAuth'); |
| 6 | +const { validateApiKey } = require('../../../../runtime-auth/security/auth/utils/apiKeyValidation'); |
| 7 | + |
| 8 | +const HTTP_401_DETAIL = 'Invalid authorization credentials.'; |
| 9 | + |
| 10 | +module.exports = async (req, res, next) => { |
| 11 | + try { |
| 12 | + const authz = req.headers?.authorization || ''; |
| 13 | + if (!/^Basic\s+/i.test(authz)) { |
| 14 | + throw new Problem(401, { detail: HTTP_401_DETAIL }); |
| 15 | + } |
| 16 | + |
| 17 | + const formIdParam = req.params.formId; |
| 18 | + if (!uuidValidate(formIdParam)) { |
| 19 | + throw new Problem(400, { detail: `Bad formId "${formIdParam}".` }); |
| 20 | + } |
| 21 | + |
| 22 | + const pair = parseBasicPair(authz); |
| 23 | + if (!pair) { |
| 24 | + throw new Problem(401, { detail: HTTP_401_DETAIL }); |
| 25 | + } |
| 26 | + |
| 27 | + const { formId, apiKey } = pair; |
| 28 | + if (formId !== formIdParam) { |
| 29 | + throw new Problem(401, { detail: HTTP_401_DETAIL }); |
| 30 | + } |
| 31 | + |
| 32 | + const apiKeyRecord = await formService.readApiKey(formId); |
| 33 | + validateApiKey(apiKey, apiKeyRecord); |
| 34 | + |
| 35 | + req.apiUser = true; |
| 36 | + next(); |
| 37 | + } catch (error) { |
| 38 | + if (error.status === 400) { |
| 39 | + next(error); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + next(new Problem(401, { detail: HTTP_401_DETAIL })); |
| 44 | + } |
| 45 | +}; |
0 commit comments