From 1c21fbd5ac34a71c5a0a4dab431e7352888bf4d9 Mon Sep 17 00:00:00 2001 From: rehan99000 Date: Fri, 19 Jun 2020 11:52:48 +0500 Subject: [PATCH] added dynamic allowed hosts --- .../extensions/edly_ecommerce_app/helpers.py | 43 +++++++++++++++++++ ecommerce/settings/production.py | 9 ++++ 2 files changed, 52 insertions(+) diff --git a/ecommerce/extensions/edly_ecommerce_app/helpers.py b/ecommerce/extensions/edly_ecommerce_app/helpers.py index 1d9f0a9a7ff..a231416ccab 100644 --- a/ecommerce/extensions/edly_ecommerce_app/helpers.py +++ b/ecommerce/extensions/edly_ecommerce_app/helpers.py @@ -109,3 +109,46 @@ def user_is_course_creator(request): decoded_cookie_data = decode_edly_user_info_cookie(edly_user_info_cookie) return decoded_cookie_data.get('is_course_creator', False) + +class AllowedHosts(object): + """ + Dynamic ALLOWED_HOSTS class that adds all current sites to ALLOWED_HOSTS. + """ + __slots__ = ('defaults', 'sites', 'cache') + + def __init__(self, defaults=None, cache=True): + self.defaults = defaults or () + self.sites = None + self.cache = cache + + def get_sites(self): + if self.cache is True and self.sites is not None: + return self.sites + self.defaults + + from django.contrib.sites.models import Site, SITE_CACHE + sites = Site.objects.all() + self.sites = tuple(site.domain for site in sites) + + # fill Site.objects.get_current()'s cache for the lifetime + # of this process. Probably. + if self.cache is True: + for site_to_cache in sites: + if site_to_cache.pk not in SITE_CACHE: + SITE_CACHE[site_to_cache.pk] = site_to_cache + + return self.sites + self.defaults + + def __iter__(self): + return iter(self.get_sites()) + + def __str__(self): + return ', '.join(self.get_sites()) + + def __contains__(self, other): + return other in self.get_sites() + + def __len__(self): + return len(self.get_sites()) + + def __add__(self, other): + return self.__class__(defaults=self.defaults + other.defaults) diff --git a/ecommerce/settings/production.py b/ecommerce/settings/production.py index ef2d57d52a3..feca5069bb0 100644 --- a/ecommerce/settings/production.py +++ b/ecommerce/settings/production.py @@ -9,6 +9,7 @@ from django.core.exceptions import ImproperlyConfigured from ecommerce.settings.base import * +from ecommerce.extensions.edly_ecommerce_app.helpers import AllowedHosts # Protocol used for construcing absolute callback URLs PROTOCOL = 'https' @@ -106,3 +107,11 @@ def get_env_setting(setting): # Edly configuration EDLY_COOKIE_SECRET_KEY = config_from_yaml.get('EDLY_COOKIE_SECRET_KEY', EDLY_COOKIE_SECRET_KEY) + +ALLOWED_HOSTS = AllowedHosts(defaults=( + 'panel.edly.io', + 'panel.backend.edly.io', + '.edly.io', + 'ecommerce.healthcheck.local' + ) +)