1 """Provide CORS support for the HTTP component."""
3 from __future__
import annotations
5 from typing
import Final, cast
7 from aiohttp.hdrs
import ACCEPT, AUTHORIZATION, CONTENT_TYPE, ORIGIN
8 from aiohttp.web
import Application
9 from aiohttp.web_urldispatcher
import (
22 KEY_ALLOW_CONFIGURED_CORS,
26 ALLOWED_CORS_HEADERS: Final[list[str]] = [
29 HTTP_HEADER_X_REQUESTED_WITH,
33 VALID_CORS_TYPES: Final = (Resource, ResourceRoute, StaticResource)
37 def setup_cors(app: Application, origins: list[str]) ->
None:
39 cors = aiohttp_cors.setup(
42 host: aiohttp_cors.ResourceOptions(
43 allow_headers=ALLOWED_CORS_HEADERS, allow_methods=
"*"
52 route: AbstractRoute | AbstractResource,
53 config: dict[str, aiohttp_cors.ResourceOptions] |
None =
None,
55 """Allow CORS on a route."""
56 if isinstance(route, AbstractRoute):
61 if not isinstance(path, VALID_CORS_TYPES):
64 path_str = path.canonical
66 if path_str.startswith(
"/api/hassio_ingress/"):
69 if path_str
in cors_added:
72 cors.add(route, config)
73 cors_added.add(path_str)
75 app[KEY_ALLOW_ALL_CORS] =
lambda route: _allow_cors(
78 "*": aiohttp_cors.ResourceOptions(
79 allow_headers=ALLOWED_CORS_HEADERS, allow_methods=
"*"
85 app[KEY_ALLOW_CONFIGURED_CORS] = cast(AllowCorsType, _allow_cors)
87 app[KEY_ALLOW_CONFIGURED_CORS] =
lambda _:
None
None setup_cors(Application app, list[str] origins)