|
25 | 25 | unresolver,
|
26 | 26 | )
|
27 | 27 | from readthedocs.core.utils import get_cache_tag
|
| 28 | +from readthedocs.projects.constants import PUBLIC |
28 | 29 | from readthedocs.projects.models import Project
|
29 | 30 | from readthedocs.proxito.cache import add_cache_tags, cache_response, private_response
|
30 | 31 | from readthedocs.proxito.redirects import redirect_to_https
|
@@ -305,6 +306,32 @@ def add_hosting_integrations_headers(self, request, response):
|
305 | 306 | if addons:
|
306 | 307 | response["X-RTD-Hosting-Integrations"] = "true"
|
307 | 308 |
|
| 309 | + def add_cors_headers(self, request, response): |
| 310 | + """ |
| 311 | + Add CORS headers only on PUBLIC versions. |
| 312 | +
|
| 313 | + DocDiff addons requires making a request from |
| 314 | + ``RTD_EXTERNAL_VERSION_DOMAIN`` to ``PUBLIC_DOMAIN`` to be able to |
| 315 | + compare both DOMs and show the visual differences. |
| 316 | +
|
| 317 | + This request needs ``Access-Control-Allow-Origin`` HTTP headers to be |
| 318 | + accepted by browsers. However, we cannot expose these headers for |
| 319 | + documentation that's not PUBLIC. |
| 320 | + """ |
| 321 | + project_slug = getattr(request, "path_project_slug", "") |
| 322 | + version_slug = getattr(request, "path_version_slug", "") |
| 323 | + |
| 324 | + if project_slug and version_slug: |
| 325 | + allow_cors = Version.objects.filter( |
| 326 | + project__slug=project_slug, |
| 327 | + slug=version_slug, |
| 328 | + privacy_level=PUBLIC, |
| 329 | + ).exists() |
| 330 | + if allow_cors: |
| 331 | + response.headers["Access-Control-Allow-Origin"] = "*.readthedocs.build" |
| 332 | + response.headers["Access-Control-Allow-Methods"] = "OPTIONS, GET" |
| 333 | + return response |
| 334 | + |
308 | 335 | def _get_https_redirect(self, request):
|
309 | 336 | """
|
310 | 337 | Get a redirect response if the request should be redirected to HTTPS.
|
@@ -342,4 +369,5 @@ def process_response(self, request, response): # noqa
|
342 | 369 | self.add_hsts_headers(request, response)
|
343 | 370 | self.add_user_headers(request, response)
|
344 | 371 | self.add_hosting_integrations_headers(request, response)
|
| 372 | + self.add_cors_headers(request, response) |
345 | 373 | return response
|
0 commit comments