From be2f83d32228c2c795baf697766d48dc075a0474 Mon Sep 17 00:00:00 2001 From: Andrew Houghton Date: Mon, 17 Jul 2017 15:38:52 -0700 Subject: [PATCH] allow regexp for origins --- README.md | 5 +++-- src/origin-matcher.js | 4 +++- test/origin.spec.js | 6 ++++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6d9673b..46bbad0 100644 --- a/README.md +++ b/README.md @@ -31,12 +31,13 @@ server.use(cors.actual) ## Allowed origins -You can specify the full list of domains and subdomains allowed in your application: +You can specify the full list of domains and subdomains allowed in your application, using strings or regular expressions. ```js origins: [ 'http://myapp.com', - 'http://*.myapp.com' + 'http://*.myapp.com', + /^https?:\/\/myapp.com(:[\d]+)?$/ ] ``` diff --git a/src/origin-matcher.js b/src/origin-matcher.js index ddfdf3e..82104ab 100644 --- a/src/origin-matcher.js +++ b/src/origin-matcher.js @@ -13,7 +13,9 @@ exports.create = function (allowedOrigins) { } function createMatcher (allowedOrigin) { - if (allowedOrigin.indexOf('*') === -1) { + if (allowedOrigin instanceof RegExp) { + return requestOrigin => requestOrigin.match(allowedOrigin) + } else if (allowedOrigin.indexOf('*') === -1) { // simple string comparison return requestOrigin => requestOrigin === allowedOrigin } else { diff --git a/test/origin.spec.js b/test/origin.spec.js index 547a9bb..4ab9a97 100644 --- a/test/origin.spec.js +++ b/test/origin.spec.js @@ -52,4 +52,10 @@ describe('Origin list', function () { var matcher = originMatcher.create(list) matcher('http://random-website.com').should.eql(false) }) + + it('supports regular expressions', function () { + var list = ['http://api.myapp.com', /https?:\/\/example.com(:8888)?/] + var matcher = originMatcher.create(list) + matcher('https://example.com:8888').should.eql(true) + }) })