Skip to content

Commit

Permalink
Update middleware.py
Browse files Browse the repository at this point in the history
  • Loading branch information
zodecky authored Nov 6, 2024
1 parent dac0d17 commit e1a7a3a
Showing 1 changed file with 11 additions and 20 deletions.
31 changes: 11 additions & 20 deletions falcon/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,6 @@ class CORSMiddleware(object):
* https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
* https://www.w3.org/TR/cors/#resource-processing-model
Note:
Falcon will automatically add OPTIONS responders if they are missing from the
responder instances added to the routes. When providing a custom ``on_options``
method, the ``Allow`` headers in the response should be set to the allowed
method values. If the ``Allow`` header is missing from the response,
this middleware will deny the preflight request.
This is also valid when using a sink function.
Keyword Arguments:
allow_origins (Union[str, Iterable[str]]): List of origins to allow (case
sensitive). The string ``'*'`` acts as a wildcard, matching every origin.
Expand Down Expand Up @@ -54,7 +45,9 @@ def __init__(
allow_origins: Union[str, Iterable[str]] = '*',
expose_headers: Optional[Union[str, Iterable[str]]] = None,
allow_credentials: Optional[Union[str, Iterable[str]]] = None,
allow_private_network: bool = False,
):

if allow_origins == '*':
self.allow_origins = allow_origins
else:
Expand Down Expand Up @@ -84,6 +77,8 @@ def __init__(
)
self.allow_credentials = allow_credentials

self.allow_private_network = allow_private_network

def process_response(
self, req: Request, resp: Response, resource: object, req_succeeded: bool
) -> None:
Expand Down Expand Up @@ -129,17 +124,13 @@ def process_response(
'Access-Control-Request-Headers', default='*'
)

if allow is None:
# there is no allow set, remove all access control headers
resp.delete_header('Access-Control-Allow-Methods')
resp.delete_header('Access-Control-Allow-Headers')
resp.delete_header('Access-Control-Max-Age')
resp.delete_header('Access-Control-Expose-Headers')
resp.delete_header('Access-Control-Allow-Origin')
else:
resp.set_header('Access-Control-Allow-Methods', allow)
resp.set_header('Access-Control-Allow-Headers', allow_headers)
resp.set_header('Access-Control-Max-Age', '86400') # 24 hours
resp.set_header('Access-Control-Allow-Methods', allow)
resp.set_header('Access-Control-Allow-Headers', allow_headers)
resp.set_header('Access-Control-Max-Age', '86400') # 24 hours

if self.allow_private_network and req.get_header('Access-Control-Request-Private-Network') == 'true':
resp.set_header('Access-Control-Allow-Private-Network', 'true')


async def process_response_async(self, *args: Any) -> None:
self.process_response(*args)

0 comments on commit e1a7a3a

Please sign in to comment.