Skip to content

Commit

Permalink
Add a middleware decorator for handling CORS.
Browse files Browse the repository at this point in the history
  • Loading branch information
rblank committed Dec 7, 2024
1 parent a0e1534 commit d4950f7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
4 changes: 2 additions & 2 deletions docs/_static/demo-html-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ const token = await decryptSecret(key, {
const storeUrl = tdoc.store_url || `${location.origin}/*store`;
const session = await toBase64(await random(18));

async function log(data) {
return await fetchJson(`${storeUrl}/log`, {
function log(data) {
return fetchJson(`${storeUrl}/log`, {
headers: bearerAuthorization(token),
body: {'time': Date.now(), 'location': location.href,
'session': session, 'data': data},
Expand Down
30 changes: 30 additions & 0 deletions tdoc/common/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,33 @@ def respond_json(respond, data):
('Cache-Control', 'no-cache'),
])
return [body]


def cors(origins=(), methods=(), headers=(), max_age=None):
achs = []
if methods:
achs.append(('Access-Control-Allow-Methods', ', '.join(methods)))
if headers:
achs.append(('Access-Control-Allow-Headers', ', '.join(headers)))
if max_age is not None:
achs.append(('Access-Control-Max-Age', str(max_age)))

def decorator(fn):
def handle(env, respond):
if '*' in origins:
ao = [('Access-Control-Allow-Origin', '*')]
elif (origin := env.get('HTTP_ORIGIN')) in origins:
ao = [('Access-Control-Allow-Origin', origin)]
else:
ao = []

def respond_with_allow_origin(status, headers, exc_info=None):
return respond(status, headers + ao, exc_info)

if (env['REQUEST_METHOD'] == 'OPTIONS' and
env.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD') is not None):
respond_with_allow_origin(http_status(HTTPStatus.OK), achs)
return []
return fn(env, respond_with_allow_origin)
return handle
return decorator

0 comments on commit d4950f7

Please sign in to comment.