|
| 1 | +from __future__ import absolute_import |
| 2 | + |
| 3 | +from . import api |
| 4 | +from .data_structures import HttpResponse, UrlPath |
| 5 | +from .utils import dict_filter |
| 6 | + |
| 7 | +# Imports for typing support |
| 8 | +from typing import Optional, Any, Sequence, Tuple, Dict, Union, List, Type # noqa |
| 9 | +from .containers import ApiInterfaceBase # noqa |
| 10 | + |
| 11 | + |
| 12 | +class AnyOrigin(object): |
| 13 | + pass |
| 14 | + |
| 15 | + |
| 16 | +Origins = Union[Sequence[str], Type[AnyOrigin]] |
| 17 | + |
| 18 | + |
| 19 | +class CORS(object): |
| 20 | + """ |
| 21 | + CORS (Cross-Origin Request Sharing) support for OdinWeb APIs. |
| 22 | +
|
| 23 | + See `MDN documentation <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_ |
| 24 | + for a technical description of CORS. |
| 25 | +
|
| 26 | + :param origins: List of whitelisted origins or use `AnyOrigin` to return a |
| 27 | + '*' or allow all. |
| 28 | + :param max_age: Max length of time access control headers can be cached |
| 29 | + in seconds. `None`, disables this header; a value of -1 will disable |
| 30 | + caching, requiring a pre-flight *OPTIONS* check for all calls. |
| 31 | + :param allow_credentials: Indicate that credentials can be submitted to |
| 32 | + this API. |
| 33 | + :param expose_headers: Request headers can be access by a client beyond |
| 34 | + the simple headers, *Cache-Control*, *Content-Language*, |
| 35 | + *Content-Type*, *Expires*, *Last-Modified*, *Pragma*. |
| 36 | + :param allow_headers: Headers that are allowed to be sent by the browser |
| 37 | + beyond the simple headers, *Accept*, *Accept-Language*, |
| 38 | + *Content-Language*, *Content-Type*. |
| 39 | +
|
| 40 | + """ |
| 41 | + priority = 1 |
| 42 | + |
| 43 | + def __new__(cls, api_interface, *args, **kwargs): |
| 44 | + # type: (CORS, ApiInterfaceBase, *Any, **Any) -> ApiInterfaceBase |
| 45 | + instance = object.__new__(cls) |
| 46 | + instance.__init__(api_interface, *args, **kwargs) |
| 47 | + |
| 48 | + # Add instance as middleware |
| 49 | + api_interface.middleware.append(instance) |
| 50 | + |
| 51 | + return api_interface |
| 52 | + |
| 53 | + def __init__(self, api_interface, origins, max_age=None, allow_credentials=None, |
| 54 | + expose_headers=None, allow_headers=None): |
| 55 | + # type: (ApiInterfaceBase, Origins, Optional[int], Optional[bool], Sequence[str], Sequence[str]) -> None |
| 56 | + self.origins = origins if origins is AnyOrigin else set(origins) |
| 57 | + self.max_age = max_age |
| 58 | + self.expose_headers = expose_headers |
| 59 | + self.allow_headers = allow_headers |
| 60 | + self.allow_credentials = allow_credentials |
| 61 | + |
| 62 | + self._register_options(api_interface) |
| 63 | + |
| 64 | + def _register_options(self, api_interface): |
| 65 | + # type: (ApiInterfaceBase) -> None |
| 66 | + """ |
| 67 | + Register CORS options endpoints. |
| 68 | + """ |
| 69 | + op_paths = api_interface.op_paths(collate_methods=True) |
| 70 | + for path, operations in op_paths.items(): |
| 71 | + if api.Method.OPTIONS not in operations: |
| 72 | + self._options_operation(api_interface, path, operations.keys()) |
| 73 | + |
| 74 | + def _options_operation(self, api_interface, path, methods): |
| 75 | + # type: (ApiInterfaceBase, UrlPath, List[api.Method]) -> None |
| 76 | + """ |
| 77 | + Generate an options operation for the specified path |
| 78 | + """ |
| 79 | + # Trim off path prefix. |
| 80 | + if path.startswith(api_interface.path_prefix): |
| 81 | + path = path[len(api_interface.path_prefix):] |
| 82 | + |
| 83 | + methods = set(methods) |
| 84 | + methods.add(api.Method.OPTIONS) |
| 85 | + |
| 86 | + @api_interface.operation(path, api.Method.OPTIONS) |
| 87 | + def _cors_options(request, **_): |
| 88 | + return HttpResponse(None, headers=self.option_headers(request, methods)) |
| 89 | + |
| 90 | + _cors_options.operation_id = path.format(separator='.') + '.cors_options' |
| 91 | + |
| 92 | + def origin_components(self, request): |
| 93 | + # type: (Any) -> Tuple[str, str] |
| 94 | + """ |
| 95 | + Return URL components that make up the origin. |
| 96 | +
|
| 97 | + This allows for customisation in the case or custom headers/proxy |
| 98 | + configurations. |
| 99 | +
|
| 100 | + :return: Tuple consisting of Scheme, Host/Port |
| 101 | +
|
| 102 | + """ |
| 103 | + return request.scheme, request.host |
| 104 | + |
| 105 | + def allow_origin(self, request): |
| 106 | + # type: (Any) -> str |
| 107 | + """ |
| 108 | + Generate allow origin header |
| 109 | + """ |
| 110 | + origins = self.origins |
| 111 | + if origins is AnyOrigin: |
| 112 | + return '*' |
| 113 | + else: |
| 114 | + origin = "{}://{}".format(*self.origin_components(request)) |
| 115 | + return origin if origin in origins else '' |
| 116 | + |
| 117 | + def option_headers(self, request, methods): |
| 118 | + # type: (Any, Sequence[api.Method]) -> Dict[str, str] |
| 119 | + """ |
| 120 | + Generate option headers. |
| 121 | + """ |
| 122 | + return dict_filter({ |
| 123 | + 'Access-Control-Allow-Origin': self.allow_origin(request), |
| 124 | + 'Access-Control-Allow-Methods': ', '.join(m.value for m in methods), |
| 125 | + 'Access-Control-Allow-Credentials': {True: 'true', False: 'false'}.get(self.allow_credentials), |
| 126 | + 'Access-Control-Allow-Headers': ', '.join(self.allow_headers) if self.allow_headers else None, |
| 127 | + 'Access-Control-Expose-Headers': ', '.join(self.expose_headers) if self.expose_headers else None, |
| 128 | + 'Access-Control-Max-Age': str(self.max_age) if self.max_age else None, |
| 129 | + 'Cache-Control': 'no-cache, no-store' |
| 130 | + }) |
| 131 | + |
| 132 | + def post_request(self, request, response): |
| 133 | + # type: (Any, HttpResponse) -> HttpResponse |
| 134 | + """ |
| 135 | + Post-request hook to allow CORS headers to responses. |
| 136 | + """ |
| 137 | + if request.method != api.Method.OPTIONS: |
| 138 | + response.headers['Access-Control-Allow-Origin'] = self.allow_origin(request) |
| 139 | + return response |
0 commit comments