* @param {*} req require('express').Request * @param {*} res require('express').Response * @param {['POST'|'GET']} opt_validMethods * @param {string[]=} opt_exposeHeaders
(req, res, opt_validMethods, opt_exposeHeaders)
| 15 | * @param {string[]=} opt_exposeHeaders |
| 16 | */ |
| 17 | function assertCors(req, res, opt_validMethods, opt_exposeHeaders) { |
| 18 | // Allow disable CORS check (iframe fixtures have origin 'about:srcdoc'). |
| 19 | if (req.query.cors == '0') { |
| 20 | return; |
| 21 | } |
| 22 | |
| 23 | const validMethods = opt_validMethods || ['GET', 'POST', 'OPTIONS']; |
| 24 | const invalidMethod = req.method + ' method is not allowed. Use POST.'; |
| 25 | const invalidOrigin = 'Origin header is invalid.'; |
| 26 | const unauthorized = 'Unauthorized Request'; |
| 27 | let origin; |
| 28 | |
| 29 | if (validMethods.indexOf(req.method) == -1) { |
| 30 | res.statusCode = 405; |
| 31 | res.end(JSON.stringify({message: invalidMethod})); |
| 32 | throw invalidMethod; |
| 33 | } |
| 34 | |
| 35 | if (req.headers.origin) { |
| 36 | origin = req.headers.origin; |
| 37 | if (!ORIGIN_REGEX.test(req.headers.origin)) { |
| 38 | res.statusCode = 403; |
| 39 | res.end(JSON.stringify({message: invalidOrigin})); |
| 40 | throw invalidOrigin; |
| 41 | } |
| 42 | } else if (req.headers['amp-same-origin'] == 'true') { |
| 43 | origin = getUrlPrefix(req); |
| 44 | } else { |
| 45 | res.statusCode = 403; |
| 46 | res.end(JSON.stringify({message: unauthorized})); |
| 47 | throw unauthorized; |
| 48 | } |
| 49 | |
| 50 | enableCors(req, res, origin, opt_exposeHeaders); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * @param {*} req require('express').Request |
nothing calls this directly
no test coverage detected