Skip to content

Commit

Permalink
Adds crossdomain decorator to allow wide open cors (fixes #17)
Browse files Browse the repository at this point in the history
  • Loading branch information
GabLeRoux committed Apr 18, 2017
1 parent 2a17483 commit e484cee
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions requestbin/api.py
Expand Up @@ -3,6 +3,8 @@

from flask import session, make_response, request, render_template
from requestbin import app, db
from requestbin.crossdomain import crossdomain


def _response(object, code=200):
jsonp = request.args.get('jsonp')
Expand Down
48 changes: 48 additions & 0 deletions requestbin/crossdomain.py
@@ -0,0 +1,48 @@
from datetime import timedelta
from functools import update_wrapper

from flask import make_response, request, current_app


def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()

def get_methods():
if methods is not None:
return methods

options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']

def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp

h = resp.headers

h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = ','.join(headers)
h['X-TESTING_HEADERS'] = 'hello world'
return resp

f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)

return decorator
3 changes: 3 additions & 0 deletions requestbin/views.py
Expand Up @@ -2,6 +2,8 @@
from flask import session, redirect, url_for, escape, request, render_template, make_response

from requestbin import app, db
from requestbin.crossdomain import crossdomain


def update_recent_bins(name):
if 'recent' not in session:
Expand Down Expand Up @@ -32,6 +34,7 @@ def home():


@app.endpoint('views.bin')
@crossdomain(origin='*')
def bin(name):
try:
bin = db.lookup_bin(name)
Expand Down

0 comments on commit e484cee

Please sign in to comment.