class Form(forms.BaseForm):
    enable_glyphicons = forms.CheckboxField(
        'Enable Glyphicons',
        required=False,
        initial=True,
        help_text=
        'If you disable this, remember to also update your sass config to not load the font.',
    )
    enable_fontawesome = forms.CheckboxField(
        'Enable Fontawesome',
        required=False,
        initial=True,
        help_text=
        'If you disable this, remember to also update your sass config to not load the font.',
    )

    carousel_styles = forms.CharField(
        'List of additional carousel styles (comma separated)', required=False)

    def to_settings(self, data, settings):
        choices = []
        if data['enable_glyphicons']:
            choices.append(('glyphicons', 'glyphicons', 'Glyphicons'))
        if data['enable_fontawesome']:
            choices.append(('fontawesome', 'fa', 'Fontawesome'))
        settings['ALDRYN_BOOTSTRAP3_ICONSETS'] = choices
        settings['ALDRYN_BOOTSTRAP3_CAROUSEL_STYLES'] = data['carousel_styles']
        return settings
class Form(forms.BaseForm):
    google_analytics_id = GoogleAnalyticsIDField('Tracking ID', max_length=50)
    # TODO: add description (not supported by forms yet):
    # https://developers.google.com/analytics/devguides/collection/upgrade/guide#transfer
    use_universal_analytics = forms.CheckboxField('Use Universal Analytics',
                                                  required=False)
    # https://developers.google.com/analytics/devguides/collection/analyticsjs/user-id?hl=en
    track_individuals = forms.CheckboxField(
        'Track individual logged in users (universal only)', required=False)

    def clean(self):
        super(Form, self).clean()
        if self.cleaned_data['track_individuals'] and not self.cleaned_data[
                'use_universal_analytics']:
            self.errors[
                'track_individuals'] = "Individual user tracking only works in with Universal Analytics."

    def to_settings(self, data, settings):
        settings['GOOGLE_ANALYTICS_ID'] = data['google_analytics_id']
        settings['GOOGLE_ANALYTICS_USE_UNIVERSAL'] = data[
            'use_universal_analytics']
        settings['GOOGLE_ANALYTICS_TRACK_INDIVIDUALS'] = data[
            'track_individuals']
        settings['INSTALLED_APPS'].append('aldryn_google_analytics')

        # aldryn-snake is configured by aldryn-django-cms
        return settings
class Form(forms.BaseForm):

    summary_richtext = forms.CheckboxField("Use rich text for Summary",
                                           required=False,
                                           initial=False)

    enable_price = forms.CheckboxField("Enable Price",
                                       required=False,
                                       initial=False)

    enable_cpd = forms.CheckboxField("Enable CPD points",
                                     required=False,
                                     initial=False)

    translate_is_published = forms.CheckboxField(
        'Translate Is published and Is featured fields',
        required=False,
        initial=False)

    def to_settings(self, data, settings):

        if data['summary_richtext']:
            settings['EVENTS_SUMMARY_RICHTEXT'] = int(data['summary_richtext'])
        if data['summary_richtext']:
            settings['EVENTS_ENABLE_PRICE'] = int(data['enable_price'])
        if data['summary_richtext']:
            settings['EVENTS_EVENTS_ENABLE_CPD'] = int(data['enable_cpd'])
        if data['translate_is_published']:
            settings['EVENTS_TRANSLATE_IS_PUBLISHED'] = int(
                data['translate_is_published'])
        settings['INSTALLED_APPS'].append('django_filters')
        settings['INSTALLED_APPS'].append('crispy_forms')
        return settings
Beispiel #4
0
class Form(forms.BaseForm):

    META_SITE_PROTOCOL = forms.SelectField(
        'Site protocol',
        choices=PROTOCOLS,
    )
    META_SITE_TYPE = forms.SelectField('Site type',
                                       choices=OBJECT_TYPES,
                                       required=False)
    META_SITE_NAME = forms.CharField('Site name', required=False)
    META_USE_OG_PROPERTIES = forms.CheckboxField(
        'Render the OpenGraph properties', required=False)
    META_USE_TWITTER_PROPERTIES = forms.CheckboxField(
        'Render the Twitter properties', required=False)
    META_USE_GOOGLEPLUS_PROPERTIES = forms.CheckboxField(
        'Render the Google properties', required=False)

    def to_settings(self, data, settings):
        settings['META_SITE_PROTOCOL'] = data['META_SITE_PROTOCOL']
        settings['META_SITE_TYPE'] = data['META_SITE_TYPE']
        settings['META_SITE_NAME'] = data['META_SITE_NAME']
        settings['META_INCLUDE_KEYWORDS'] = []
        settings['META_DEFAULT_KEYWORDS'] = []
        settings['META_USE_OG_PROPERTIES'] = data['META_USE_OG_PROPERTIES']
        settings['META_USE_TWITTER_PROPERTIES'] = data[
            'META_USE_TWITTER_PROPERTIES']
        settings['META_USE_GOOGLEPLUS_PROPERTIES'] = data[
            'META_USE_GOOGLEPLUS_PROPERTIES']
        settings['META_USE_TITLE_TAG'] = False
        settings['META_USE_SITES'] = True
        return settings
class Form(forms.BaseForm):
    section_layouts = forms.CharField('Section layouts', required=False)
    slideshow_layouts = forms.CharField('Slideshow layouts', required=False)
    slide_layouts = forms.CharField('Slide layouts', required=False)
    hide_article = forms.CheckboxField('Hide Showcase Article',
                                       required=False,
                                       initial=False)
    hide_slide = forms.CheckboxField('Hide Showcase Slide',
                                     required=False,
                                     initial=False)

    def to_settings(self, data, settings):
        if data['section_layouts']:
            settings['SHOWCASE_SECTION_LAYOUTS'] = tuple(
                l.strip() for l in data['section_layouts'].split(','))
        if data['slideshow_layouts']:
            settings['SHOWCASE_SLIDESHOW_LAYOUTS'] = tuple(
                l.strip() for l in data['slideshow_layouts'].split(','))
        if data['slide_layouts']:
            settings['SHOWCASE_SLIDE_LAYOUTS'] = tuple(
                l.strip() for l in data['slide_layouts'].split(','))
        if data['hide_article']:
            settings['SHOWCASE_HIDE_ARTICLE'] = int(data['hide_article'])
        if data['hide_slide']:
            settings['SHOWCASE_HIDE_SLIDE'] = int(data['hide_slide'])
        return settings
Beispiel #6
0
class Form(forms.BaseForm):
    hide_promo = forms.CheckboxField(
        'Hide Promo Unit', required=False, initial=False
    )
    hide_promo_rollover = forms.CheckboxField(
        'Hide Promo Unit rollover field', required=False, initial=True
    )
    hide_promo_video = forms.CheckboxField(
        'Hide Promo Unit background video', required=False, initial=True
    )
    hide_twitter = forms.CheckboxField(
        'Hide Twitter plugin', required=False, initial=False
    )
    twitter_app_key = forms.CharField(
        'Twitter App Key', required=False
    )
    twitter_app_secret = forms.CharField(
        'Twitter App Secret', required=False
    )
    twitter_oauth_token = forms.CharField(
        'Twitter OAuth Tocken', required=False
    )
    twitter_oauth_secret = forms.CharField(
        'Twitter OAuth Secret', required=False
    )
    hide_counters = forms.CheckboxField(
        'Hide Counters plugin', required=False, initial=False
    )
    hide_rawhtml = forms.CheckboxField(
        'Hide Raw HTML plugin', required=False, initial=False
    )
    hide_gated_content = forms.CheckboxField(
        'Hide Gated Content plugin', required=False, initial=True
    )
    hide_float = forms.CheckboxField(
        'Hide Float plugin', required=False, initial=True
    )
    hide_lightbox = forms.CheckboxField(
        'Hide Lightbox plugin', required=False, initial=True
    )

    def to_settings(self, data, settings):
        settings['COMPONENTS_HIDE_PROMO'] = int(data['hide_promo'])
        settings['COMPONENTS_HIDE_PROMO_ROLLOVER'] = int(data['hide_promo_rollover'])
        settings['COMPONENTS_HIDE_PROMO_VIDEO'] = int(data['hide_promo_video'])
        settings['COMPONENTS_HIDE_TWITTER'] = int(data['hide_twitter'])
        if data['twitter_app_key']:
            settings['TWITTER_APP_KEY'] = data['twitter_app_key']
        if data['twitter_app_secret']:
            settings['TWITTER_APP_SECRET'] = data['twitter_app_secret']
        if data['twitter_oauth_token']:
            settings['TWITTER_OAUTH_TOKEN'] = data['twitter_oauth_token']
        if data['twitter_oauth_secret']:
            settings['TWITTER_OAUTH_SECRET'] = data['twitter_oauth_secret']
        settings['COMPONENTS_HIDE_COUNTERS'] = int(data['hide_counters'])
        settings['COMPONENTS_HIDE_RAWHTML'] = int(data['hide_rawhtml'])
        settings['COMPONENTS_HIDE_GATED_CONTENT'] = int(data['hide_gated_content'])
        settings['COMPONENTS_HIDE_FLOAT'] = int(data['hide_float'])
        settings['COMPONENTS_HIDE_LIGHTBOX'] = int(data['hide_lightbox'])
        return settings
Beispiel #7
0
class Form(forms.BaseForm):
    enable_djangocms_personalise_by_auth = forms.CheckboxField(
        'Enable Personalise by Auth',
        required=False,
        initial=True,
    )
    enable_djangocms_personalise_by_cookie = forms.CheckboxField(
        'Enable Personalise by Cookie',
        required=False,
        initial=True,
    )
    enable_djangocms_personalise_by_country = forms.CheckboxField(
        'Enable Personalise by Country',
        required=False,
        initial=True,
        help_text=(
            'Requires the country code to be provided as an http header. Works '
            'automatically with CloudFlare. Please contact support for more '
            'information.'))
    enable_djangocms_personalise_by_parameters = forms.CheckboxField(
        'Enable Personalise by Parameters',
        required=False,
        initial=True,
    )
    enable_djangocms_personalise_manually = forms.CheckboxField(
        'Enable Personalise Manually',
        required=False,
        initial=True,
    )

    def to_settings(self, data, settings):
        from djangocms_personalise_by_country.constants import DEFAULT_COUNTRY_HEADERS
        from functools import partial
        from aldryn_addons.utils import djsenv
        env = partial(djsenv, settings=settings)

        settings['INSTALLED_APPS'].append('djangocms_personalisation')

        for key, value in data.items():
            if not key.startswith('enable_djangocms_personalise_'):
                continue
            if not value:
                continue
            settings['INSTALLED_APPS'].append(key.replace('enable_', ''))
            if key == 'enable_djangocms_personalise_by_parameters':
                settings['INSTALLED_APPS'].append('djangocms_attributes_field')
            elif key == 'enable_djangocms_personalise_by_country':
                settings['DJANGOCMS_PERSONALISE_BY_COUNTRY_HEADERS'] = env(
                    'DJANGOCMS_PERSONALISE_BY_COUNTRY_HEADERS',
                    DEFAULT_COUNTRY_HEADERS)
        return settings
class Form(forms.BaseForm):
    grid_size = forms.NumberField('Maximum columns to support', required=False)
    enable_glyphicons = forms.CheckboxField(
        'Enable Glyphicons',
        required=False,
        initial=True,
        help_text=
        'If you disable this, remember to also update your sass config to not load the font.',
    )
    enable_fontawesome = forms.CheckboxField(
        'Enable Fontawesome',
        required=False,
        initial=True,
        help_text=
        'If you disable this, remember to also update your sass config to not load the font.',
    )
    carousel_styles = forms.CharField(
        'List of additional carousel styles (comma separated)', required=False)

    def clean(self):
        data = super(Form, self).clean()

        # older versions of this addon had a bug where the values would be
        # saved to settings.json as a list instead of a string.
        if isinstance(data['carousel_styles'], list):
            data['carousel_styles'] = ', '.join(data['carousel_styles'])

        # prettify
        data['carousel_styles'] = ', '.join(
            split_and_strip(data['carousel_styles']))
        return data

    def to_settings(self, data, settings):
        choices = []
        if data['grid_size']:
            settings['ALDRYN_BOOTSTRAP3_GRID_SIZE'] = int(data['grid_size'])
        if data['enable_glyphicons']:
            choices.append(('glyphicons', 'glyphicons', 'Glyphicons'))
        if data['enable_fontawesome']:
            choices.append(('fontawesome', 'fa', 'Font Awesome'))
        if choices:
            settings['ALDRYN_BOOTSTRAP3_ICONSETS'] = choices

        if data['carousel_styles']:
            settings['ALDRYN_BOOTSTRAP3_CAROUSEL_STYLES'] = [
                (item, item)
                for item in split_and_strip(data['carousel_styles'])
            ]

        return settings
class Form(forms.BaseForm):
    enable_livereload = forms.CheckboxField(
        'Enable Livereload',
        required=False,
        initial=False,
        help_text=
        'Auto reloads the website on changes made in local development.')

    def to_settings(self, data, settings):
        import django
        from django.core.urlresolvers import reverse_lazy

        from aldryn_addons.utils import djsenv

        env = partial(djsenv, settings=settings)
        django_version = LooseVersion(django.get_version())

        cloud_sync_key = env('CMSCLOUD_SYNC_KEY')
        credential_url = env('LIVERELOAD_CREDENTIAL_URL')

        if django_version >= LooseVersion('1.8'):
            TEMPLATE_CONTEXT_PROCESSORS = settings['TEMPLATES'][0]['OPTIONS'][
                'context_processors']
        else:
            TEMPLATE_CONTEXT_PROCESSORS = settings[
                'TEMPLATE_CONTEXT_PROCESSORS']

        if 'aldryn_snake.template_api.template_processor' not in TEMPLATE_CONTEXT_PROCESSORS:
            TEMPLATE_CONTEXT_PROCESSORS.append(
                'aldryn_snake.template_api.template_processor')

        if cloud_sync_key and credential_url:
            settings['LIVERELOAD_CREDENTIAL_URL'] = credential_url
            # By selectively adding the urls, we avoid having to do
            # all sorts of checks in the views, instead the views
            # have no logic as to what settings are required or not.
            settings['ADDON_URLS'].append('aldryn_devsync.urls')
            settings['INSTALLED_APPS'].append('aldryn_devsync')

        if 'ALDRYN_SSO_LOGIN_WHITE_LIST' in settings:
            # stage sso enabled
            # add internal endpoints that do not require authentication
            settings['ALDRYN_SSO_LOGIN_WHITE_LIST'].extend([
                reverse_lazy('devsync-add-file'),
                reverse_lazy('devsync-delete-file'),
                reverse_lazy('devsync-run-command'),
                reverse_lazy('livereload-iframe-content'),
                reverse_lazy('toggle-livereload'
                             ),  #TODO: is ok for this to be white listed?
                reverse_lazy('devsync-trigger-sync'),
            ])

        settings['CMSCLOUD_SYNC_KEY'] = cloud_sync_key
        settings['LAST_BOILERPLATE_COMMIT'] = env('LAST_BOILERPLATE_COMMIT')
        settings['SYNC_CHANGED_FILES_URL'] = env('SYNC_CHANGED_FILES_URL')
        settings['SYNC_CHANGED_FILES_SIGNATURE_MAX_AGE'] = 60  # seconds

        settings['ALDRYN_DEVSYNC_ENABLE_LIVERELOAD'] = data[
            'enable_livereload']
        return settings
Beispiel #10
0
class Form(forms.BaseForm):

    show_all_recipients = forms.CheckboxField('Show all users as selectable e-mail recipients (not only admins)', required=False, initial=True)

    def to_settings(self, data, settings):
        settings['ALDRYN_FORMS_SHOW_ALL_RECIPIENTS'] = data['show_all_recipients']
        return settings
Beispiel #11
0
class Form(forms.BaseForm):
    enable_rest_framework = forms.CheckboxField(
        'Enable Django REST Framework',
        required=False,
        initial=True,
    )

    permissions_policy = forms.CharField(
        'Django REST Framework Permissions Policy',
        required=False,
        initial='AllowAny',
        help_text=(
            'REST Framework Permissions Policies are described at '
            'http://www.django-rest-framework.org/api-guide/permissions/ '))

    def to_settings(self, data, settings):
        enable_rest_framework = data['enable_rest_framework']
        permissions_policy = ('rest_framework.permissions.{}'.format(
            data['permissions_policy']))

        if enable_rest_framework:
            settings['INSTALLED_APPS'].extend([
                'rest_framework',
            ])
            settings['ADDON_URLS'].append('aldryn_django_rest_framework.urls')
            settings['REST_FRAMEWORK'] = {
                'DEFAULT_PERMISSION_CLASSES': (permissions_policy, )
            }
        return settings
Beispiel #12
0
class Form(forms.BaseForm):
    templates = forms.CharField(
        'List of additional templates (comma separated)',
        required=False,
    )
    terms = forms.CharField(
        'Default Terms',
        required=False,
    )
    show_context = forms.CheckboxField(
        'Show Context',
        required=False,
        initial=False,
    )

    def clean(self):
        data = super(Form, self).clean()

        # prettify
        data['templates'] = ', '.join(split_and_strip(data['templates']))
        return data

    def to_settings(self, data, settings):
        if data['templates']:
            settings['DJANGOCMS_FILE_TEMPLATES'] = [
                (item, item) for item in split_and_strip(data['templates'])
            ]
        if data['terms']:
            settings['DJANGOCMS_FILE_TERMS'] = data['terms']
        if data['show_context']:
            settings['DJANGOCMS_FILE_SHOW_CONTEXT'] = int(data['show_context'])

        return settings
class Form(forms.BaseForm):

    enable_debug_toolbar = forms.CheckboxField(
        'Enable Django Debug Toolbar',
        required=False,
        initial=True,
    )

    # The generally recommended position for the DebugToolbarMiddleware is immediately after the
    # GZipMiddleware. See:
    #
    # https://django-debug-toolbar.readthedocs.io/en/stable/installation.html#middleware
    # https://django-debug-toolbar.readthedocs.io/en/stable/tips.html#middleware-isn-t-working-correctly

    POSITIONS = [
        ["top", "As close to the top as possible (generally recommended)"],
        ["end", "As close to the end as possible"],
    ]

    toolbar_middleware_position = forms.SelectField(
        'DebugToolbarMiddleware position',
        help_text="Position in the middleware list",
        choices=POSITIONS,
        initial="top",
    )

    def _show_toolbar(self, request):
        return True

    def to_settings(self, data, settings):

        if settings["DEBUG"] and data['enable_debug_toolbar']:

            settings["INSTALLED_APPS"].extend(["debug_toolbar"])

            settings["DEBUG_TOOLBAR_CONFIG"] = {
                "SHOW_TOOLBAR_CALLBACK": self._show_toolbar
            }

            middleware = settings["MIDDLEWARE_CLASSES"]
            debug_toolbar_middleware = "debug_toolbar.middleware.DebugToolbarMiddleware"
            debug_toolbar_middleware_position = data[
                "toolbar_middleware_position"]

            if "django.middleware.gzip.GZipMiddleware" in middleware and debug_toolbar_middleware_position == "top":

                middleware.insert(
                    middleware.index("django.middleware.gzip.GZipMiddleware") +
                    1, debug_toolbar_middleware)

            elif debug_toolbar_middleware_position == "end":
                middleware.append(debug_toolbar_middleware)

            else:
                middleware.insert(0, debug_toolbar_middleware)

            settings['ADDON_URLS'].append('aldryn_django_debug_toolbar.urls')

        return settings
class Form(forms.BaseForm):
    enable_drag_and_drop = forms.CheckboxField(
        'Enable ajax drag and drop Placemark and Map in draft', required=False)

    def to_settings(self, data, settings):
        if data['enable_drag_and_drop']:
            settings['ADDON_URLS'].append('cmsplugin_yandex_maps.addon_urls')

        return settings
Beispiel #15
0
class Form(forms.BaseForm):
    enabled = forms.CheckboxField('Enabled', required=False, initial=True)

    def to_settings(self, data, settings):
        if data['enabled']:
            settings["INSTALLED_APPS"].append('admin_reorder')
            settings["MIDDLEWARE"].append(
                'admin_reorder.middleware.ModelAdminReorder')
        return settings
Beispiel #16
0
class Form(forms.BaseForm):
    name = forms.CharField(
        'name of consent cookie that remembers user choice',
        help_text='Default: cookie_consent',
        required=False
    )
    max_age = forms.NumberField(
        'max-age of consent cookie',
        help_text='Default: 1 year',
        required=False
    )
    decline = forms.CharField(
        'decline value',
        help_text='Default: -1',
        required=False
    )
    enabled = forms.CheckboxField(
        'Enabled', required=False, initial=True
    )
    opt_out = forms.CheckboxField(
        'opt-out cookies', required=False, initial=False,
        help_text='opt-out cookies are set until declined opt-in cookies are set only if accepted'

    )
    cache_backend = forms.CharField(
        'Alias for backend to use for caching',
        help_text='Default: default',
        required=False
    )

    def to_settings(self, data, settings):
        if data['name']:
            settings['COOKIE_CONSENT_NAME'] = data['name']
        if data['max_age']:
            settings['COOKIE_CONSENT_MAX_AGE'] = int(data['max_age'])
        if data['decline']:
            settings['COOKIE_CONSENT_DECLINE'] = data['decline']
        settings['COOKIE_CONSENT_ENABLED'] = data['enabled']
        settings['COOKIE_CONSENT_OPT_OUT'] = data['opt_out']
        if data['cache_backend']:
            settings['COOKIE_CONSENT_CACHE_BACKEND'] = data['cache_backend']
        #settings['ADDON_URLS'].append('cookie_consent.urls')

        return settings
Beispiel #17
0
class Form(forms.BaseForm):
    show_alternatives = forms.CheckboxField(
        "Show language alternatives",
        required=False,
        initial=False)

    def to_settings(self, data, settings):
        if data['show_alternatives']:
            settings['SITEMAP_SHOW_ALTERNATIVES'] = int(data['show_alternatives'])

        return settings
Beispiel #18
0
class Form(forms.BaseForm):
    show_pro_icons = forms.CheckboxField('Show Pro Icons',
                                         required=False,
                                         initial=False)
    show_duotone_icons = forms.CheckboxField('Show Duotone icons',
                                             required=False,
                                             initial=False)
    enable_color = forms.CheckboxField('Enable color input',
                                       required=False,
                                       initial=False)
    enable_size = forms.CheckboxField('Enable size input',
                                      required=False,
                                      initial=False)

    def to_settings(self, data, settings):
        settings['DJANGOCMS_ICON_SHOW_PRO_ICONS'] = int(data['show_pro_icons'])
        settings['DJANGOCMS_ICON_SHOW_DUOTONE_ICONS'] = int(
            data['show_duotone_icons'])
        settings['DJANGOCMS_ICON_ENABLE_COLOR'] = int(data['enable_color'])
        settings['DJANGOCMS_ICON_ENABLE_SIZE'] = int(data['enable_size'])
        return settings
class Form(forms.BaseForm):
    templates = forms.CharField(
        'List of additional templates (comma separated)',
        required=False,
    )
    alignment = forms.CharField(
        'List of alignment types, default "left, center, right" (comma separated)',
        required=False,
    )
    ratio = forms.CharField(
        'The ratio used to calculate the missing width or height, default "1.618"',
        required=False,
    )
    nesting = forms.CheckboxField(
        'Allow plugins to be nested inside the picture plugin.',
        required=False,
        initial=False,
    )

    def clean(self):
        data = super(Form, self).clean()

        # older versions of this addon had a bug where the values would be
        # saved to settings.json as a list instead of a string.
        if isinstance(data['templates'], list):
            data['templates'] = ', '.join(data['templates'])
        if isinstance(data['alignment'], list):
            data['alignment'] = ', '.join(data['alignment'])

        # prettify
        data['templates'] = ', '.join(split_and_strip(data['templates']))
        data['alignment'] = ', '.join(split_and_strip(data['alignment']))
        return data

    def to_settings(self, data, settings):
        if data['templates']:
            settings['DJANGOCMS_PICTURE_TEMPLATES'] = [
                (item, item)
                for item in split_and_strip(data['templates'])
            ]
        if data['alignment']:
            settings['DJANGOCMS_PICTURE_ALIGN'] = [
                (item, item)
                for item in split_and_strip(data['alignment'])
            ]
        if data['ratio']:
            settings['DJANGOCMS_PICTURE_RATIO'] = float(data['ratio'])
        if data['nesting']:
            settings['DJANGOCMS_PICTURE_NESTING'] = data['nesting']

        return settings
Beispiel #20
0
class Form(forms.BaseForm):

    hide_related_articles = forms.CheckboxField(
        "Hide Specific Articles Selector", required=False, initial=True)

    hide_tags = forms.CheckboxField("Hide Tags", required=False, initial=True)

    hide_user = forms.CheckboxField('Hide owner',
                                    required=False,
                                    initial=False)

    summary_richtext = forms.CheckboxField("Use rich text for Summary",
                                           required=False,
                                           initial=False)

    def to_settings(self, data, settings):

        if data['hide_related_articles']:
            settings['HIDE_RELATED_ARTICLES'] = int(
                data['hide_related_articles'])

        if data['hide_tags']:
            settings['HIDE_TAGS'] = int(data['hide_tags'])

        if data['hide_user']:
            settings['HIDE_USER'] = int(data['hide_user'])

        if data['summary_richtext']:
            settings['SUMMARY_RICHTEXT'] = int(data['summary_richtext'])

        settings['INSTALLED_APPS'].extend([
            'aldryn_apphooks_config', 'aldryn_boilerplates',
            'aldryn_categories', 'aldryn_common', 'aldryn_newsblog',
            'aldryn_people', 'aldryn_translation_tools', 'easy_thumbnails',
            'filer', 'sortedm2m', 'taggit', 'treebeard'
        ])

        return settings
class Form(forms.BaseForm):
    hide_user_management = forms.CheckboxField(
        'Hide user management',
        required=False,
        initial='true'
    )

    def to_settings(self, data, settings):
        from django.core.urlresolvers import reverse_lazy

        from aldryn_addons.utils import djsenv

        env = partial(djsenv, settings=settings)

        settings['LOGIN_REDIRECT_URL'] = '/'

        is_local_dev = env('STAGE') == 'local'
        if is_local_dev:
            settings['LOCAL_DEVELOPMENT'] = True

        if env('SSO_DSN'):
            # Expire user session every day because:
            # User can change its data on Login's server.
            # We cannot do a sync of "recently changed" user data due to these reasons:
            # - security risk, leaking user data to unauthorized websites,
            # - it would require some periodic tasks (celery?),
            # - stage websites are being paused during which the sync wouldn't work
            settings['CLOUD_USER_SESSION_EXPIRATION'] = 24 * 60 * 60  # 24h = 1day
            settings['SSO_DSN'] = env('SSO_DSN')

        if env('SSO_DSN') or is_local_dev:
            settings['ALDRYN_SSO_HIDE_USER_MANAGEMENT'] = data['hide_user_management']
            settings['ADDON_URLS'].append('aldryn_sso.urls')
            settings['INSTALLED_APPS'].insert(
                settings['INSTALLED_APPS'].index('django.contrib.admin'),
                'aldryn_sso'
            )
            settings['CMSCLOUD_STATIC_URL'] = env('CMSCLOUD_STATIC_URL', 'https://static.aldryn.com/')
        else:
            # there is no SSO_DSN set and is not local dev.
            # No point in configuring anything else.
            return settings

        if env('STAGE') == 'test':
            position = settings['MIDDLEWARE_CLASSES'].index('django.contrib.auth.middleware.AuthenticationMiddleware') + 1
            settings['ALDRYN_SSO_LOGIN_WHITE_LIST'] = [reverse_lazy('simple-sso-login')]
            settings['MIDDLEWARE_CLASSES'].insert(position, 'aldryn_sso.middleware.AccessControlMiddleware')
            settings['SHARING_VIEW_ONLY_TOKEN_KEY_NAME'] = env('SHARING_VIEW_ONLY_TOKEN_KEY_NAME')
            settings['SHARING_VIEW_ONLY_SECRET_TOKEN'] = env('SHARING_VIEW_ONLY_SECRET_TOKEN')
        return settings
Beispiel #22
0
class Form(forms.BaseForm):

    show_all_recipients = forms.CheckboxField(
        'Show all users as selectable e-mail recipients (not only admins)',
        required=False,
        initial=True)
    enable_simple_forms = forms.CheckboxField('Enable Simple forms',
                                              required=False,
                                              initial=False)
    enable_form_template = forms.CheckboxField('Enable Form template',
                                               required=False,
                                               initial=False)
    enable_custom_css = forms.CheckboxField('Enable Custom CSS classes',
                                            required=False,
                                            initial=False)
    enable_localstorage = forms.CheckboxField('Enable local storage',
                                              required=False,
                                              initial=False)
    enable_api = forms.CheckboxField('Enable API options',
                                     required=False,
                                     initial=False)
    enable_form_id = forms.CheckboxField('Enable Form ID',
                                         required=False,
                                         initial=False)
    default_action_backend = forms.SelectField('Default Action',
                                               ACTIONS,
                                               required=True)
    recaptcha_private_key = forms.CharField('ReCaptcha Private Key',
                                            required=False)
    recaptcha_public_key = forms.CharField('ReCaptcha Public Key',
                                           required=False)

    def to_settings(self, data, settings):
        settings['ALDRYN_FORMS_ENABLE_API'] = True
        settings['ALDRYN_FORMS_SHOW_ALL_RECIPIENTS'] = data[
            'show_all_recipients']
        settings['ALDRYN_FORMS_ENABLE_LOCALSTORAGE'] = data[
            'enable_localstorage']
        settings['ALDRYN_FORMS_ENABLE_SIMPLE_FORMS'] = data[
            'enable_simple_forms']
        settings['ALDRYN_FORMS_ENABLE_FORM_TEMPLATE'] = data[
            'enable_form_template']
        settings['ALDRYN_FORMS_ENABLE_CUSTOM_CSS'] = data['enable_custom_css']
        settings['ALDRYN_FORMS_DEFAULT_ACTION_BACKEND'] = data[
            'default_action_backend']
        settings['ALDRYN_FORMS_ENABLE_API'] = data['enable_api']
        settings['ALDRYN_FORMS_ENABLE_FORM_ID'] = data['enable_form_id']
        if data['recaptcha_private_key']:
            settings['RECAPTCHA_PRIVATE_KEY'] = data['recaptcha_private_key']
        if data['recaptcha_public_key']:
            settings['RECAPTCHA_PUBLIC_KEY'] = data['recaptcha_public_key']
        return settings
Beispiel #23
0
class Form(forms.BaseForm):
    plugin_module = forms.CharField('Plugin module name', initial='Generic')
    plugin_name = forms.CharField('Plugin name', initial='Youtube')
    use_https = forms.CheckboxField(
        'Use HTTPS?', initial=False, required=False,
        help_text='Check this box to use HTTPS for thumbnail URLS')
    api_key = forms.CharField(
        'YouTube Data API key',
        help_text='You can register an app via '
                  'https://developers.google.com/youtube/registering_an_application')

    def to_settings(self, data, settings):
        settings['DJANGOCMS_YOUTUBE_PLUGIN_MODULE'] = data['plugin_module']
        settings['DJANGOCMS_YOUTUBE_PLUGIN_NAME'] = data['plugin_name']
        settings['DJANGOCMS_YOUTUBE_USE_HTTPS'] = data['use_https']
        settings['DJANGOCMS_YOUTUBE_API_KEY'] = data['api_key']
        return settings
class Form(forms.BaseForm):

    grid_size = forms.NumberField('Maximum columns to support, default is 12.',
                                  required=False)
    enable_icons = forms.CheckboxField(
        'Enable icon support',
        required=False,
        initial=True,
    )

    def to_settings(self, data, settings):
        if data['grid_size']:
            settings['DJANGOCMS_BOOTSTRAP4_GRID_SIZE'] = int(data['grid_size'])
        if data['enable_icons']:
            settings['DJANGOCMS_BOOTSTRAP4_USE_ICONS'] = int(
                data['enable_icons'])

        return settings
class Form(forms.BaseForm):
    templates = forms.CharField(
        'List of additional templates (comma separated)',
        required=False,
    )
    extensions = forms.CharField(
        'List of allowed extensions, default "mp4, webm, ogv" when empty (comma separated)',
        required=False,
    )
    enable_poster = forms.CheckboxField(
        'Enable Video poster',
        required=False,
        initial=False,
    )

    def clean(self):
        data = super(Form, self).clean()

        # older versions of this addon had a bug where the values would be
        # saved to settings.json as a list instead of a string.
        if isinstance(data['templates'], list):
            data['templates'] = ', '.join(data['templates'])
        if isinstance(data['extensions'], list):
            data['extensions'] = ', '.join(data['extensions'])

        # prettify
        data['templates'] = ', '.join(split_and_strip(data['templates']))
        data['extensions'] = ', '.join(split_and_strip(data['extensions']))
        return data

    def to_settings(self, data, settings):
        if data['templates']:
            settings['DJANGOCMS_VIDEO_TEMPLATES'] = [
                (item, item) for item in split_and_strip(data['templates'])
            ]
        if data['extensions']:
            settings['DJANGOCMS_VIDEO_ALLOWED_EXTENSIONS'] = split_and_strip(
                data['extensions'])
        settings['DJANGOCMS_VIDEO_ENABLE_POSTER'] = int(data['enable_poster'])

        return settings
Beispiel #26
0
class Form(forms.BaseForm):
    plugin_module = forms.CharField('Plugin module name', initial='Generic')
    plugin_name = forms.CharField('Plugin name', initial='Form')
    html5_required = forms.CheckboxField(
        'Use HTML5 required?',
        initial=False,
        required=False,
        help_text='If checked, all required fields inputs will be rendered '
        'with HTML5 "required=required" attribute')
    recaptcha_public_key = forms.CharField('ReCaptcha Site Key',
                                           required=False)
    recaptcha_secret_key = forms.CharField('ReCaptcha Secret Key',
                                           required=False)

    def to_settings(self, data, settings):
        settings['DJANGOCMS_FORMS_PLUGIN_MODULE'] = data['plugin_module']
        settings['DJANGOCMS_FORMS_PLUGIN_NAME'] = data['plugin_name']
        settings['DJANGOCMS_FORMS_USE_HTML5_REQUIRED'] = data['html5_required']
        settings['DJANGOCMS_FORMS_RECAPTCHA_PUBLIC_KEY'] = data[
            'recaptcha_public_key']
        settings['DJANGOCMS_FORMS_RECAPTCHA_SECRET_KEY'] = data[
            'recaptcha_secret_key']
        return settings
Beispiel #27
0
class Form(forms.BaseForm):
    editor_theme = forms.CharField(
        'Custom editor theme, (e.g. "twilight", default: "github")',
        required=False,
    )
    editor_mode = forms.CharField(
        'Custom editor mode (e.g. "javascript", default: "html")',
        required=False,
    )
    enable_search = forms.CheckboxField(
        'Enable snippet content to be searchable.',
        required=False,
        initial=False,
    )

    def to_settings(self, data, settings):
        if data['editor_theme']:
            settings['DJANGOCMS_SNIPPET_THEME'] = data['editor_theme']
        if data['editor_mode']:
            settings['DJANGOCMS_SNIPPET_MODE'] = data['editor_mode']
        if data['enable_search']:
            settings['DJANGOCMS_SNIPPET_SEARCH'] = data['enable_search']
        return settings
class Form(forms.BaseForm):

    hide_related_services = forms.CheckboxField(
        "Hide Specific Services Selector", required=False, initial=False)
    summary_richtext = forms.CheckboxField("Use rich text for Summary",
                                           required=False,
                                           initial=False)
    enable_pubdate = forms.CheckboxField("Enable Published date",
                                         required=False,
                                         initial=False)
    enable_image = forms.CheckboxField("Enable Featured image",
                                       required=False,
                                       initial=True)
    related_templates = forms.CharField(
        'Related services templates, comma separated', required=False)
    translate_is_published = forms.CheckboxField(
        'Translate Is published and Is featured fields',
        required=False,
        initial=False)
    translate_layout = forms.CheckboxField('Translate layout field',
                                           required=False,
                                           initial=False)

    def to_settings(self, data, settings):

        settings['SERVICES_HIDE_RELATED_SERVICES'] = int(
            data['hide_related_services'])
        settings['SERVICES_SUMMARY_RICHTEXT'] = int(data['summary_richtext'])
        settings['SERVICES_ENABLE_PUBDATE'] = int(data['enable_pubdate'])
        settings['SERVICES_ENABLE_IMAGE'] = int(data['enable_image'])
        settings['SERVICES_TRANSLATE_IS_PUBLISHED'] = int(
            data['translate_is_published'])
        settings['SERVICES_TRANSLATE_LAYOUT'] = int(data['translate_layout'])
        if data['related_templates']:
            settings['SERVICES_RELATED_SERVICES_LAYOUTS'] = data[
                'related_templates'].split(',')

        return settings
class Form(forms.BaseForm):
    languages = forms.CharField(
        'Languages',
        required=True,
        initial='["en", "de"]',
        help_text=SYSTEM_FIELD_WARNING,
    )
    use_manifeststaticfilesstorage = forms.CheckboxField(
        'Hash static file names',
        required=False,
        initial=False,
        help_text=(
            'Use ManifestStaticFilesStorage to manage static files and set '
            'far-expiry headers. Enabling this option disables autosync for '
            'static files, and can cause deployment and/or 500 errors if a '
            'referenced file is missing. Please ensure that your test server '
            'works with this option enabled before deploying it to the live '
            'site.'))
    enable_gis = forms.CheckboxField(
        'Enable django.contrib.gis',
        required=False,
        initial=False,
        help_text=(
            'Enable Geodjango (django.contrib.gis) related functionality.\n'
            'WARNING: Requires postgis (contact support to enable it for your '
            'project). For local development change "postgres:9.4" to '
            '"mdillon/postgis:9.4" in docker-compose.yml and run '
            '"aldryn project up" to re-create the db container.'))
    disable_default_language_prefix = forms.CheckboxField(
        'Remove URL language prefix for default language',
        required=False,
        initial=False,
        help_text=(
            'For example, http://example.com/ rather than '
            'http://example.com/en/ if en (English) is the default language.'))
    session_timeout = forms.NumberField(
        'Timeout for users session, in seconds.',
        required=False,
        initial=(60 * 60 * 24 * 7 * 2),
        help_text=('By default it\'s two weeks (django default).'),
    )

    def to_settings(self, data, settings):
        import django_cache_url
        import dj_database_url
        import warnings
        from functools import partial
        from aldryn_addons.utils import boolean_ish, djsenv
        env = partial(djsenv, settings=settings)

        # BASE_DIR should already be set by aldryn-addons
        settings['BASE_DIR'] = env('BASE_DIR', required=True)
        settings['DATA_ROOT'] = env('DATA_ROOT',
                                    os.path.join(settings['BASE_DIR'], 'data'))
        settings['SECRET_KEY'] = env('SECRET_KEY', 'this-is-not-very-random')
        settings['DEBUG'] = boolean_ish(env('DEBUG', False))
        settings['ENABLE_SYNCING'] = boolean_ish(
            env('ENABLE_SYNCING', settings['DEBUG']))
        settings['DISABLE_TEMPLATE_CACHE'] = boolean_ish(
            env('DISABLE_TEMPLATE_CACHE', settings['DEBUG']))

        settings['DATABASE_URL'] = env('DATABASE_URL')
        settings['CACHE_URL'] = env('CACHE_URL')
        if env('DJANGO_MODE') == 'build':
            # In build mode we don't have any connected services like db or
            # cache available. So we need to configure those things in a way
            # they can run without real backends.
            settings['DATABASE_URL'] = 'sqlite://:memory:'
            settings['CACHE_URL'] = 'locmem://'

        if not settings['DATABASE_URL']:
            settings['DATABASE_URL'] = 'sqlite:///{}'.format(
                os.path.join(settings['DATA_ROOT'], 'db.sqlite3'))
            warnings.warn(
                'no database configured. Falling back to DATABASE_URL={0}'.
                format(settings['DATABASE_URL']),
                RuntimeWarning,
            )
        settings['DATABASES']['default'] = dj_database_url.parse(
            settings['DATABASE_URL'])

        if not settings['CACHE_URL']:
            settings['CACHE_URL'] = 'locmem://'
            warnings.warn(
                'no cache configured. Falling back to CACHE_URL={0}'.format(
                    settings['CACHE_URL']),
                RuntimeWarning,
            )
        settings['CACHES']['default'] = django_cache_url.parse(
            settings['CACHE_URL'])

        settings['ROOT_URLCONF'] = env('ROOT_URLCONF', 'urls')
        settings['ADDON_URLS_I18N'].append('aldryn_django.i18n_urls')

        settings['WSGI_APPLICATION'] = 'wsgi.application'

        settings['INSTALLED_APPS'].extend([
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.messages',
            'django.contrib.admin',
            'django.contrib.staticfiles',
            'aldryn_django',
        ])

        if settings['ENABLE_SYNCING'] or settings['DISABLE_TEMPLATE_CACHE']:
            loader_list_class = list
        else:
            loader_list_class = CachedLoader

        settings['TEMPLATES'] = [
            {
                'BACKEND':
                'django.template.backends.django.DjangoTemplates',
                'DIRS':
                env(
                    'TEMPLATE_DIRS',
                    [os.path.join(settings['BASE_DIR'], 'templates')],
                ),
                'OPTIONS': {
                    'debug':
                    boolean_ish(env('TEMPLATE_DEBUG', settings['DEBUG'])),
                    'context_processors': [
                        'django.contrib.auth.context_processors.auth',
                        'django.contrib.messages.context_processors.messages',
                        'django.template.context_processors.i18n',
                        'django.template.context_processors.debug',
                        'django.template.context_processors.request',
                        'django.template.context_processors.media',
                        'django.template.context_processors.csrf',
                        'django.template.context_processors.tz',
                        'django.template.context_processors.static',
                        'aldryn_django.context_processors.debug',
                    ],
                    'loaders':
                    loader_list_class([
                        'django.template.loaders.filesystem.Loader',
                        'django.template.loaders.app_directories.Loader',
                        'django.template.loaders.eggs.Loader',
                    ]),
                },
            },
        ]

        settings['MIDDLEWARE_CLASSES'] = [
            'django.contrib.sessions.middleware.SessionMiddleware',
            # 'django.middleware.common.CommonMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'django.middleware.locale.LocaleMiddleware',
            'django.contrib.sites.middleware.CurrentSiteMiddleware',
            'django.middleware.common.CommonMiddleware',
            'django.middleware.clickjacking.XFrameOptionsMiddleware',
            # 'django.middleware.security.SecurityMiddleware',
        ]

        if not env('DISABLE_GZIP'):
            settings['MIDDLEWARE_CLASSES'].insert(
                0, 'django.middleware.gzip.GZipMiddleware')

        settings['SITE_ID'] = env('SITE_ID', 1)

        settings['ADDON_URLS_I18N_LAST'] = 'aldryn_django.urls_redirect'

        self.domain_settings(data, settings, env=env)
        self.security_settings(data, settings, env=env)
        self.server_settings(settings, env=env)
        self.logging_settings(settings, env=env)
        # Order matters, sentry settings rely on logging being configured.
        self.sentry_settings(settings, env=env)
        self.storage_settings_for_media(settings, env=env)
        self.storage_settings_for_static(data, settings, env=env)
        self.email_settings(data, settings, env=env)
        self.i18n_settings(data, settings, env=env)
        self.migration_settings(settings, env=env)
        settings['ALDRYN_DJANGO_ENABLE_GIS'] = data['enable_gis']
        if settings['ALDRYN_DJANGO_ENABLE_GIS']:
            self.gis_settings(settings, env=env)
        return settings

    def domain_settings(self, data, settings, env):
        settings['ALLOWED_HOSTS'] = env('ALLOWED_HOSTS', ['localhost', '*'])
        # will take a full config dict from ALDRYN_SITES_DOMAINS if available,
        # otherwise fall back to constructing the dict from DOMAIN,
        # DOMAIN_ALIASES and DOMAIN_REDIRECTS
        domain = env('DOMAIN')
        if domain:
            settings['DOMAIN'] = domain

        domains = env('ALDRYN_SITES_DOMAINS', {})
        if not domains and domain:
            domain_aliases = [
                d.strip() for d in env('DOMAIN_ALIASES', '').split(',')
                if d.strip()
            ]
            domain_redirects = [
                d.strip() for d in env('DOMAIN_REDIRECTS', '').split(',')
                if d.strip()
            ]
            domains = {
                1: {
                    'name': env('SITE_NAME', ''),
                    'domain': domain,
                    'aliases': domain_aliases,
                    'redirects': domain_redirects,
                },
            }
        settings['ALDRYN_SITES_DOMAINS'] = domains

        # This is ensured again by aldryn-sites, but we already do it here
        # as we need the full list of domains later when configuring
        # media/static serving, before aldryn-sites had a chance to run.
        site_domains = domains.get(settings['SITE_ID'])
        if site_domains:
            settings['ALLOWED_HOSTS'].append(site_domains['domain'])
            settings['ALLOWED_HOSTS'].extend(site_domains['aliases'])
            settings['ALLOWED_HOSTS'].extend(site_domains['redirects'])

        settings['INSTALLED_APPS'].append('aldryn_sites')

        settings['MIDDLEWARE_CLASSES'].insert(
            settings['MIDDLEWARE_CLASSES'].index(
                'django.middleware.common.CommonMiddleware'),
            'aldryn_sites.middleware.SiteMiddleware',
        )

    def security_settings(self, data, settings, env):
        s = settings
        s['SECURE_SSL_REDIRECT'] = env('SECURE_SSL_REDIRECT', None)
        s['SECURE_REDIRECT_EXEMPT'] = env('SECURE_REDIRECT_EXEMPT', [])
        s['SECURE_HSTS_SECONDS'] = env('SECURE_HSTS_SECONDS', 0)
        # SESSION_COOKIE_SECURE is handled by
        #   django.contrib.sessions.middleware.SessionMiddleware
        s['SESSION_COOKIE_SECURE'] = env('SESSION_COOKIE_SECURE', False)
        s['SECURE_PROXY_SSL_HEADER'] = env('SECURE_PROXY_SSL_HEADER',
                                           ('HTTP_X_FORWARDED_PROTO', 'https'))
        s['SESSION_COOKIE_AGE'] = env(
            'SESSION_COOKIE_AGE',
            data.get('session_timeout') or 60 * 60 * 24 * 7 * 2)

        # SESSION_COOKIE_HTTPONLY and SECURE_FRAME_DENY must be False for CMS
        # SESSION_COOKIE_HTTPONLY is handled by
        #   django.contrib.sessions.middleware.SessionMiddleware
        s['SESSION_COOKIE_HTTPONLY'] = env('SESSION_COOKIE_HTTPONLY', False)

        s['SECURE_CONTENT_TYPE_NOSNIFF'] = env('SECURE_CONTENT_TYPE_NOSNIFF',
                                               False)
        s['SECURE_BROWSER_XSS_FILTER'] = env('SECURE_BROWSER_XSS_FILTER',
                                             False)

        s['MIDDLEWARE_CLASSES'].insert(
            s['MIDDLEWARE_CLASSES'].index(
                'aldryn_sites.middleware.SiteMiddleware') + 1,
            'django.middleware.security.SecurityMiddleware',
        )

    def server_settings(self, settings, env):
        settings['PORT'] = env('PORT', 80)
        settings['BACKEND_PORT'] = env('BACKEND_PORT', 8000)
        settings['ENABLE_NGINX'] = env('ENABLE_NGINX', False)
        settings['ENABLE_PAGESPEED'] = env(
            'ENABLE_PAGESPEED',
            env('PAGESPEED', False),
        )
        settings['STATICFILES_DEFAULT_MAX_AGE'] = env(
            'STATICFILES_DEFAULT_MAX_AGE',
            # Keep BROWSERCACHE_MAX_AGE for backwards compatibility
            env('BROWSERCACHE_MAX_AGE', 300),
        )
        settings['NGINX_CONF_PATH'] = env('NGINX_CONF_PATH')
        settings['NGINX_PROCFILE_PATH'] = env('NGINX_PROCFILE_PATH')
        settings['PAGESPEED_ADMIN_HTPASSWD_PATH'] = env(
            'PAGESPEED_ADMIN_HTPASSWD_PATH',
            os.path.join(
                os.path.dirname(settings['NGINX_CONF_PATH']),
                'pagespeed_admin.htpasswd',
            ))
        settings['PAGESPEED_ADMIN_USER'] = env('PAGESPEED_ADMIN_USER')
        settings['PAGESPEED_ADMIN_PASSWORD'] = env('PAGESPEED_ADMIN_PASSWORD')
        settings['DJANGO_WEB_WORKERS'] = env('DJANGO_WEB_WORKERS', 3)
        settings['DJANGO_WEB_MAX_REQUESTS'] = env('DJANGO_WEB_MAX_REQUESTS',
                                                  500)
        settings['DJANGO_WEB_TIMEOUT'] = env('DJANGO_WEB_TIMEOUT', 120)

        # https://docs.djangoproject.com/en/1.8/ref/settings/#use-x-forwarded-host
        settings['USE_X_FORWARDED_HOST'] = env('USE_X_FORWARDED_HOST', False)

    def logging_settings(self, settings, env):
        settings['LOGGING'] = {
            'version': 1,
            'disable_existing_loggers': False,
            'filters': {
                'require_debug_false': {
                    '()': 'django.utils.log.RequireDebugFalse',
                },
                'require_debug_true': {
                    '()': 'django.utils.log.RequireDebugTrue',
                },
            },
            'handlers': {
                'console': {
                    'level': 'INFO',
                    'class': 'logging.StreamHandler',
                    'stream': sys.stdout,
                },
                'null': {
                    'class': 'logging.NullHandler',
                },
            },
            'loggers': {
                '': {
                    'handlers': ['console'],
                    'level': 'INFO',
                },
                'django': {
                    'handlers': ['console'],
                    'level': 'INFO',
                },
                'django.request': {
                    'handlers': ['console'],
                    'level': 'INFO',
                    'propagate': False,
                },
                'aldryn': {
                    'handlers': ['console'],
                    'level': 'INFO',
                },
                'py.warnings': {
                    'handlers': ['console'],
                },
            }
        }

    def sentry_settings(self, settings, env):
        sentry_dsn = env('SENTRY_DSN')

        if sentry_dsn:
            settings['INSTALLED_APPS'].append('raven.contrib.django')
            settings['RAVEN_CONFIG'] = {'dsn': sentry_dsn}
            settings['LOGGING']['handlers']['sentry'] = {
                'level':
                'ERROR',
                'class':
                'raven.contrib.django.raven_compat.handlers.SentryHandler',
            }

    def storage_settings_for_media(self, settings, env):
        import yurl
        from aldryn_django.storage import parse_storage_url
        if env('DEFAULT_STORAGE_DSN'):
            settings['DEFAULT_STORAGE_DSN'] = env('DEFAULT_STORAGE_DSN')
        settings['MEDIA_URL'] = env('MEDIA_URL', '/media/')
        if 'DEFAULT_STORAGE_DSN' in settings:
            settings.update(parse_storage_url(settings['DEFAULT_STORAGE_DSN']))
        media_host = yurl.URL(settings['MEDIA_URL']).host
        settings['MEDIA_URL_IS_ON_OTHER_DOMAIN'] = (
            media_host and media_host not in settings['ALLOWED_HOSTS'])
        settings['MEDIA_ROOT'] = env(
            'MEDIA_ROOT', os.path.join(settings['DATA_ROOT'], 'media'))
        settings['MEDIA_HEADERS'] = []

        cmds = {}
        if os.path.exists('/usr/bin/pngout'):
            cmds[
                'png'] = '/usr/bin/pngout {filename} {filename}.png -s0 -y -force && mv {filename}.png {filename}'
        if os.path.exists('/usr/bin/jpegoptim'):
            cmds[
                'jpeg'] = '/usr/bin/jpegoptim --max=90 --overwrite --strip-all --all-progressive {filename}'
        if os.path.exists('/usr/bin/gifsicle'):
            cmds['gif'] = '/usr/bin/gifsicle --batch --optimize=2 {filename}'
        settings['THUMBNAIL_OPTIMIZE_COMMAND'] = cmds

    def storage_settings_for_static(self, data, settings, env):
        import yurl
        use_gzip = not env('DISABLE_GZIP')
        use_manifest = data['use_manifeststaticfilesstorage']
        if use_gzip:
            if use_manifest:
                storage = 'aldryn_django.storage.ManifestGZippedStaticFilesStorage'
            else:
                storage = 'aldryn_django.storage.GZippedStaticFilesStorage'
        else:
            if use_manifest:
                storage = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
            else:
                storage = 'django.contrib.staticfiles.storage.StaticFilesStorage'
        settings['STATICFILES_STORAGE'] = storage

        settings['STATIC_URL'] = env('STATIC_URL', '/static/')
        static_host = yurl.URL(settings['STATIC_URL']).host
        settings['STATIC_URL_IS_ON_OTHER_DOMAIN'] = (
            static_host and static_host not in settings['ALLOWED_HOSTS'])
        settings['STATIC_ROOT'] = env(
            'STATIC_ROOT',
            os.path.join(settings['BASE_DIR'], 'static_collected'),
        )
        settings['STATIC_HEADERS'] = [
            # Set far-future expiration headers for static files with hashed
            # filenames. Also set cors headers to * for fonts.
            (r'.*\.[0-9a-f]{10,16}\.(eot|ttf|otf|woff)', {
                'Access-Control-Allow-Origin': '*',
                'Cache-Control': 'public, max-age={}'.format(3600 * 24 * 365),
            }),
            (r'.*\.[0-9a-f]{10,16}\.[a-z]+', {
                'Cache-Control': 'public, max-age={}'.format(3600 * 24 * 365),
            }),
            # Set default expiration headers for all remaining static files.
            # *Has to be last* as processing stops at the first matching
            # pattern it finds. Also set cors headers to * for fonts.
            (r'.*\.(eot|ttf|otf|woff)', {
                'Access-Control-Allow-Origin':
                '*',
                'Cache-Control':
                'public, max-age={}'.format(
                    settings['STATICFILES_DEFAULT_MAX_AGE'], ),
            }),
            ('.*', {
                'Cache-Control':
                'public, max-age={}'.format(
                    settings['STATICFILES_DEFAULT_MAX_AGE'], ),
            }),
        ]
        settings['STATICFILES_DIRS'] = env(
            'STATICFILES_DIRS', [os.path.join(settings['BASE_DIR'], 'static')])

    def email_settings(self, data, settings, env):
        import dj_email_url

        email_url = env('EMAIL_URL', '')
        if email_url:
            settings['EMAIL_URL'] = email_url
            settings.update(dj_email_url.parse(email_url))

        from_email = env('DEFAULT_FROM_EMAIL', '')
        if from_email:
            settings['DEFAULT_FROM_EMAIL'] = from_email

        server_email = env('SERVER_EMAIL', '')
        if server_email:
            settings['SERVER_EMAIL'] = server_email

    def i18n_settings(self, data, settings, env):
        settings['ALL_LANGUAGES'] = list(settings['LANGUAGES'])
        settings['ALL_LANGUAGES_DICT'] = dict(settings['ALL_LANGUAGES'])

        settings['USE_L10N'] = True
        settings['USE_I18N'] = True

        def language_codes_to_tuple(codes):
            return [(code, settings['ALL_LANGUAGES_DICT'][code])
                    for code in codes]

        langs_from_env = env('LANGUAGES', None)
        lang_codes_from_env = env('LANGUAGE_CODES', None)
        langs_from_form = json.loads(data['languages'])

        if langs_from_env:
            settings['LANGUAGES'] = langs_from_env
        elif lang_codes_from_env:
            settings['LANGUAGES'] = language_codes_to_tuple(
                lang_codes_from_env)
        else:
            settings['LANGUAGES'] = language_codes_to_tuple(langs_from_form)

        lang_code_from_env = env('LANGUAGE_CODE', None)
        if lang_code_from_env:
            settings['LANGUAGE_CODE'] = lang_code_from_env
        else:
            settings['LANGUAGE_CODE'] = settings['LANGUAGES'][0][0]

        settings['LOCALE_PATHS'] = [
            os.path.join(settings['BASE_DIR'], 'locale'),
        ]
        settings['PREFIX_DEFAULT_LANGUAGE'] = not data[
            'disable_default_language_prefix']

        if not settings['PREFIX_DEFAULT_LANGUAGE']:
            settings['MIDDLEWARE_CLASSES'].insert(
                settings['MIDDLEWARE_CLASSES'].index(
                    'django.middleware.locale.LocaleMiddleware'),
                'aldryn_django.middleware.LanguagePrefixFallbackMiddleware',
            )

    def time_settings(self, settings, env):
        if env('TIME_ZONE'):
            settings['TIME_ZONE'] = env('TIME_ZONE')

    def migration_settings(self, settings, env):
        from aldryn_django import storage
        from aldryn_addons.utils import boolean_ish

        settings.setdefault('MIGRATION_COMMANDS', [])
        mcmds = settings['MIGRATION_COMMANDS']

        mcmds.append(
            'CACHE_URL="locmem://" python manage.py createcachetable django_dbcache; exit 0'
        )
        mcmds.append('python manage.py migrate --noinput')

        if not boolean_ish(env('DISABLE_S3_MEDIA_HEADERS_UPDATE')):
            if settings['DEFAULT_FILE_STORAGE'] == storage.SCHEMES['s3']:
                mcmds.append('python manage.py aldryn_update_s3_media_headers')

    def gis_settings(self, settings, env):
        settings['DATABASES']['default'][
            'ENGINE'] = 'django.contrib.gis.db.backends.postgis'
        settings['INSTALLED_APPS'].append('django.contrib.gis')
Beispiel #30
0
class Form(forms.BaseForm):
    hide_user_management = forms.CheckboxField(
        'Hide user management',
        required=False,
        initial=False,
    )

    def to_settings(self, data, settings):
        from functools import partial
        from aldryn_addons.exceptions import ImproperlyConfigured
        from aldryn_addons.utils import boolean_ish
        from aldryn_addons.utils import djsenv
        from simple_sso.compat import reverse_lazy

        def boolean_ish_or(value, or_values=()):
            if value in or_values:
                return value
            return boolean_ish(value)

        env = partial(djsenv, settings=settings)

        if settings.get('MIDDLEWARE'):
            # Django>=1.10
            MIDDLEWARE = settings['MIDDLEWARE']
        else:
            # Django<1.10
            MIDDLEWARE = settings['MIDDLEWARE_CLASSES']

        settings['ALDRYN_SSO_HIDE_USER_MANAGEMENT'] = data['hide_user_management']

        # if the SSO button is the only configured login option: redirect right
        # to the login without showing the page.
        settings['ALDRYN_SSO_ENABLE_AUTO_SSO_LOGIN'] = boolean_ish(
            env('ALDRYN_SSO_ENABLE_AUTO_SSO_LOGIN', True)
        )

        settings['SSO_DSN'] = env('SSO_DSN')

        settings['LOGIN_REDIRECT_URL'] = '/'

        settings['ALDRYN_SSO_ENABLE_SSO_LOGIN'] = boolean_ish(
            env(
                'ALDRYN_SSO_ENABLE_SSO_LOGIN',
                default=boolean_ish(settings['SSO_DSN']),
            )
        )

        settings['ALDRYN_SSO_ENABLE_LOGIN_FORM'] = boolean_ish(
            env(
                'ALDRYN_SSO_ENABLE_LOGIN_FORM',
                default=not settings['ALDRYN_SSO_HIDE_USER_MANAGEMENT'],
            )
        )

        settings['ALDRYN_SSO_ENABLE_LOCALDEV'] = boolean_ish(
            env(
                'ALDRYN_SSO_ENABLE_LOCALDEV',
                default=env('STAGE') == 'local',
            )
        )

        settings['ALDRYN_SSO_ALWAYS_REQUIRE_LOGIN'] = boolean_ish_or(
            env(
                'ALDRYN_SSO_ALWAYS_REQUIRE_LOGIN',
                default=env('STAGE') == 'test',
            ),
            or_values=(
                'basicauth',
            )
        )

        settings['ALDRYN_SSO_LOGIN_WHITE_LIST'] = env(
            'ALDRYN_SSO_LOGIN_WHITE_LIST',
            default=[]
        )

        settings['ADDON_URLS'].append('aldryn_sso.urls')
        settings['ADDON_URLS_I18N'].append('aldryn_sso.urls_i18n')

        # aldryn_sso must be after django.contrib.admin so it can unregister
        # the User/Group Admin if necessary.
        settings['INSTALLED_APPS'].insert(
            settings['INSTALLED_APPS'].index('django.contrib.admin'),
            'aldryn_sso'
        )

        if settings['ALDRYN_SSO_ENABLE_SSO_LOGIN']:
            # Expire user session every day because:
            # Users can change their data on the SSO server.
            # We cannot do a sync of "recently changed" user data due to these reasons:
            # - security risk, leaking user data to unauthorized websites,
            # - it would require some periodic tasks (celery?),
            # - stage websites are being paused during which the sync wouldn't work
            settings['CLOUD_USER_SESSION_EXPIRATION'] = 24 * 60 * 60  # 24h = 1day
            if not settings['SSO_DSN']:
                raise ImproperlyConfigured(
                    'ALDRYN_SSO_ENABLE_SSO_LOGIN is True, but no SSO_DSN is set.')
        if settings['ALDRYN_SSO_ALWAYS_REQUIRE_LOGIN'] == 'basicauth':
            basicauth_user = env('ALDRYN_SSO_BASICAUTH_USER')
            basicauth_password = env('ALDRYN_SSO_BASICAUTH_PASSWORD')
            if basicauth_user and basicauth_password:
                settings['ALDRYN_SSO_BASICAUTH_USER'] = basicauth_user
                settings['ALDRYN_SSO_BASICAUTH_PASSWORD'] = basicauth_password
            else:
                raise ImproperlyConfigured(
                    'ALDRYN_SSO_ALWAYS_REQUIRE_LOGIN set to "basicauth", but '
                    'ALDRYN_SSO_BASICAUTH_USER and ALDRYN_SSO_BASICAUTH_PASSWORD not set'
                )
            position = MIDDLEWARE.index('django.contrib.auth.middleware.AuthenticationMiddleware') + 1
            MIDDLEWARE.insert(position, 'aldryn_sso.middleware.BasicAuthAccessControlMiddleware')
        elif settings['ALDRYN_SSO_ALWAYS_REQUIRE_LOGIN']:
            position = MIDDLEWARE.index('django.contrib.auth.middleware.AuthenticationMiddleware') + 1
            MIDDLEWARE.insert(position, 'aldryn_sso.middleware.AccessControlMiddleware')
            settings['ALDRYN_SSO_LOGIN_WHITE_LIST'].extend([
                reverse_lazy('simple-sso-login'),
                reverse_lazy('aldryn_sso_login'),
                reverse_lazy('aldryn_sso_localdev_login'),
                reverse_lazy('aldryn_localdev_create_user'),
            ])

        if settings['ALDRYN_SSO_ALWAYS_REQUIRE_LOGIN']:
            settings['SHARING_VIEW_ONLY_TOKEN_KEY_NAME'] = env('SHARING_VIEW_ONLY_TOKEN_KEY_NAME')
            settings['SHARING_VIEW_ONLY_SECRET_TOKEN'] = env('SHARING_VIEW_ONLY_SECRET_TOKEN')

        settings['ALDRYN_SSO_OVERIDE_ADMIN_LOGIN_VIEW'] = env(
            'ALDRYN_SSO_OVERIDE_ADMIN_LOGIN_VIEW',
            any([
                settings['ALDRYN_SSO_ENABLE_SSO_LOGIN'],
                settings['ALDRYN_SSO_ENABLE_LOGIN_FORM'],
                settings['ALDRYN_SSO_ENABLE_LOCALDEV'],
            ])
        )

        if settings['ALDRYN_SSO_OVERIDE_ADMIN_LOGIN_VIEW']:
            # configure our combined login view to be the default
            settings['LOGIN_URL'] = 'aldryn_sso_login'
            # see admin.py for how we force admin to use this view as well
        return settings