add CORS middleware to add CORS header to *all* requests

This commit is contained in:
Martin Zimmermann 2013-11-05 01:11:18 +01:00
parent e3fc33fec4
commit 6126f0ec6f
2 changed files with 39 additions and 10 deletions

View File

@ -121,10 +121,6 @@ class Isso(object):
| misaka.HTML_SKIP_HTML | misaka.HTML_SKIP_IMAGES | misaka.HTML_SAFELINK)
def dispatch(self, request):
if request.method == "OPTIONS":
return Isso.CORS(request, Response("", 200), self.conf.getiter("general", "host"))
adapter = Isso.urls.bind_to_environ(request.environ)
try:
@ -139,8 +135,8 @@ class Isso(object):
except Exception:
logger.exception("%s %s", request.method, request.environ["PATH_INFO"])
return InternalServerError()
return Isso.CORS(request, response, self.conf.getiter("general", "host"))
else:
return response
def wsgi_app(self, environ, start_response):
@ -176,10 +172,13 @@ def make_app(conf=None):
from werkzeug.contrib.profiler import ProfilerMiddleware
isso = ProfilerMiddleware(isso, sort_by=("cumtime", ), restrictions=("isso/(?!lib)", ))
app = ProxyFix(wsgi.SubURI(SharedDataMiddleware(isso, {
'/js': join(dirname(__file__), 'js/'),
'/css': join(dirname(__file__), 'css/')
})))
app = ProxyFix(
wsgi.SubURI(
wsgi.CORSMiddleWare(
SharedDataMiddleware(isso, {
'/js': join(dirname(__file__), 'js/'),
'/css': join(dirname(__file__), 'css/')}),
list(isso.conf.getiter("general", "host")))))
return app

View File

@ -15,3 +15,33 @@ class SubURI(object):
environ['PATH_INFO'] = path_info[len(script_name):]
return self.app(environ, start_response)
class CORSMiddleWare(object):
def __init__(self, app, hosts):
self.app = app
self.hosts = hosts
def __call__(self, environ, start_response):
def add_cors_headers(status, headers, exc_info=None):
for host in self.hosts:
if environ.get("HTTP_ORIGIN", None) == host.rstrip("/"):
origin = host.rstrip("/")
break
else:
origin = host.rstrip("/")
headers.append(("Access-Control-Allow-Origin", origin.encode("latin-1")))
headers.append(("Access-Control-Allow-Headers", "Origin, Content-Type"))
headers.append(("Access-Control-Allow-Credentials", "true"))
headers.append(("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"))
return start_response(status, headers, exc_info)
if environ.get("REQUEST_METHOD") == "OPTIONS":
add_cors_headers("200 Ok", [("Content-Type", "text/plain")])
return ['200 Ok']
return self.app(environ, add_cors_headers)