Created
March 5, 2019 05:34
-
-
Save kamleshchandnani/04014dcc134327c20957811c5e0519fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logger from 'utils/logger'; | |
const allowedOrigins = [ | |
__CONFIG__.hostUrl, | |
`${__CONFIG__.hostUrl.replace('-', '--').replace('.', '-')}.cdn.ampproject.org`, | |
`${__CONFIG__.hostUrl}.amp.cloudflare.com`, | |
'https://cdn.ampproject.org', | |
]; | |
const corsMiddlewareAmp = (req, res, next) => { | |
if (__STAGE__ !== 'staging' && __STAGE__ !== 'production') { | |
logger.info('[corsMiddlewareAmp] bypassing since __STAGE__:', __STAGE__); | |
return next(); | |
} | |
let origin = ''; | |
const ampSourceOrigin = req.query.__amp_source_origin; | |
if (!ampSourceOrigin) { | |
logger.info('[corsMiddlewareAmp] no ampSourceOrigin', ampSourceOrigin); | |
return next(); | |
} | |
if (req.header('Amp-Same-Origin') === 'true') { | |
origin = ampSourceOrigin; | |
logger.info('[corsMiddlewareAmp] Amp-Same-Origin is true'); | |
} else if ( | |
allowedOrigins.includes(req.header('Origin')) && | |
ampSourceOrigin === __CONFIG__.hostUrl | |
) { | |
origin = req.header('Origin'); | |
logger.info('[corsMiddlewareAmp] Orign is not Host', origin, __CONFIG__.hostUrl); | |
} else { | |
logger.info('[corsMiddlewareAmp] cors validation failure'); | |
return res.sendStatus(401); | |
} | |
logger.info('[corsMiddlewareAmp] cors validation success'); | |
res.header('Access-Control-Allow-Credentials', 'true'); | |
res.header('Access-Control-Allow-Origin', origin); | |
res.header('AMP-Access-Control-Allow-Source-Origin', ampSourceOrigin); | |
res.header('Access-Control-Expose-Headers', 'AMP-Access-Control-Allow-Source-Origin'); | |
return next(); | |
}; | |
export default corsMiddlewareAmp; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment