Created
February 14, 2022 11:46
-
-
Save regeda/9ddcd7f9e8abca4d921a8c5401ff546e to your computer and use it in GitHub Desktop.
Allow origin function for AWS CloudFront
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
function allowOriginFunc(allowOrigins) { | |
if (allowOrigins.length == 0) { | |
return function(o) { return true; }; | |
} | |
var origins = [], wildcards = []; | |
allowOrigins.forEach(function(o) { | |
var i = o.indexOf('*'); | |
if (i == -1) { | |
origins.push(o) | |
} else { | |
wildcards.push([ | |
o.substring(0, i), // prefix | |
o.substring(i+1), // suffix | |
]); | |
} | |
}) | |
return function(o) { | |
if (!o) { return false; } | |
for (var i = 0; i < origins.length; i++) { | |
if (origins[i] == o) { | |
return true; | |
} | |
} | |
for (var i = 0; i < wildcards.length; i++) { | |
if (o.hasPrefix(wildcards[i][0]) && o.hasSuffix(wildcards[i][1])) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
} | |
String.prototype.hasPrefix = function(s) { | |
return this.indexOf(s) == 0; | |
} | |
String.prototype.hasSuffix = function(s) { | |
return this.indexOf(s, -1) == (this.length - s.length); | |
} | |
// configure allow origins | |
var allowOrigin = allowOriginFunc([ | |
"https://*.example2.io", | |
"https://example.io", | |
"http://localhost:*", | |
]); | |
function handler(event) { | |
var request = event.request; | |
var response = event.response; | |
if (!response.headers['access-control-allow-origin']) { | |
var origin = request.headers['origin'] || {}; | |
if (allowOrigin(origin.value)) { | |
response.headers['access-control-allow-origin'] = origin; | |
} | |
} | |
return response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment