Example #1
0
class Base(Configuration):

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = values.BooleanValue(False)
    INTERNAL_IPS = ['127.0.0.1']
    ALLOWED_HOSTS = values.ListValue(['*'])

    # Site
    SITE_ID = values.IntegerValue(1)
    HOSTNAME = values.Value('')

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # Application definition
    INSTALLED_APPS = [
        # Default
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.humanize',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        # Requirements
        'pytz',
        'corsheaders',
        'rest_framework',
        'rest_framework.authtoken',
        'rest_framework_simplejwt',
        'rest_framework_simplejwt.token_blacklist',
        'common',
        'multiselectfield',
        'compressor',
        # Applications
        'fallout',
    ]

    # Middleware
    MIDDLEWARE = [
        # CORS Headers
        'corsheaders.middleware.CorsMiddleware',
        # Default
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.locale.LocaleMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        # Application defined
        'common.middleware.ServiceUsageMiddleware',
    ]

    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
    DATABASES = values.DatabaseURLValue('sqlite://./db.sqlite3')
    DATABASE_ROUTERS = values.ListValue(
        ('common.router.DatabaseOverrideRouter', ))

    # URL router
    ROOT_URLCONF = 'rpg.urls'
    # WSGI entrypoint
    WSGI_APPLICATION = 'rpg.wsgi.application'

    # Templates configuration
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': (),
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                    'django.template.context_processors.request',
                    'django.template.context_processors.media',
                    'django.template.context_processors.debug',
                ],
            },
        },
    ]

    # Authentication backends
    AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
        'common.auth.LdapAuthenticationBackend',
    )

    # Password validation
    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME':
            'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]

    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/
    LANGUAGE_CODE = values.Value('fr')
    TIME_ZONE = values.Value('Europe/Paris')
    USE_I18N = values.BooleanValue(True)
    USE_L10N = values.BooleanValue(True)
    USE_TZ = values.BooleanValue(True)

    LANGUAGES = (
        ('fr', _('Français')),
        ('en', _('English')),
    )

    LOCALE_PATHS = (
        os.path.join(BASE_DIR, 'locale'),
        os.path.join(BASE_DIR, 'fallout/locale'),
    )

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/
    STATIC_URL = values.Value('/static/')
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

    STATICFILES_DIRS = (os.path.join(BASE_DIR, 'statics'), )

    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'compressor.finders.CompressorFinder',
    )

    # Media url and directory
    MEDIA_NAME = 'medias'
    MEDIA_URL = values.Value('/medias/')
    MEDIA_ROOT = values.Value(os.path.join(BASE_DIR, MEDIA_NAME))

    # Custom settings
    CELERY_ENABLE = values.BooleanValue(False)
    CORS_ORIGIN_ALLOW_ALL = values.BooleanValue(True)
    APPEND_SLASH = values.BooleanValue(True)

    # Django REST Framework configuration
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES':
        ('rest_framework.permissions.IsAuthenticated', ),
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
            'rest_framework.authentication.SessionAuthentication',
        ),
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework.renderers.JSONRenderer',
            'rest_framework.renderers.BrowsableAPIRenderer',
            'rest_framework.renderers.AdminRenderer',
        ),
        'DEFAULT_PARSER_CLASSES': (
            'rest_framework.parsers.JSONParser',
            'rest_framework.parsers.FormParser',
            'rest_framework.parsers.MultiPartParser',
            'rest_framework.parsers.FileUploadParser',
            'rest_framework_xml.parsers.XMLParser',
        ),
        'DEFAULT_PAGINATION_CLASS':
        'common.api.pagination.CustomPageNumberPagination',
        'PAGE_SIZE':
        10,
        'TEST_REQUEST_DEFAULT_FORMAT':
        'json',
        'COERCE_DECIMAL_TO_STRING':
        True,
        'HYPERLINKED':
        True,
    }

    # JSON Web Token Authentication
    SIMPLE_JWT = {
        'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=5),
        'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1),
        'ROTATE_REFRESH_TOKENS': False,
        'BLACKLIST_AFTER_ROTATION': True,
        'ALGORITHM': 'HS256',
        'SIGNING_KEY': values.SecretValue(environ_name='SECRET_KEY'),
        'VERIFYING_KEY': None,
        'AUTH_HEADER_TYPES': (
            'Bearer',
            'JWT',
        ),
        'USER_ID_FIELD': 'id',
        'USER_ID_CLAIM': 'user_id',
        'AUTH_TOKEN_CLASSES':
        ('rest_framework_simplejwt.tokens.AccessToken', ),
        'TOKEN_TYPE_CLAIM': 'token_type',
        'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
        'SLIDING_TOKEN_LIFETIME': datetime.timedelta(minutes=5),
        'SLIDING_TOKEN_REFRESH_LIFETIME': datetime.timedelta(days=1),
    }

    # Login URLs
    LOGIN_URL = values.Value('login')
    LOGOUT_URL = values.Value('logout')
    LOGIN_REDIRECT_URL = values.Value('fallout:index')
    LOGOUT_REDIRECT_URL = values.Value('fallout:index')

    # User substitution
    AUTH_USER_MODEL = 'fallout.Player'

    # Messages
    MESSAGE_TAGS = {
        messages.DEBUG: values.Value('light', environ_name='CSS_DEBUG'),
        messages.INFO: values.Value('info', environ_name='CSS_INFO'),
        messages.SUCCESS: values.Value('success', environ_name='CSS_SUCCESS'),
        messages.WARNING: values.Value('warning', environ_name='CSS_WARNING'),
        messages.ERROR: values.Value('danger error', environ_name='CSS_ERROR'),
    }
    CSS_CLASSES = {
        (1, 1): values.Value('info', environ_name='CSS_11'),
        (1, 0): values.Value('success', environ_name='CSS_10'),
        (0, 0): values.Value('warning', environ_name='CSS_00'),
        (0, 1): values.Value('danger error', environ_name='CSS_01'),
    }

    # CSS and JS compression
    COMPRESS_ENABLED = values.BooleanValue(True)
    COMPRESS_OFFLINE = values.BooleanValue(False)
    COMPRESS_OUTPUT_DIR = values.Value('_cache')

    # Clé secrète pour les communications sécurisées entre le front et les APIs
    FRONTEND_SECRET_KEY = values.Value('')

    # Durée de validité du lien de réinitialisation de mot de passe
    PASSWORD_RESET_TIMEOUT_DAYS = values.IntegerValue(1)

    # Gestionnaire utilisé pour l'import des fichiers
    FILE_UPLOAD_HANDLERS = ('common.utils.TemporaryFileHandler', )

    # Taille du payload maximum autorisée et permissions à l'upload
    DATA_UPLOAD_MAX_MEMORY_SIZE = values.IntegerValue(10485760)
    FILE_UPLOAD_PERMISSIONS = values.IntegerValue(0o644)

    # Stocke le token CSRF en session plutôt que dans un cookie
    CSRF_USE_SESSIONS = values.BooleanValue(False)

    # E-mail configuration
    EMAIL_HOST = values.Value('')
    EMAIL_HOST_USER = values.Value('')
    EMAIL_HOST_PASSWORD = values.Value('')
    EMAIL_PORT = values.IntegerValue(25)
    EMAIL_SUBJECT_PREFIX = values.Value("")
    EMAIL_USE_TLS = values.BooleanValue(False)
    EMAIL_USE_SSL = values.BooleanValue(False)
    EMAIL_TIMEOUT = values.IntegerValue(300)
    DEFAULT_FROM_EMAIL = values.Value('Fallout <*****@*****.**>')

    # Logging configuration
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'simple': {
                'format': '[%(asctime)s] %(levelname)7s: %(message)s',
                'datefmt': '%d/%m/%Y %H:%M:%S',
            },
        },
        'handlers': {
            'console': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
                'formatter': 'simple',
            },
            'file': {
                'level': 'WARNING',
                'class': 'logging.FileHandler',
                'filename': 'rpg.log',
                'formatter': 'simple',
            },
        },
        'loggers': {
            '': {
                'handlers': ['console'],
                'level': 'INFO',
                'propagate': True,
            },
            'django': {
                'handlers': ['console'],
                'level': 'INFO',
                'propagate': False,
            },
        }
    }
class Common(Configuration):

    # APP CONFIGURATION
    DJANGO_APPS = (
        # Default Django apps:
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',

        # Useful template tags:
        # 'django.contrib.humanize',

        # Admin
        'django.contrib.admin',
    )
    THIRD_PARTY_APPS = (
        'crispy_forms',  # Form layouts
        'avatar',  # for user avatars
        'allauth',  # registration
        'allauth.account',  # registration
        'allauth.socialaccount',  # registration
    )

    # Apps specific for this project go here.
    LOCAL_APPS = (
        'users',  # custom users app
        # Your stuff: custom apps go here
        'pipeline',  # assets management made easy
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
    INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
    # END APP CONFIGURATION

    # MIDDLEWARE CONFIGURATION
    MIDDLEWARE_CLASSES = (
        # Make sure djangosecure.middleware.SecurityMiddleware is listed first
        'djangosecure.middleware.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )
    # END MIDDLEWARE CONFIGURATION

    # MIGRATIONS CONFIGURATION
    MIGRATION_MODULES = {'sites': 'contrib.sites.migrations'}
    # END MIGRATIONS CONFIGURATION

    # DEBUG
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
    DEBUG = values.BooleanValue(False)

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
    TEMPLATE_DEBUG = DEBUG
    # END DEBUG

    # SECRET CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
    # Note: This key only used for development and testing.
    #       In production, this is changed to a values.SecretValue() setting
    SECRET_KEY = 'CHANGEME!!!'
    # END SECRET CONFIGURATION

    # FIXTURE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
    FIXTURE_DIRS = (join(BASE_DIR, 'fixtures'), )
    # END FIXTURE CONFIGURATION

    # EMAIL CONFIGURATION
    EMAIL_BACKEND = values.Value('django.core.mail.backends.smtp.EmailBackend')
    # END EMAIL CONFIGURATION

    # MANAGER CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
    ADMINS = (("""Arnaud Limbourg""", 'Your email'), )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
    MANAGERS = ADMINS
    # END MANAGER CONFIGURATION

    # DATABASE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
    DATABASES = values.DatabaseURLValue(
        'postgres://localhost/heroku-libsass-python')
    # END DATABASE CONFIGURATION

    # CACHING
    # Do this here because thanks to django-pylibmc-sasl and pylibmc
    # memcacheify (used on heroku) is painful to install on windows.
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': ''
        }
    }
    # END CACHING

    # GENERAL CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
    TIME_ZONE = 'America/Los_Angeles'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
    LANGUAGE_CODE = 'en-us'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
    SITE_ID = 1

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
    USE_I18N = True

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
    USE_L10N = True

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
    USE_TZ = True
    # END GENERAL CONFIGURATION

    # TEMPLATE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
    TEMPLATE_CONTEXT_PROCESSORS = (
        'django.contrib.auth.context_processors.auth',
        'allauth.account.context_processors.account',
        'allauth.socialaccount.context_processors.socialaccount',
        'django.core.context_processors.debug',
        'django.core.context_processors.i18n',
        'django.core.context_processors.media',
        'django.core.context_processors.static',
        'django.core.context_processors.tz',
        'django.contrib.messages.context_processors.messages',
        'django.core.context_processors.request',
        # Your stuff: custom template context processers go here
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
    TEMPLATE_DIRS = (join(BASE_DIR, 'templates'), )

    TEMPLATE_LOADERS = (
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )

    # See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs
    CRISPY_TEMPLATE_PACK = 'bootstrap3'
    # END TEMPLATE CONFIGURATION

    # STATIC FILE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
    STATIC_ROOT = join(os.path.dirname(BASE_DIR), 'staticfiles')

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
    STATIC_URL = '/static/'

    # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
    STATICFILES_DIRS = (join(BASE_DIR, 'static'), )

    # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )
    # END STATIC FILE CONFIGURATION

    # MEDIA CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
    MEDIA_ROOT = join(BASE_DIR, 'media')

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
    MEDIA_URL = '/media/'
    # END MEDIA CONFIGURATION

    # URL Configuration
    ROOT_URLCONF = 'urls'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
    WSGI_APPLICATION = 'wsgi.application'
    # End URL Configuration

    # AUTHENTICATION CONFIGURATION
    AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
        'allauth.account.auth_backends.AuthenticationBackend',
    )

    # Some really nice defaults
    ACCOUNT_AUTHENTICATION_METHOD = 'username'
    ACCOUNT_EMAIL_REQUIRED = True
    ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
    # END AUTHENTICATION CONFIGURATION

    # Custom user app defaults
    # Select the correct user model
    AUTH_USER_MODEL = 'users.User'
    LOGIN_REDIRECT_URL = 'users:redirect'
    LOGIN_URL = 'account_login'
    # END Custom user app defaults

    # SLUGLIFIER
    AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify'
    # END SLUGLIFIER

    # LOGGING CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
    # A sample logging configuration. The only tangible logging
    # performed by this configuration is to send an email to
    # the site admins on every HTTP 500 error when DEBUG=False.
    # See http://docs.djangoproject.com/en/dev/topics/logging for
    # more details on how to customize your logging configuration.
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse'
            }
        },
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'filters': ['require_debug_false'],
                'class': 'django.utils.log.AdminEmailHandler'
            }
        },
        'loggers': {
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
        }
    }
    # END LOGGING CONFIGURATION

    @classmethod
    def post_setup(cls):
        cls.DATABASES['default']['ATOMIC_REQUESTS'] = True

    # Your common stuff: Below this line define 3rd party library settings
    PIPELINE_CSS = {
        'general': {
            'source_filenames': ('sass/project.scss', ),
            'output_filename': 'css/general.css',
            'extra_context': {
                'media': 'screen',
            },
        },
    }

    PIPELINE_JS = {
        'common': {
            'source_filenames': ('js/project.js', ),
            'output_filename': 'js/common.js',
        }
    }

    PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.uglifyjs.UglifyJSCompressor'

    PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.cssmin.CSSMinCompressor'

    PIPELINE_COMPILERS = ('pipeline.compilers.sass.SASSCompiler', )

    PIPELINE_SASS_BINARY = 'sassc'

    PIPELINE_SASS_ARGUMENTS = ''
Example #3
0
class Common(Configuration):
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = values.BooleanValue(False)

    ALLOWED_HOSTS = values.ListValue([])

    # Application definition
    INSTALLED_APPS = [
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "django.contrib.humanize",
        "whitenoise.runserver_nostatic",
        "django.contrib.staticfiles",
        "django_extensions",
        "debug_toolbar",
        "django_s3_storage",
        "django_filters",
        "crispy_forms",
        "rest_framework",
        "contratospr.users",
        "contratospr.contracts",
        "contratospr.api",
        "contratospr.utils",
    ]

    MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "whitenoise.middleware.WhiteNoiseMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
        "debug_toolbar.middleware.DebugToolbarMiddleware",
    ]

    ROOT_URLCONF = "contratospr.urls"
    TEMPLATES = [{
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, "templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ]
        },
    }]

    WSGI_APPLICATION = "contratospr.wsgi.application"

    # Database
    # https://docs.djangoproject.com/en/2.1/ref/settings/#databases
    DATABASES = values.DatabaseURLValue("sqlite:///{}".format(
        os.path.join(BASE_DIR, "db.sqlite3")))

    # Password validation
    # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
    AUTH_PASSWORD_VALIDATORS = [
        {
            "NAME":
            "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.MinimumLengthValidator"
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.CommonPasswordValidator"
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.NumericPasswordValidator"
        },
    ]

    # Internationalization
    # https://docs.djangoproject.com/en/2.1/topics/i18n/
    LANGUAGE_CODE = "en-us"

    TIME_ZONE = "UTC"

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.1/howto/static-files/
    STATIC_URL = "/static/"
    STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
    STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
    STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

    MEDIA_ROOT = os.path.join(BASE_DIR, "media")

    AUTH_USER_MODEL = "users.User"

    REDIS_URL = values.Value(environ_prefix=None)

    @property
    def BROKER_URL(self):
        return f"{self.REDIS_URL}/0"

    FILEPREVIEWS_API_KEY = values.Value(environ_prefix=None)
    FILEPREVIEWS_API_SECRET = values.Value(environ_prefix=None)

    GOOGLE_APPLICATION_CREDENTIALS = values.Value(environ_prefix=None)

    DEBUG_TOOLBAR_CONFIG = {
        "SHOW_TOOLBAR_CALLBACK": "contratospr.utils.debug_toolbar.show_toolbar"
    }

    CONTRACTS_DOCUMENT_STORAGE = "django.core.files.storage.FileSystemStorage"

    REST_FRAMEWORK = {
        "DEFAULT_PAGINATION_CLASS":
        "rest_framework.pagination.PageNumberPagination",
        "PAGE_SIZE": 100,
    }
Example #4
0
class Common(Configuration):
    """ manage.py Command 'settings' to setup environment """

    BASE_URL = values.Value(default='http://*****:*****@openconceptlab.org'
    ACCOUNT_EMAIL_SUBJECT_PREFIX = '[openconceptlab.org] '

    USE_X_FORWARDED_HOST = True

    ########## APP CONFIGURATION
    DJANGO_APPS = (
        # Default Django apps:
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',

        # Useful template tags:
        # 'django.contrib.humanize',

        # Admin
        'django.contrib.admin',
    )
    THIRD_PARTY_APPS = (
        'south',  #  Database migration helpers:
        'crispy_forms',  #  Form layouts
        'avatar',  #  For user avatars
        'bootstrap3',
    )

    # Apps specific for this project go here.
    LOCAL_APPS = (
        'users',  # custom users app
        'apps.core',
        # Your stuff: custom apps go here
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
    INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

    INSTALLED_APPS += (
        # Needs to come last for now because of a weird edge case between
        #   South and allauth
        'allauth',  # registration
        'allauth.account',  # registration
        'allauth.socialaccount',  # registration
        'django.contrib.humanize', # user-friendly django template tags
    )
    ########## END APP CONFIGURATION

    ########## SITE CONFIGURATION
    # Hosts/domain names that are valid for this site
    # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
    ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]', '.openconceptlab.org', '.openmrs.org']
    ########## END SITE CONFIGURATION

    ########## MIDDLEWARE CONFIGURATION
    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )
    ########## END MIDDLEWARE CONFIGURATION

    ########## DEBUG
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
    DEBUG = values.BooleanValue(False)

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
    TEMPLATE_DEBUG = DEBUG
    ########## END DEBUG

    ########## FIXTURE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
    FIXTURE_DIRS = (
        join(BASE_DIR, 'fixtures'),
    )
    ########## END FIXTURE CONFIGURATION

    ########## EMAIL CONFIGURATION
    EMAIL_BACKEND = values.Value('django.core.mail.backends.smtp.EmailBackend')
    DEFAULT_FROM_EMAIL = values.Value('openconceptlab <*****@*****.**>')
    EMAIL_HOST = values.Value(environ_name="EMAIL_HOST", environ_prefix="")
    EMAIL_HOST_PASSWORD = values.Value(environ_name="EMAIL_HOST_PASSWORD", environ_prefix="", default="")
    EMAIL_HOST_USER = values.Value(environ_name="EMAIL_HOST_USER", environ_prefix="")
    EMAIL_PORT = values.IntegerValue(environ_name="EMAIL_PORT", environ_prefix="", default=587)
    EMAIL_USE_TLS = values.BooleanValue(environ_name="EMAIL_USE_TLS", environ_prefix="", default=True)
    EMAIL_USE_SSL = values.BooleanValue(environ_name="EMAIL_USE_SSL", environ_prefix="", default=False)
    EMAIL_SUBJECT_PREFIX = values.Value('[openconceptlab.org] ')
    ########## END EMAIL CONFIGURATION

    ########## MANAGER CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
    ADMINS = (
        ('Jonathan Payne', '*****@*****.**')
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
    MANAGERS = ADMINS
    ########## END MANAGER CONFIGURATION

    ########## DATABASE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
    DATABASES = values.DatabaseURLValue('postgres://*****:*****@dbweb.openconceptlab.org:5432/ocl')
    ########## END DATABASE CONFIGURATION

    ########## CACHING
    # Do this here because thanks to django-pylibmc-sasl and pylibmc memcacheify is
    # painful to install on windows. memcacheify is what's used in Production
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': ''
        }
    }
    ########## END CACHING

    ########## GENERAL CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
    TIME_ZONE = 'America/New_York'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
    LANGUAGE_CODE = 'en-us'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
    SITE_ID = 1

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
    USE_I18N = True

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
    USE_L10N = True

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
    USE_TZ = True
    ########## END GENERAL CONFIGURATION

    ########## TEMPLATE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
    TEMPLATE_CONTEXT_PROCESSORS = (
        'django.contrib.auth.context_processors.auth',
        "allauth.account.context_processors.account",
        "allauth.socialaccount.context_processors.socialaccount",
        'django.core.context_processors.debug',
        'django.core.context_processors.i18n',
        'django.core.context_processors.media',
        'django.core.context_processors.static',
        'django.core.context_processors.tz',
        'django.contrib.messages.context_processors.messages',
        'django.core.context_processors.request',
        # Your stuff: custom template context processers go here
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
    TEMPLATE_DIRS = (
        join(BASE_DIR, 'templates'),
    )

    TEMPLATE_LOADERS = (
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )

    # See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs
    CRISPY_TEMPLATE_PACK = 'bootstrap3'
    ########## END TEMPLATE CONFIGURATION

    ########## STATIC FILE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
    STATIC_ROOT = join(os.path.dirname(BASE_DIR), 'staticfiles')

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
    STATIC_URL = '/static/'

    # See:
    # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
    STATICFILES_DIRS = (
        join(BASE_DIR, 'static'),
    )

    # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )
    ########## END STATIC FILE CONFIGURATION

    ########## MEDIA CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
    MEDIA_ROOT = join(BASE_DIR, 'media')

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
    MEDIA_URL = '/media/'
    ########## END MEDIA CONFIGURATION

    ########## URL Configuration
    ROOT_URLCONF = 'config.urls'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
    WSGI_APPLICATION = 'config.wsgi.application'
    ########## End URL Configuration

    ########## AUTHENTICATION CONFIGURATION
    AUTHENTICATION_BACKENDS = (
        "django.contrib.auth.backends.ModelBackend",
        "allauth.account.auth_backends.AuthenticationBackend",
    )

    # Some really nice defaults
    ACCOUNT_AUTHENTICATION_METHOD = "username"
    ACCOUNT_EMAIL_REQUIRED = True
    ACCOUNT_EMAIL_VERIFICATION = "mandatory"
    ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.SignupForm'
    ACCOUNT_ADAPTER = 'users.adapter.OCLAccountAdapter'

    ########## END AUTHENTICATION CONFIGURATION

    ########## Custom user app defaults
    # Select the correct user model
    AUTH_USER_MODEL = "users.User"
    LOGIN_REDIRECT_URL = "users:redirect"
    ########## END Custom user app defaults

    ########## SLUGLIFIER
    AUTOSLUG_SLUGIFY_FUNCTION = "slugify.slugify"
    ########## END SLUGLIFIER

    ########## LOGGING CONFIGURATION
    def ignore_404_and_401_errors(record):
        if ' 404' in record.message or ' 401' in record.message:
            return False
        return True

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse'
            },
            'ignore_404_errors': {
                '()': 'django.utils.log.CallbackFilter',
                'callback': ignore_404_and_401_errors
            }
        },

        'formatters': {
            'normal': {
                'format': "%(levelname)s %(asctime)s [%(module)s %(filename)s:%(lineno)s %(funcName)s()] %(message)s",
                'datefmt': "%Y/%m/%d %H:%M:%S"
            },
        },

        'handlers': {
            'sentry': {
                'level': 'ERROR',
                'filters': ['ignore_404_errors', 'require_debug_false'],
                'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
                'tags': {'custom-tag': 'x'},
            },
            'mail_admins': {
                'level': 'ERROR',
                'filters': ['require_debug_false'],
                'class': 'django.utils.log.AdminEmailHandler'
            },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'normal',
            },
            'logfile': {
                'level': 'DEBUG',
                'class': 'logging.handlers.TimedRotatingFileHandler',
                'when': 'midnight',
                'filename': os.path.join(BASE_DIR, 'oclweb.log'),
                'formatter': 'normal',
            },
        },

        'loggers': {
            'django.request': {
                'handlers': ['mail_admins', 'console', 'logfile', 'sentry'],
                'level': 'DEBUG',
            },
            'oclapi.request': {
                'handlers': ['console', 'logfile', 'sentry'],
                'level': 'INFO',
            },
            'oclapi': {
                'handlers': ['console', 'logfile', 'sentry'],
                'level': 'DEBUG',
            },
            '': {
                'handlers': ['console', 'logfile', 'sentry'],
                'level': 'INFO',
            },
        }
    }
    ########## END LOGGING CONFIGURATION


    ########## Your common stuff: Below this line define 3rd party libary settings
    # API_HOST = 'http://65.99.230.144'
    # API_TOKEN = 'Token ' + '%s' % os.environ.get('OCL_API_TOKEN')
    API_HOST = values.Value(default='http://172.17.0.1:8000',environ_name='OCL_API_HOST', environ_prefix=None)
    API_TOKEN = values.Value(default='891b4b17feab99f3ff7e5b5d04ccc5da7aa96da6',environ_name='OCL_API_TOKEN', environ_prefix=None)
Example #5
0
class Base(Configuration):
    DEBUG = values.BooleanValue(True)

    DATABASES = values.DatabaseURLValue('sqlite:///dev.db')
    CONN_MAX_AGE = None

    INSTALLED_APPS = values.ListValue([
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'django.contrib.admin',
        'django_comments',
        'django.contrib.flatpages',
        'django.contrib.sitemaps',
        'django.contrib.humanize',

        # external
        'haystack',
        'taggit',
        'overextends',
        'storages',
        'treebeard',

        # local
        'froide.foirequest',
        'froide.foirequestfollower',
        'froide.frontpage',
        'froide.publicbody',
        'froide.account',
        'froide.team',
        'froide.foisite',
        'froide.helper',

        # API
        'oauth2_provider',
        'rest_framework',
    ])

    CACHES = values.CacheURLValue('dummy://')

    # ############# Site Configuration #########

    # Make this unique, and don't share it with anybody.
    SECRET_KEY = 'make_me_unique!!'

    SITE_NAME = values.Value('Froide')
    SITE_EMAIL = values.Value('*****@*****.**')
    SITE_URL = values.Value('http://*****:*****@example.com'),
    )

    MANAGERS = ADMINS

    INTERNAL_IPS = values.TupleValue(('127.0.0.1', ))

    # ############## PATHS ###############

    PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

    LOCALE_PATHS = values.TupleValue(
        (os.path.abspath(os.path.join(PROJECT_ROOT, '..', "locale")), ))

    GEOIP_PATH = None

    # Absolute filesystem path to the directory that will hold user-uploaded files.
    # Example: "/home/media/media.lawrence.com/media/"
    MEDIA_ROOT = values.Value(
        os.path.abspath(os.path.join(PROJECT_ROOT, "..", "files")))

    # Sub path in MEDIA_ROOT that will hold FOI attachments
    FOI_MEDIA_PATH = values.Value('foi')

    # Absolute path to the directory static files should be collected to.
    # Don't put anything in this directory yourself; store your static files
    # in apps' "static/" subdirectories and in STATICFILES_DIRS.
    # Example: "/home/media/media.lawrence.com/static/"
    STATIC_ROOT = values.Value(
        os.path.abspath(os.path.join(PROJECT_ROOT, "..", "public")))

    # Additional locations of static files
    STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, "static"), )
    # ########## URLs #################

    ROOT_URLCONF = values.Value('froide.urls')

    # URL that handles the media served from MEDIA_ROOT. Make sure to use a
    # trailing slash.
    # Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
    MEDIA_URL = values.Value('/files/')

    # URL prefix for static files.
    # Example: "http://media.lawrence.com/static/"

    # URL that handles the static files like app media.
    # Example: "http://media.lawrence.com"
    STATIC_URL = values.Value('/static/')

    USE_X_ACCEL_REDIRECT = values.BooleanValue(False)
    X_ACCEL_REDIRECT_PREFIX = values.Value('/protected')

    # ## URLs that can be translated to a secret value

    SECRET_URLS = values.DictValue({"admin": "admin"})

    # ######## Backends, Finders, Processors, Classes ####

    AUTH_USER_MODEL = values.Value('account.User')
    PASSWORD_HASHERS = [
        'django.contrib.auth.hashers.PBKDF2PasswordHasher',
        'froide.account.hashers.PBKDF2WrappedSHA1PasswordHasher',
    ]

    # List of finder classes that know how to find static files in
    # various locations.
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
        'django.contrib.staticfiles.finders.FileSystemFinder',
    )

    TEMPLATES = [{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(PROJECT_ROOT, "templates"),
        ],
        'OPTIONS': {
            'debug':
            values.BooleanValue(DEBUG),
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
            'builtins': ['overextends.templatetags.overextends_tags'],
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'froide.helper.context_processors.froide',
                'froide.helper.context_processors.site_settings',
                'froide.helper.context_processors.block_helper'
            ]
        }
    }]

    MIDDLEWARE = [
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.locale.LocaleMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'oauth2_provider.middleware.OAuth2TokenMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    # ######### I18N and L10N ##################

    # Local time zone for this installation. Choices can be found here:
    # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
    # although not all choices may be available on all operating systems.
    # On Unix systems, a value of None will cause Django to use the same
    # timezone as the operating system.
    # If running in a Windows environment this must be set to the same as your
    # system time zone.
    TIME_ZONE = values.Value('Europe/Berlin')
    USE_TZ = values.BooleanValue(True)

    # Language code for this installation. All choices can be found here:
    # http://www.i18nguy.com/unicode/language-identifiers.html
    LANGUAGE_CODE = values.Value('en')
    LANGUAGES = (
        ('en', _('English')),
        ('es', _('Spanish')),
        ('fi-fi', _('Finnish (Finland)')),
        ('de', _('German')),
        ('da-dk', _('Danish (Denmark)')),
        ('it', _('Italian')),
        ('pt', _('Portuguese')),
        ('sv-se', _('Swedish (Sweden)')),
        ('sv-fi', _('Swedish (Finland)')),
        ('zh-cn', _('Chinese (Simplified)')),
        ('zh-hk', _('Chinese (Traditional, Hong Kong)')),
    )

    # If you set this to False, Django will make some optimizations so as not
    # to load the internationalization machinery.
    USE_I18N = values.BooleanValue(True)

    # If you set this to False, Django will not format dates, numbers and
    # calendars according to the current locale
    USE_L10N = values.BooleanValue(True)

    DATE_FORMAT = values.Value("d. F Y")
    SHORT_DATE_FORMAT = values.Value("d.m.Y")
    DATE_INPUT_FORMATS = values.TupleValue(("%d.%m.%Y", ))
    SHORT_DATETIME_FORMAT = values.Value("d.m.Y H:i")
    DATETIME_INPUT_FORMATS = values.TupleValue(("%d.%m.%Y %H:%M", ))
    TIME_FORMAT = values.Value("H:i")
    TIME_INPUT_FORMATS = values.TupleValue(("%H:%M", ))

    HOLIDAYS = [
        (1, 1),  # New Year's Day
        (12, 25),  # Christmas
        (12, 26)  # Second day of Christmas
    ]

    # Weekends are non-working days
    HOLIDAYS_WEEKENDS = True

    # Calculates other holidays based on easter sunday
    HOLIDAYS_FOR_EASTER = (0, -2, 1, 39, 50, 60)

    # ######## Logging ##########

    # A sample logging configuration.
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': True,
        'root': {
            'level': 'WARNING',
            'handlers': [],
        },
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse'
            }
        },
        'formatters': {
            'verbose': {
                'format':
                '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
            },
        },
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'filters': ['require_debug_false'],
                'class': 'django.utils.log.AdminEmailHandler'
            },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
            }
        },
        'loggers': {
            'froide': {
                'handlers': ['console'],
                'propagate': True,
                'level': 'DEBUG',
            },
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
            'django.db.backends': {
                'level': 'ERROR',
                'handlers': ['console'],
                'propagate': False,
            }
        }
    }

    # ######## Security ###########

    CSRF_COOKIE_SECURE = False
    CSRF_FAILURE_VIEW = values.Value('froide.account.views.csrf_failure')

    # Change this
    # ALLOWED_HOSTS = ()
    ALLOWED_REDIRECT_HOSTS = ()

    SESSION_COOKIE_AGE = values.IntegerValue(3628800)  # six weeks
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SECURE = False

    # ######## Celery #############

    CELERY_BEAT_SCHEDULE = {
        'fetch-mail': {
            'task': 'froide.foirequest.tasks.fetch_mail',
            'schedule': crontab(),
        },
        'detect-asleep': {
            'task': 'froide.foirequest.tasks.detect_asleep',
            'schedule': crontab(hour=0, minute=0),
        },
        'detect-overdue': {
            'task': 'froide.foirequest.tasks.detect_overdue',
            'schedule': crontab(hour=0, minute=0),
        },
        'update-foirequestfollowers': {
            'task': 'froide.foirequestfollower.tasks.batch_update',
            'schedule': crontab(hour=0, minute=0),
        },
        'classification-reminder': {
            'task': 'froide.foirequest.tasks.classification_reminder',
            'schedule': crontab(hour=7, minute=0, day_of_week=6),
        },
    }

    CELERY_TASK_ALWAYS_EAGER = values.BooleanValue(True)

    CELERY_TASK_ROUTES = {
        'froide.foirequest.tasks.fetch_mail': {
            "queue": "emailfetch"
        },
        'froide.foirequest.tasks.process_mail': {
            "queue": "email"
        },
        'djcelery_email_send_multiple': {
            "queue": "email"
        },
    }
    CELERY_TIMEZONE = 'UTC'
    # We need to serialize email data as binary
    # which doesn't work well in JSON
    CELERY_TASK_SERIALIZER = 'pickle'
    CELERY_RESULT_SERIALIZER = 'pickle'
    CELERY_ACCEPT_CONTENT = ['pickle']

    CELERY_EMAIL_TASK_CONFIG = {'queue': 'email'}

    # ######## Haystack ###########

    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
        }
    }

    # ######### API #########

    # Do not include xml by default, so lxml doesn't need to be present
    TASTYPIE_DEFAULT_FORMATS = ['json']

    OAUTH2_PROVIDER = {
        'SCOPES': {
            'read:user': _('Access to user status'),
            'read:profile': _('Read user profile information'),
            'read:email': _('Read user email'),
            'read:request': _('Read my (private) requests'),
            'make:request': _('Make requests on my behalf'),
        }
    }
    OAUTH2_PROVIDER_APPLICATION_MODEL = 'account.Application'

    LOGIN_URL = 'account-login'

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.SessionAuthentication',
            'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        ),
        'DEFAULT_PERMISSION_CLASSES':
        ('rest_framework.permissions.IsAuthenticatedOrReadOnly', ),
        'DEFAULT_PAGINATION_CLASS':
        'froide.helper.api_utils.CustomLimitOffsetPagination',
        'PAGE_SIZE':
        50,
        'DEFAULT_FILTER_BACKENDS':
        ('django_filters.rest_framework.DjangoFilterBackend', )
    }

    # ######### Froide settings ########

    FROIDE_CONFIG = dict(
        user_can_hide_web=True,
        public_body_officials_public=True,
        public_body_officials_email_public=False,
        request_public_after_due_days=14,
        payment_possible=True,
        currency="Euro",
        default_law=1,
        search_engine_query=
        "http://www.google.de/search?as_q=%(query)s&as_epq=&as_oq=&as_eq=&hl=en&lr=&cr=&as_ft=i&as_filetype=&as_qdr=all&as_occt=any&as_dt=i&as_sitesearch=%(domain)s&as_rights=&safe=images",
        greetings=[rec(r"Dear (?:Mr\.?|Mr?s\.? .*?)")],
        redact_salutation=r"(?:Mr\.?|Mr?s\.?)",
        custom_replacements=[],
        closings=[rec(r"Sincerely yours,?")],
        public_body_boosts={},
        autocomplete_body_boosts={},
        dryrun=False,
        read_receipt=False,
        delivery_receipt=False,
        dsn=False,
        delivery_reporter=None,
        request_throttle=
        None,  # Set to [(15, 7 * 24 * 60 * 60),] for 15 requests in 7 days
        dryrun_domain="testmail.example.com",
        allow_pseudonym=False,
        doc_conversion_binary=None,  # replace with libreoffice instance
        doc_conversion_call_func=None,  # see settings_test for use
    )

    # ###### Email ##############

    # Django settings

    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
    EMAIL_SUBJECT_PREFIX = values.Value('[Froide] ')
    SERVER_EMAIL = values.Value('*****@*****.**')
    DEFAULT_FROM_EMAIL = values.Value('*****@*****.**')

    # Official Notification Mail goes through
    # the normal Django SMTP Backend
    EMAIL_HOST = values.Value("")
    EMAIL_PORT = values.IntegerValue(587)
    EMAIL_HOST_USER = values.Value("")
    EMAIL_HOST_PASSWORD = values.Value("")
    EMAIL_USE_TLS = values.BooleanValue(True)

    # Custom backend that also requests Delivery Status
    FOI_EMAIL_BACKEND = 'froide.foirequest.smtp.FoiEmailBackend'
    # Froide special case settings
    # IMAP settings for fetching mail
    FOI_EMAIL_PORT_IMAP = values.IntegerValue(993)
    FOI_EMAIL_HOST_IMAP = values.Value("imap.example.com")
    FOI_EMAIL_ACCOUNT_NAME = values.Value("*****@*****.**")
    FOI_EMAIL_ACCOUNT_PASSWORD = values.Value("")
    FOI_EMAIL_USE_SSL = values.BooleanValue(True)

    # SMTP settings for sending FoI mail
    FOI_EMAIL_HOST_USER = values.Value(FOI_EMAIL_ACCOUNT_NAME)
    FOI_EMAIL_HOST_FROM = values.Value(FOI_EMAIL_HOST_USER)
    FOI_EMAIL_HOST_PASSWORD = values.Value(FOI_EMAIL_ACCOUNT_PASSWORD)
    FOI_EMAIL_HOST = values.Value("smtp.example.com")
    FOI_EMAIL_PORT = values.IntegerValue(587)
    FOI_EMAIL_USE_TLS = values.BooleanValue(True)

    # The FoI Mail can use a different account
    FOI_EMAIL_DOMAIN = values.Value("example.com")

    FOI_EMAIL_TEMPLATE = None
    # Example:
    # FOI_EMAIL_TEMPLATE = lambda user_name, secret: "{username}.{secret}@{domain}" % (user_name, secret, FOI_EMAIL_DOMAIN)

    # Is the message you can send from fixed
    # or can you send from any address you like?
    FOI_EMAIL_FIXED_FROM_ADDRESS = values.BooleanValue(True)
Example #6
0
class Production(Common):

    DEBUG = values.BooleanValue(False)

    DATABASES = values.DatabaseURLValue(environ_name='DATABASE_URL')

    INSTALLED_APPS = Common.INSTALLED_APPS

    SECRET_KEY = values.SecretValue()

    STATIC_ROOT = STATIC_DIR

    MEDIA_ROOT  = MEDIA_DIR

    ALLOWED_HOSTS = ["rookie-booking.rosslyoung.com"]

    WEBPACK_LOADER = {
        'DEFAULT': {
            'CACHE': not DEBUG,
            'BUNDLE_DIR_NAME': 'js/react/',  # must end with slash
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-prod.json'),
            'POLL_INTERVAL': 0.1,
            'TIMEOUT': None,
            'IGNORE': ['.+\.hot-update.js', '.+\.map']
        }
    }

    ######################################################################
    ########## STORAGE CONFIGURATION #####################################
    ######################################################################

    # # See: http://django-storages.readthedocs.org/en/latest/index.html
    # INSTALLED_APPS += (
    #     'storages',
    # )
    #
    # # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings
    # STATICFILES_STORAGE = DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
    #
    # # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings
    # AWS_ACCESS_KEY_ID       = values.SecretValue()
    # AWS_SECRET_ACCESS_KEY   = values.SecretValue()
    # AWS_STORAGE_BUCKET_NAME = values.SecretValue()
    # AWS_AUTO_CREATE_BUCKET  = True
    # AWS_QUERYSTRING_AUTH    = False
    #
    # # see: https://github.com/antonagestam/collectfast
    # AWS_PRELOAD_METADATA = True
    # INSTALLED_APPS += ("collectfast", )
    #
    # # AWS cache settings, don't change unless you know what you're doing:
    # AWS_EXPIREY = 60 * 60 * 24 * 7
    # AWS_HEADERS = {
    #     'Cache-Control': 'max-age=%d, s-maxage=%d, must-revalidate' % (AWS_EXPIREY,
    #         AWS_EXPIREY)
    # }
    #
    # # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
    # STATIC_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
    # ########## END STORAGE CONFIGURATION
    #

    EMAIL_BACKEND     = "sgbackend.SendGridBackend"
    SENDGRID_API_KEY  = values.SecretValue(environ_prefix="", environ_name="SENDGRID_API_KEY")

    DEFAULT_FROM_EMAIL   = values.Value('Rookie Booking Admin <*****@*****.**>')

    TEMPLATES = [

        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                os.path.join(BASE_DIR, 'templates'),
                os.path.join(BASE_DIR, 'rookie_booking', 'commentry', 'templates'),
                os.path.join(BASE_DIR, 'templates', 'allauth'),
            ],
            'OPTIONS': {
                'context_processors': [
                    'django.contrib.auth.context_processors.auth',
                    'django.template.context_processors.debug',
                    'django.template.context_processors.i18n',
                    'django.template.context_processors.media',
                    'django.template.context_processors.static',
                    'django.template.context_processors.tz',
                    'django.contrib.messages.context_processors.messages',
                    'django.template.context_processors.request',
                ],
                'debug':  DEBUG,
                'string_if_invalid':  "",
                'loaders': [
                    ('django.template.loaders.cached.Loader', [
                        'django.template.loaders.filesystem.Loader',
                        'django.template.loaders.app_directories.Loader',
                    ]),
                ],
            },
        },
    ]

    SESSION_CACHE_ALIAS = "default"
    SESSION_ENGINE = "django.contrib.sessions.backends.cache"

    SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'

    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://cache-private:6383/0",
            "OPTIONS": {
                #"CLIENT_CLASS": "django_redis.client.DefaultClient",
                "PARSER_CLASS": "redis.connection.HiredisParser",
            }
        }
    }

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'file': {
                'level': 'INFO',
                'class': 'logging.FileHandler',
                'filename': '/www/logs/rookie_booking/application.log',
            },
        },
        'loggers': {
            'loggyMcLog': {
                'handlers': ['file'],
                'level': 'INFO',
                'propagate': True,
            },
            'django': {
                'handlers': ['file'],
                'level': 'INFO',
                'propagate': True,
            },
            'django.template': {
                'handlers': ['file'],
                'level': 'INFO',
                'propagate': True,
            },
        },
    }
Example #7
0
class Common(Configuration):
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = values.BooleanValue(False)

    ALLOWED_HOSTS = values.ListValue([])

    # Application definition
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'whitenoise.runserver_nostatic',
        'django.contrib.staticfiles',
        'django_extensions',
        'wagtail.core',
        'wagtail.admin',
        'wagtail.documents',
        'wagtail.snippets',
        'wagtail.users',
        'wagtail.images',
        'wagtail.embeds',
        'wagtail.search',
        'wagtail.sites',
        'wagtail.contrib.redirects',
        'wagtail.contrib.forms',
        'wagtail.contrib.sitemaps',
        'wagtail.contrib.routable_page',
        'taggit',
        'modelcluster',
        'django_social_share',
        'puputcodeblock',
        'wagtailcodeblock',
        'puput',
        'config.users',
    ]

    MIDDLEWARE = [
        # 'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'wagtail.core.middleware.SiteMiddleware',
        'wagtail.contrib.redirects.middleware.RedirectMiddleware',
    ]

    ROOT_URLCONF = 'config.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                    'django.template.context_processors.request',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'config.wsgi.application'

    # Database
    # https://docs.djangoproject.com/en/2.2/ref/settings/#databases
    DATABASES = values.DatabaseURLValue('sqlite:///{}'.format(
        os.path.join(BASE_DIR, 'db.sqlite3')))

    # Password validation
    # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME':
            'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]

    # Internationalization
    # https://docs.djangoproject.com/en/2.2/topics/i18n/
    # LANGUAGE_CODE = 'en-us'
    LANGUAGE_CODE = 'zh-hans'

    LOCALE_PATHS = [
        os.path.join(BASE_DIR, 'locale'),
    ]

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.2/howto/static-files/

    STATICFILES_FINDERS = [
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    ]

    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

    # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    MEDIA_URL = '/media/'

    AUTH_USER_MODEL = 'users.User'

    PUPUT_ENTRY_MODEL = 'puputcodeblock.models.EntryAbstract'

    WAGTAIL_SITE_NAME = 'My Blog'
    WAGTAIL_CODE_BLOCK_THEME = 'coy'
    WAGTAIL_CODE_BLOCK_LANGUAGES = (
        ('bash', 'Bash/Shell'),
        ('css', 'CSS'),
        ('diff', 'diff'),
        ('html', 'HTML'),
        ('javascript', 'Javascript'),
        ('json', 'JSON'),
        ('python', 'Python'),
        ('scss', 'SCSS'),
        ('yaml', 'YAML'),
    )

    CACHES = {
        "default": {
            "BACKEND": "django.core.cache.backends.db.DatabaseCache",
            "LOCATION": "database_cache",
        }
    }

    # Reset logging
    LOGFILE_ROOT = os.path.join(BASE_DIR, 'logs')
    # (see http://www.caktusgroup.com/blog/2015/01/27/Django-Logging-Configuration-logging_config-default-settings-logger/)

    # Reset logging
    LOGGING_CONFIG = None
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'root': {
            'level': 'DEBUG',
            'handlers': [
                'console',
            ],
        },
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse'
            }
        },
        'formatters': {
            'verbose': {
                'format':
                '%(levelname)s %(asctime)s %(module)s.%(funcName)s: %(message)s'
            },
            'simple': {
                'format': '%(levelname)s: %(module)s - %(message)s'
            },
        },
        'handlers': {
            # 'null': {
            #     'level': 'DEBUG',
            #     'class': 'django.utils.log.NullHandler',
            # },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'mail_admins': {
                'level': 'ERROR',
                'filters': [
                    'require_debug_false',
                ],
                'class': 'django.utils.log.AdminEmailHandler'
            },
            'log': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(LOGFILE_ROOT, 'web.log'),
                'maxBytes': 1024 * 1024 * 5,  # 5 MB
                'backupCount': 5,
                'formatter': 'verbose',
            },
            'log_warning': {
                'level': 'WARNING',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(LOGFILE_ROOT, 'errors.log'),
                'maxBytes': 1024 * 1024 * 5,  # 5 MB
                'backupCount': 5,
                'formatter': 'verbose',
            },
            'request_log': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(LOGFILE_ROOT, 'web-request.log'),
                'maxBytes': 1024 * 1024 * 5,  # 5 MB
                'backupCount': 5,
                'formatter': 'verbose',
            },
        },
        'loggers': {
            '': {
                'handlers': ['console', 'log_warning'],
                'level': 'INFO',  #  or 'DEBUG'
            },
            'django.db.backends': {
                'handlers': [
                    'console',
                ],
                'level': 'ERROR',
                'propagate': False,
            },
            'django': {
                'handlers': ['log', 'log_warning'],
                'propagate': True,
                'level': 'INFO',
            },
            'app': {
                'handlers': ['log_warning', 'log'],
                'propagate': True,
                'level': 'INFO',
            },
            'django.request': {
                'handlers':
                ['console', 'mail_admins', 'request_log', 'log_warning'],
                'level':
                'WARNING',
                'propagate':
                False,
            },
        }
    }

    logging.config.dictConfig(LOGGING)
Example #8
0
class Common(Configuration):

    # Application settings
    HTTP_PROTOCOL = 'https'
    ENVIRONMENT = values.Value(environ_prefix=None)
    DOMAIN = values.Value(environ_prefix=None, default='localhost:8000')

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = values.BooleanValue(False)

    TEMPLATE_DEBUG = values.BooleanValue(False)

    ALLOWED_HOSTS = []

    # Application definition
    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'django.contrib.sitemaps',

        'south',
        'rest_framework',
        'django_extensions',
        'reversion',

        'blimp_boards.utils',
        'blimp_boards.users',
        'blimp_boards.accounts',
        'blimp_boards.invitations',
        'blimp_boards.boards',
        'blimp_boards.cards',
        'blimp_boards.comments',
        'blimp_boards.notifications',
    )

    # Middlewares
    MIDDLEWARE_CLASSES = (
        'djangosecure.middleware.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )

    ROOT_URLCONF = 'blimp_boards.urls'

    WSGI_APPLICATION = 'blimp_boards.wsgi.application'

    # Database
    DATABASES = values.DatabaseURLValue(
        'postgres://{}@localhost/boards'.format(
            os.getenv('USER')), environ=True)

    # Internationalization
    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    STATIC_URL = '/static/'
    STATIC_ROOT = 'staticfiles'
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )

    # Templates
    TEMPLATE_DIRS = (
        os.path.join(BASE_DIR, 'templates'),
    )

    TEMPLATE_CONTEXT_PROCESSORS = (
        'django.contrib.auth.context_processors.auth',
        'django.core.context_processors.debug',
        'django.core.context_processors.i18n',
        'django.core.context_processors.media',
        'django.core.context_processors.static',
        'django.core.context_processors.tz',
        'django.core.context_processors.request',
        'django.contrib.messages.context_processors.messages',
        'blimp_boards.utils.context_processors.app_settings',
    )

    # Custom User Model
    AUTH_USER_MODEL = 'users.User'

    AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
        'blimp_boards.users.backends.EmailBackend',
    )

    # Logging configuration.
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
            },
        },
        'loggers': {
            'django.db.backends': {
                'level': 'ERROR',
                'handlers': ['console'],
                'propagate': False,
            },
            'blimp_boards': {
                'handlers': ['console'],
                'propagate': True,
            }
        }
    }

    # Cache
    SITEMAP_CACHE_TIMEOUT = 60 * 60 * 24

    # Django REST framework
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        ),
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'blimp_boards.users.authentication.JWTAuthentication',
            'blimp_boards.users.authentication.SessionAuthentication',
        ),
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework.renderers.JSONRenderer',
        ),
        'EXCEPTION_HANDLER':
        'blimp_boards.utils.exceptions.custom_exception_handler',
    }

    JWT_AUTH = {
        'JWT_PAYLOAD_HANDLER':
        'blimp_boafrds.utils.jwt_handlers.jwt_payload_handler',

        'JWT_EXPIRATION_DELTA': datetime.timedelta(days=90)
    }

    # Announce
    ANNOUNCE_TEST_MODE = values.BooleanValue(environ_prefix=None, default=True)

    # AWS
    AWS_ACCESS_KEY_ID = values.Value(environ_prefix=None)
    AWS_SECRET_ACCESS_KEY = values.Value(environ_prefix=None)
    AWS_STORAGE_BUCKET_NAME = values.Value(environ_prefix=None)
    AWS_SIGNATURE_EXPIRES_IN = 60 * 60 * 3

    # boards-web
    BOARDS_WEB_STATIC_URL = values.Value(environ_prefix=None)
    BOARDS_WEB_CLIENT_VERSION = values.Value(environ_prefix=None)

    # blimp-previews
    BLIMP_PREVIEWS_API_KEY = values.Value(environ_prefix=None)
    BLIMP_PREVIEWS_SECRET_KEY = values.Value(environ_prefix=None)
    BLIMP_PREVIEWS_URL = values.Value(environ_prefix=None)

    # boards-sockets
    BOARDS_SOCKETS_URL = values.Value(environ_prefix=None)
    BOARDS_SOCKETS_REDIS_URL = values.Value(environ_prefix=None)

    BOARDS_API_VERSION = 'v1'
    BOARDS_DEMO_BOARD_ID = values.Value(environ_prefix=None)

    CAMO_URL = values.Value(environ_prefix=None)

    # Email settings
    EMAIL_BACKEND = "djrill.mail.backends.djrill.DjrillBackend"
    MANDRILL_API_KEY = values.Value(environ_prefix=None)
    DEFAULT_FROM_EMAIL = values.Value(environ_prefix=None)

    # Sentry
    SENTRY_PUBLIC_DSN = values.Value(environ_prefix=None)

    # Google Analytics
    GOOGLE_ANALYTICS_PROPERTY_ID = values.Value(environ_prefix=None)
    GOOGLE_ANALYTICS_DOMAIN = values.Value(environ_prefix=None)

    # Olark
    OLARK_SITE_ID = values.Value(environ_prefix=None)

    @property
    def APPLICATION_URL(self):
        return '{}://{}'.format(self.HTTP_PROTOCOL, self.DOMAIN)

    @property
    def BOARDS_API_URL(self):
        return '{}/api/{}'.format(
            self.APPLICATION_URL, self.BOARDS_API_VERSION)
Example #9
0
class Base(Configuration):
    """
    For more info about the `django-configurations` library, see
    https://django-configurations.readthedocs.io/en/latest/
    """

    DEBUG = False

    SECRET_KEY = values.Value()

    ALLOWED_HOSTS = []
    SITE_URL = values.Value()
    SITE_ID = 1

    INSTALLED_APPS = [
        # django apps
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "django.contrib.staticfiles",
        "django.contrib.sites",
        "django.contrib.sitemaps",
        "django.contrib.humanize",
        # third-party apps
        "rest_framework",
        "storages",
        "taggit",
        "ckeditor",
        "ckeditor_uploader",
        # project apps
        "buildings",
        "pages",
        "blog",
    ]

    MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "whitenoise.middleware.WhiteNoiseMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
    ]

    ROOT_URLCONF = "seismic_site.urls"

    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "APP_DIRS": True,
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.debug",
                    "django.template.context_processors.request",
                    "django.contrib.auth.context_processors.auth",
                    "django.contrib.messages.context_processors.messages",
                ]
            },
        }
    ]

    WSGI_APPLICATION = "seismic_site.wsgi.application"

    # Database
    # https://docs.djangoproject.com/en/2.2/ref/settings/#databases

    DATABASES = values.DatabaseURLValue()

    # Password validation
    # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"  # noqa
        },
        {
            "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"  # noqa
        },
        {
            "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"  # noqa
        },
        {
            "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"  # noqa
        },
    ]

    # Internationalization
    # https://docs.djangoproject.com/en/2.2/topics/i18n/

    LANGUAGE_CODE = values.Value(default="en-us")
    TIME_ZONE = "UTC"
    USE_I18N = True
    USE_L10N = True
    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.2/howto/static-files/

    STATIC_URL = "/static/"
    STATIC_ROOT = os.path.join(BASE_DIR, "./public/static")
    # STATICFILES_DIRS = (
    #     os.path.join(BASE_DIR, 'static'),
    # )
    STATICFILES_STORAGE = (
        "whitenoise.storage.CompressedManifestStaticFilesStorage"
    )

    MEDIA_URL = "/media/"
    MEDIA_ROOT = os.path.join(BASE_DIR, "./public/media")

    CKEDITOR_UPLOAD_PATH = "uploads/"

    REST_FRAMEWORK = {
        # Use Django's standard `django.contrib.auth` permissions,
        # or allow read-only access for unauthenticated users.
        "DEFAULT_PERMISSION_CLASSES": [
            "rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly"
        ]
    }
Example #10
0
class BaseConfiguration(Configuration):
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    SECRET_KEY = 'secret'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = values.BooleanValue(False)

    ALLOWED_HOSTS = values.ListValue([])

    # Application definition

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'django_extensions',
        'django_filters',
        'rest_framework',
        'rest_framework.authtoken',
        'corsheaders',
        'simple_history',
        'drf_yasg',
        'rules.apps.AutodiscoverRulesConfig',
        'core',
        'agency',
        'client',
        'survey',
        'program',
        'eligibility',
        'security',
        'note',
        'matching',
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'simple_history.middleware.HistoryRequestMiddleware',
        'core.middleware.LoggingMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    ROOT_URLCONF = 'backend.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'backend.wsgi.application'

    DATABASES = values.DatabaseURLValue()

    # Password validation
    # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME':
            'django.contrib.auth.password_validation.MinimumLengthValidator',
            'OPTIONS': {
                'min_length': 6,
            }
        },
    ]

    # Internationalization
    # https://docs.djangoproject.com/en/3.0/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/3.0/howto/static-files/

    STATIC_URL = '/static/'

    REST_FRAMEWORK = {
        # Use Django's standard `django.contrib.auth` permissions,
        # or allow read-only access for unauthenticated users.
        'DEFAULT_PERMISSION_CLASSES':
        ['rest_framework.permissions.IsAuthenticated'],
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.TokenAuthentication',
            'rest_framework.authentication.SessionAuthentication',
        ],
        'DEFAULT_PAGINATION_CLASS':
        'core.pagination.PageNumberPaginationWithTotalPages',
        'DEFAULT_FILTER_BACKENDS': [
            'django_filters.rest_framework.DjangoFilterBackend',
            'rest_framework.filters.OrderingFilter'
        ],
        'PAGE_SIZE':
        100,
    }

    CORS_ORIGIN_ALLOW_ALL = True
    CORS_ALLOW_CREDENTIALS = True
    CORS_ORIGIN_WHITELIST = [
        'http://localhost:3030',
    ]
    CORS_ORIGIN_REGEX_WHITELIST = [
        'http://localhost:3030',
    ]

    SWAGGER_SETTINGS = {
        'SECURITY_DEFINITIONS': {
            'DRF Token': {
                'type': 'apiKey',
                'name': 'Authorization',
                'in': 'header'
            }
        },
        'LOGIN_URL': '/admin/login/',
        'LOGOUT_URL': '/admin/logout/',
    }

    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    # Logging
    LOG_FILE = values.Value('./../application.log')
    LOG_LEVEL = values.Value('DEBUG')
    LOGGING_CONFIG = None

    BUILD_VERSION = values.Value('development')
    BUILD_DATE = values.Value(datetime.now())

    def __init__(self):
        print(f'Using {self.__class__.__name__} config')
        print(
            f'Logging {self.LOG_LEVEL} messages to {os.path.abspath(self.LOG_FILE)}'
        )
        setup_logging(str(self.LOG_LEVEL), str(self.LOG_FILE))
Example #11
0
class Common(Configuration):
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    ENVIRONMENT = values.Value(environ_prefix=None, default="development")

    APPNAME = "horas"

    DEBUG = False

    SECRET_KEY = values.SecretValue(environ_prefix=None)
    SSO_SECRET_KEY = values.SecretValue(environ_prefix=None)

    DISCOURSE_SSO_REDIRECT_URL = "http://comunidad.1hora.org/session/sso_login?"

    ALLOWED_HOSTS = ["unahora.herokuapp.com", "1hora.org"]

    SITE_ID = 1

    DATE_FORMAT = "D, F j, Y"

    # Application definition
    INSTALLED_APPS = (
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "django.contrib.staticfiles",
        "django.contrib.sites",
        # Third-party
        "django_extensions",
        "allauth",
        "allauth.account",
        "allauth.socialaccount",
        "allauth.socialaccount.providers.twitter",
        "allauth.socialaccount.providers.facebook",
        "allauth.socialaccount.providers.google",
        "taggit",
        "pinax.notifications",
        "gunicorn",
        "storages",
        "collectfast",
        "bootstrap3",
        "markdown_deux",
        "django_fsm_log",
        # Local apps
        "apps.core",
        "apps.profiles",
        "apps.search",
        "apps.meetings",
        "apps.stats",
        "apps.sso",
        "apps.comments",
    )

    MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.locale.LocaleMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
        "apps.core.middleware.TimezoneMiddleware",
        "apps.core.middleware.EnsureCompleteProfileMiddleware",
        "debug_toolbar.middleware.DebugToolbarMiddleware",
    ]

    TEMPLATES = [{
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, "templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "debug":
            DEBUG,
            "context_processors": [
                "django.contrib.auth.context_processors.auth",
                "django.template.context_processors.debug",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.tz",
                "django.contrib.messages.context_processors.messages",
                "django.template.context_processors.request",
            ],
        },
    }]

    AUTHENTICATION_BACKENDS = (
        "django.contrib.auth.backends.ModelBackend",
        "allauth.account.auth_backends.AuthenticationBackend",
    )

    # Custom user model
    AUTH_USER_MODEL = "profiles.User"
    LOGIN_URL = "/accounts/login/"

    # allauth settings
    ACCOUNT_ADAPTER = "apps.profiles.adapters.AccountAdapter"
    ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https"
    ACCOUNT_EMAIL_SUBJECT_PREFIX = "[Horas] "
    ACCOUNT_LOGOUT_ON_GET = True
    ACCOUNT_EMAIL_REQUIRED = True
    ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = False
    ACCOUNT_CONFIRM_EMAIL_ON_GET = True
    ACCOUNT_LOGOUT_REDIRECT_URL = LOGIN_URL
    ACCOUNT_USERNAME_BLACKLIST = ["admin"]
    ACCOUNT_SIGNUP_FORM_CLASS = "apps.profiles.forms.SignupForm"

    ROOT_URLCONF = "horas.urls"

    WSGI_APPLICATION = "horas.wsgi.application"

    # Database
    # https://docs.djangoproject.com/en/dev/ref/settings/#databases
    DATABASES = values.DatabaseURLValue("sqlite://{}".format(
        os.path.join(BASE_DIR, "db.sqlite3")))

    # Internationalization
    # https://docs.djangoproject.com/en/dev/topics/i18n/
    LANGUAGE_CODE = "es"

    LOCALE_PATHS = [os.path.join(os.path.dirname(__file__), "locale")]
    LANGUAGES = (("es", _("Spanish")), ("en", _("English")))

    TIME_ZONE = "UTC"
    HORAS_DEFAULT_TZ = os.environ.get("HORAS_DEFAULT_TZ")

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    DEFAULT_FILE_STORAGE = "storages.backends.s3.S3Storage"

    AWS_PRELOAD_METADATA = True
    AWS_ACCESS_KEY_ID = values.Value(environ_prefix=None)
    AWS_SECRET_ACCESS_KEY = values.Value(environ_prefix=None)
    AWS_STORAGE_BUCKET_NAME = values.Value(environ_prefix=None)

    STATIC_URL = "/static/public/"

    STATIC_ROOT = os.path.join(BASE_DIR, "static")

    STATICFILES_DIRS = (os.path.join(BASE_DIR, "static", "public"), )

    ANNOUNCE_TEST_MODE = False
class Base(Core):
    """Configuration that may change per-environment, some with defaults."""

    SECRET_KEY = values.SecretValue()

    DEBUG = values.BooleanValue(default=False)

    ALLOWED_HOSTS = values.ListValue([])

    #: The URL under which this instance is running
    SITE_URL = values.URLValue('http://*****:*****@db/postgres')

    REDIS_URL_DEFAULT = 'redis://redis:6379/1'
    CACHES = values.CacheURLValue(
        REDIS_URL_DEFAULT,
        environ_prefix=None,
        environ_name='REDIS_URL',
    )
    # Use redis as the Celery broker.
    CELERY_BROKER_URL = os.environ.get('REDIS_URL', REDIS_URL_DEFAULT)

    LOGGING_USE_JSON = values.BooleanValue(False)

    OIDC_RP_CLIENT_ID = values.Value(
        environ_name='OIDC_RP_CLIENT_ID', environ_prefix=None)
    OIDC_RP_CLIENT_SECRET = values.Value(
        environ_name='OIDC_RP_CLIENT_SECRET', environ_prefix=None)
    OIDC_OP_AUTHORIZATION_ENDPOINT = values.Value(
        environ_name='OIDC_OP_AUTHORIZATION_ENDPOINT', environ_prefix=None)
    OIDC_OP_TOKEN_ENDPOINT = values.Value(
        environ_name='OIDC_OP_TOKEN_ENDPOINT', environ_prefix=None)
    OIDC_OP_USER_ENDPOINT = values.Value(
        environ_name='OIDC_OP_USER_ENDPOINT', environ_prefix=None)
    OIDC_OP_DOMAIN = values.Value(
        environ_name='OIDC_OP_DOMAIN', environ_prefix=None)

    def LOGGING(self):
        return {
            'version': 1,
            'disable_existing_loggers': False,
            'formatters': {
                'json': {
                    '()': 'dockerflow.logging.JsonLogFormatter',
                    'logger_name': 'atmo',
                },
                'verbose': {
                    'format': '%(levelname)s %(asctime)s %(name)s %(message)s',
                },
                'django.server': {
                    '()': 'django.utils.log.ServerFormatter',
                    'format': '[%(server_time)s] %(message)s',
                },
            },
            'handlers': {
                'console': {
                    'level': 'DEBUG',
                    'class': 'logging.StreamHandler',
                    'formatter': 'json' if self.LOGGING_USE_JSON else 'verbose',
                },
                'sentry': {
                    'level': 'ERROR',
                    'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
                },
                'django.server': {
                    'level': 'INFO',
                    'class': 'logging.StreamHandler',
                    'formatter': 'django.server',
                },
            },
            'loggers': {
                'root': {
                    'level': 'INFO',
                    'handlers': ['sentry', 'console'],
                },
                'django.db.backends': {
                    'level': 'ERROR',
                    'handlers': ['console'],
                    'propagate': False,
                },
                'django.server': {
                    'handlers': ['django.server'],
                    'level': 'INFO',
                    'propagate': False,
                },
                'raven': {
                    'level': 'DEBUG',
                    'handlers': ['console'],
                    'propagate': False,
                },
                'sentry.errors': {
                    'level': 'DEBUG',
                    'handlers': ['console'],
                    'propagate': False,
                },
                'atmo': {
                    'level': 'DEBUG',
                    'handlers': ['console'],
                    'propagate': False,
                },
                'celery.task': {
                    'level': 'DEBUG',
                    'handlers': ['console'],
                    'propagate': False,
                },
                'redbeat.schedulers': {
                    'level': 'DEBUG',
                    'handlers': ['console'],
                    'propagate': False,
                },
                'request.summary': {
                    'level': 'DEBUG',
                    'handlers': ['console'],
                    'propagate': False,
                },
                'mozilla_django_oidc': {
                    'level': 'INFO',
                    'handlers': ['console'],
                    'propagate': False,
                },
            },
        }
Example #13
0
class Common(Configuration):

    ########## APP CONFIGURATION
    DJANGO_APPS = (
        # Default Django apps:
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        # Useful template tags:
        # 'django.contrib.humanize',
    )
    THIRD_PARTY_APPS = (
        'south',  # Database migration helpers:
        'crispy_forms',  # Form layouts
        'avatar',  # for user avatars
        'compressor',  # assets management
        'sorl.thumbnail',  #thumbnails
    )

    # Apps specific for this project go here.
    LOCAL_APPS = (
        'users',  # custom users app
        # Your stuff: custom apps go here
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
    INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

    INSTALLED_APPS += (
        # Needs to come last for now because of a weird edge case between
        #   South and allauth
        'allauth',  # registration
        'allauth.account',  # registration
        'allauth.socialaccount',  # registration
        'admin_tools',  #admin tools
        'admin_tools.menu',
        'admin_tools.theming',
        'admin_tools.dashboard',
        'django.contrib.admin',  # Admin
    )
    ########## END APP CONFIGURATION

    ########## MIDDLEWARE CONFIGURATION
    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )
    ########## END MIDDLEWARE CONFIGURATION

    ########## DEBUG
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
    DEBUG = values.BooleanValue(True)

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
    TEMPLATE_DEBUG = DEBUG
    ########## END DEBUG

    ########## SECRET CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
    # Note: This key only used for development and testing.
    #       In production, this is changed to a values.SecretValue() setting
    SECRET_KEY = "CHANGEME!!!"
    ########## END SECRET CONFIGURATION

    ########## ADMIN TOOLS CONFIGURATION
    ADMIN_TOOLS_INDEX_DASHBOARD = 'config.dashboard.CustomIndexDashboard'
    ########## END ADMIN TOOLS CONFIGURATION

    ########## FIXTURE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
    FIXTURE_DIRS = (join(BASE_DIR, 'fixtures'), )
    ########## END FIXTURE CONFIGURATION

    ########## MANAGER CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
    ADMINS = (('{{cookiecutter.author_name}}', '{{cookiecutter.email}}'), )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
    MANAGERS = ADMINS
    ########## END MANAGER CONFIGURATION

    ########## DATABASE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
    DATABASES = values.DatabaseURLValue(
        'postgres://postgres@/{{cookiecutter.repo_name}}')
    ########## END DATABASE CONFIGURATION

    ########## CACHING AND SESSIONS CONFIGURATION
    CACHES = {
        "default": {
            "BACKEND": "redis_cache.cache.RedisCache",
            "LOCATION": "127.0.0.1:6379:0",
            "OPTIONS": {
                "CLIENT_CLASS": "redis_cache.client.DefaultClient",
            }
        }
    }
    SESSION_ENGINE = 'redis_sessions.session'
    ########## END CACHING AND SESSIONS CONFIGURATION

    ########## REDIS CONFIGURATION
    THUMBNAIL_REDIS_HOST = '127.0.0.1'
    THUMBNAIL_REDIS_PORT = 6379
    THUMBNAIL_REDIS_DB = 0
    THUMBNAIL_KEY_PREFIX = 'thumb'
    SESSION_REDIS_HOST = '127.0.0.1'
    SESSION_REDIS_PORT = 6379
    SESSION_REDIS_DB = 0
    SESSION_REDIS_PREFIX = 'sess'
    ########## END REDIS CONFIGURATION

    ########## GENERAL CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
    TIME_ZONE = 'Europe/Moscow'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
    LANGUAGE_CODE = 'ru-ru'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
    SITE_ID = 1

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
    USE_I18N = True

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
    USE_L10N = True

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
    USE_TZ = True

    # Locales
    gettext = lambda s: s
    LANGUAGES = (
        ('ru', gettext('Russian')),
        ('en', gettext('English')),
    )
    LOCALE_PATHS = (join(BASE_DIR, 'locale'), )
    ########## END GENERAL CONFIGURATION

    ########## TEMPLATE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
    TEMPLATE_CONTEXT_PROCESSORS = (
        'django.contrib.auth.context_processors.auth',
        "allauth.account.context_processors.account",
        "allauth.socialaccount.context_processors.socialaccount",
        'django.core.context_processors.debug',
        'django.core.context_processors.i18n',
        'django.core.context_processors.media',
        'django.core.context_processors.static',
        'django.core.context_processors.tz',
        'django.contrib.messages.context_processors.messages',
        'django.core.context_processors.request',
        # Your stuff: custom template context processers go here
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
    TEMPLATE_DIRS = (join(BASE_DIR, 'templates'), )

    TEMPLATE_LOADERS = (
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )

    # See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs
    CRISPY_TEMPLATE_PACK = 'bootstrap3'
    ########## END TEMPLATE CONFIGURATION

    ########## STATIC FILE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
    STATIC_ROOT = 'staticfiles'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
    STATIC_URL = '/static/'

    # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
    STATICFILES_DIRS = (join(BASE_DIR, 'static'), )

    # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
        'compressor.finders.CompressorFinder',
    )
    ########## END STATIC FILE CONFIGURATION

    ########## MEDIA CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
    MEDIA_ROOT = join(BASE_DIR, '../media')

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
    MEDIA_URL = '/media/'
    ########## END MEDIA CONFIGURATION

    ########## URL ConfigurationAunque los importantísimos yacimientos de gas de Siria no parezcan tener hoy el mismo valor que hace 12 años, momento en que se planificó la guerra contra ese país, no es menos cierto que siguen siendo un factor invisible del conflicto. La Comisión Económica de la Coalición de la oposición externa siria se ha dedicado esencialmente a la repartición del gas que se haría entre los aliados después de la caída del Estado sirio. Pero, como ese momento no acaba de llegar, las grandes potencias van a tener que revisar sus apuestas.1314566-1730036
    ROOT_URLCONF = 'config.urls'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
    WSGI_APPLICATION = 'config.wsgi.application'
    ########## End URL Configuration

    ########## AUTHENTICATION CONFIGURATION
    AUTHENTICATION_BACKENDS = (
        "django.contrib.auth.backends.ModelBackend",
        "allauth.account.auth_backends.AuthenticationBackend",
    )

    # Some really nice defaults
    ACCOUNT_AUTHENTICATION_METHOD = "email"
    ACCOUNT_EMAIL_REQUIRED = True
    ACCOUNT_USERNAME_REQUIRED = False
    ACCOUNT_EMAIL_VERIFICATION = "mandatory"
    ########## END AUTHENTICATION CONFIGURATION

    ########## Custom user app defaults
    # Select the correct user model
    AUTH_USER_MODEL = "users.User"
    LOGIN_REDIRECT_URL = "users:redirect"
    ########## END Custom user app defaults

    ########## SLUGLIFIER
    AUTOSLUG_SLUGIFY_FUNCTION = "slugify.slugify"
    ########## END SLUGLIFIER

    ########## SORL THUMBNAIL
    THUMBNAIL_KVSTORE = "sorl.thumbnail.kvstores.redis_kvstore.KVStore"
    ########## END SORL THUMBNAIL

    ########## DJANGO COMPRESSOR
    COMPRESS_ENABLED = True
    COMPRESS_CSS_FILTERS = [
        'compressor.filters.css_default.CssAbsoluteFilter',
        'compressor.filters.datauri.CssDataUriFilter',
        'compressor.filters.cssmin.CSSMinFilter'
    ]
    COMPRESS_JS_FILTERS = ['compressor.filters.jsmin.SlimItFilter']
    COMPRESS_DATA_URI_MAX_SIZE = 4096
    ########## END DJANGO COMPRESSOR

    ########## LOGGING CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
    # A sample logging configuration. The only tangible logging
    # performed by this configuration is to send an email to
    # the site admins on every HTTP 500 error when DEBUG=False.
    # See http://docs.djangoproject.com/en/dev/topics/logging for
    # more details on how to customize your logging configuration.
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse'
            }
        },
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'filters': ['require_debug_false'],
                'class': 'django.utils.log.AdminEmailHandler'
            }
        },
        'loggers': {
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
        }
    }
Example #14
0
class Common(Configuration):

    ADMINS = (
        ('Admin', '*****@*****.**'),
    )

    AUTH_USER_MODEL = 'userprofile.User'

    MANAGERS = ADMINS

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    sys.path.insert(0, os.path.join(BASE_DIR, 'farmstand/apps'))

    USE_SOUTH = False

    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = False

    TEMPLATE_DEBUG = False

    DEFAULT_CURRENCY = 'USD'
    DEFAULT_WEIGHT = 'Ounces'

    CANONICAL_HOSTNAME = os.environ.get('CANONICAL_HOSTNAME', 'localhost:8000')
    PAYMENT_BASE_URL = 'http://%s/' % CANONICAL_HOSTNAME

    PAYMENT_MODEL = 'order.Payment'

    PAYMENT_VARIANTS = {
        'default': ('payments.dummy.DummyProvider', {})
    }

    PAYMENT_HOST = os.environ.get('PAYMENT_HOST', 'localhost:8000')

    SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
    SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'

    CHECKOUT_PAYMENT_CHOICES = [
        ('default', 'Dummy provider')
    ]

    FACEBOOK_APP_ID = ""
    GOOGLE_CLIENT_ID = ""


    # Application definition

    INSTALLED_APPS = (
        'suit',
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.redirects",
        "django.contrib.sessions",
        "django.contrib.sites",
        "django.contrib.sitemaps",
        "django.contrib.staticfiles",

        "django_extensions",
        'floppyforms',
        'rest_framework',

        # Saleor apps
        'saleor.userprofile',
        'saleor.product',
        'saleor.cart',
        'saleor.checkout',
        'saleor.core',
        'saleor.order',
        'saleor.registration',
        'saleor.dashboard',

        # External apps
        'versatileimagefield',
        'django_prices',
        'emailit',
        'mptt',
        'payments',
        'selectable',
        'materializecssform'
    )

    TEMPLATE_CONTEXT_PROCESSORS = Configuration.TEMPLATE_CONTEXT_PROCESSORS + \
        ("django.core.context_processors.request",
         "django.core.context_processors.tz",
         "saleor.core.context_processors.canonical_hostname",
         "saleor.core.context_processors.default_currency",
         "saleor.core.context_processors.categories"
        )

    MIDDLEWARE_CLASSES = (
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'saleor.cart.middleware.CartMiddleware',
        'saleor.core.middleware.DiscountMiddleware',
        'saleor.core.middleware.GoogleAnalytics',

    )

    STATICFILES_FINDERS = (
        "django.contrib.staticfiles.finders.FileSystemFinder",
        "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    )

    ACCOUNT_AUTHENTICATION_METHOD = "email"
    ACCOUNT_USER_MODEL_USERNAME_FIELD = None
    ACCOUNT_EMAIL_REQUIRED = True
    ACCOUNT_UNIQUE_EMAIL = True
    ACCOUNT_USERNAME_REQUIRED = False

    AUTHENTICATION_BACKENDS = (
        "django.contrib.auth.backends.ModelBackend",
        'saleor.registration.backends.EmailPasswordBackend',
        #'saleor.registration.backends.ExternalLoginBackend',
        'saleor.registration.backends.TrivialBackend',
        "allauth.account.auth_backends.AuthenticationBackend",)

    ROOT_URLCONF = 'farmstand.urls'

    WSGI_APPLICATION = 'farmstand.wsgi.application'

    DATABASES = values.DatabaseURLValue('sqlite:///{0}'.format(
        os.path.join(BASE_DIR, 'db.sqlite3'),
        environ=True))

    NEVERCACHE_KEY = values.Value('klladsf-wefkjlwef-wekjlwef--wefjlkjfslkxvl')

    #CACHES = values.CacheURLValue('memcached://127.0.0.1:11211')

    # Internationalization
    # https://docs.djangoproject.com/en/1.6/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'America/New_York'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    SITE_ID = 1

    ALLOWED_HOSTS = values.Value('*')

    SESSION_EXPIRE_AT_BROWSER_CLOSE = True

    PROJECT_DIRNAME = BASE_DIR.split(os.sep)[-1]

    CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_DIRNAME

    MEDIA_URL = "/media/"

    MEDIA_ROOT = os.path.join(BASE_DIR, 'public/media')

    TEMPLATE_DIRS = (os.path.join(BASE_DIR, "farmstand/templates"),)

    STATIC_URL = '/static/'

    STATIC_ROOT = os.path.join(BASE_DIR, 'public/static')

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, "farmstand/static"),
    )

    #DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

    AWS_ACCESS_KEY_ID = values.Value()
    AWS_SECRET_ACCESS_KEY = values.Value()
    AWS_STORAGE_BUCKET_NAME = 'example.com'
    AWS_HEADERS = {'ExpiresDefault': 'access plus 30 days',
                   'Cache-Control': 'max-age=86400', }

    # Account activations automatically expire after this period
    ACCOUNT_ACTIVATION_DAYS = 14

    LOGIN_EXEMPT_URLS = ['', '/',
                         '/accounts/login/',
                         'login',
                         '/accounts/signup/']

    LOGIN_URL = '/accounts/login/'
    LOGIN_REDIRECT_URL = '/'
    LOGOUT_URL = '/accounts/logout/'

    # A sample logging configuration. The only tangible logging
    # performed by this configuration is to send an email to
    # the site admins on every HTTP 500 error when DEBUG=False.
    # See http://docs.djangoproject.com/en/dev/topics/logging for
    # more details on how to customize your logging configuration.
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'class': 'django.utils.log.AdminEmailHandler'
            }
        },
        'loggers': {
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
        }
    }
Example #15
0
class Common(Configuration):
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    SECRET_KEY = values.SecretValue()
    DEBUG = values.BooleanValue(False)
    ALLOWED_HOSTS = values.ListValue(["*"])
    INSTALLED_APPS = [
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "whitenoise.runserver_nostatic",
        "django.contrib.staticfiles",
        "hijack",
        "hijack_admin",
        "compat",
        "djmoney",
        "rest_framework",
        "rest_framework.authtoken",
        "drf_generators",
        "django_filters",
        "django_extensions",
        "debug_toolbar",
        "bartender.users",
        "bartender.drinks",
    ]

    MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "whitenoise.middleware.WhiteNoiseMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
    ]

    ROOT_URLCONF = "bartender.urls"

    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "DIRS": [os.path.join(BASE_DIR, "templates")],
            "APP_DIRS": True,
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.debug",
                    "django.template.context_processors.request",
                    "django.contrib.auth.context_processors.auth",
                    "django.contrib.messages.context_processors.messages",
                ],
            },
        },
    ]

    WSGI_APPLICATION = "bartender.wsgi.application"

    DATABASES = values.DatabaseURLValue("sqlite:///{}".format(
        os.path.join(BASE_DIR, "db.sqlite3")))

    AUTH_PASSWORD_VALIDATORS = [
        {
            "NAME":
            "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.MinimumLengthValidator",
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.CommonPasswordValidator",
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.NumericPasswordValidator",
        },
    ]

    LANGUAGE_CODE = "en-us"

    TIME_ZONE = "UTC"

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    STATIC_URL = "/static/"
    STATIC_ROOT = os.path.join(BASE_DIR, "static")
    STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

    DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"

    AWS_ACCESS_KEY_ID = values.SecretValue()
    AWS_SECRET_ACCESS_KEY = values.SecretValue()
    AWS_STORAGE_BUCKET_NAME = values.Value("bartender")
    AWS_S3_ENDPOINT_URL = values.Value("https://s3.malik.consulting")

    TELEGRAM_TOKEN = values.SecretValue()

    AUTH_USER_MODEL = "users.User"

    DEFAULT_CURRENCY = values.Value("EUR")

    REST_FRAMEWORK = {
        "DEFAULT_PAGINATION_CLASS":
        "rest_framework.pagination.PageNumberPagination",
        "DEFAULT_AUTHENTICATION_CLASSES": [
            "rest_framework.authentication.TokenAuthentication",
            "rest_framework.authentication.SessionAuthentication",
        ],
        "PAGE_SIZE":
        50,
        "DEFAULT_THROTTLE_CLASSES": [
            "rest_framework.throttling.AnonRateThrottle",
            "rest_framework.throttling.UserRateThrottle",
        ],
        "DEFAULT_THROTTLE_RATES": {
            "anon": "100/day",
            "user": "******"
        },
        "DEFAULT_FILTER_BACKENDS":
        ["django_filters.rest_framework.DjangoFilterBackend"],
    }

    DRF_ACCESS_POLICY = {
        "reusable_conditions": "bartender.global_access_conditions"
    }

    HIJACK_LOGIN_REDIRECT_URL = "/api/v1/"
    HIJACK_LOGOUT_REDIRECT_URL = "/admin"
    HIJACK_ALLOW_GET_REQUESTS = True
    HIJACK_REGISTER_ADMIN = False
Example #16
0
class Base(Configuration):
    IS_TEST = values.BooleanValue(False)
    DEBUG = values.BooleanValue(False)
    SECRET_KEY = values.SecretValue()

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    DATABASES = values.DatabaseURLValue()

    ALLOWED_HOSTS = []

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'rest_framework.authtoken',
        'corsheaders',
        'djoser',
        'apps.account',
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    ROOT_URLCONF = 'sample.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    # WSGI

    WSGI_APPLICATION = 'sample.wsgi.application'

    # Password validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME':
            'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]

    AUTH_USER_MODEL = 'account.User'

    # Internationalization

    LANGUAGE_CODE = 'ja-JP'
    TIME_ZONE = 'Asia/Tokyo'
    USE_I18N = True
    USE_L10N = True
    USE_TZ = True

    # Static files
    STATIC_URL = '/static/'
    STATIC_BASE = os.path.join(BASE_DIR, 'static')
    STATICFILES_DIRS = (STATIC_BASE, )

    # REST
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
            'rest_framework.authentication.BasicAuthentication',
            'rest_framework.authentication.SessionAuthentication',
        ),
        'DEFAULT_PAGINATION_CLASS':
        'rest_framework.pagination.PageNumberPagination',
        'PAGE_SIZE':
        100,
    }

    DJOSER = {
        'SERIALIZERS': {
            'user': '******',
        }
    }
Example #17
0
class Common(Configuration):

    DEBUG = values.BooleanValue(True)

    SECRET_KEY = values.SecretValue()

    FIXTURE_DIRS = (join(BASE_DIR, 'fixtures'),)

    ADMINS = (
        ('Ross', '*****@*****.**'),
    )

    MANAGERS = ADMINS

    TIME_ZONE = 'Europe/London'

    LANGUAGE_CODE = 'en-gb'

    SITE_ID = 1

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    DATABASES = values.DatabaseURLValue(environ_name='DATABASE_URL_LOCAL')

    CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': ''
        }
    }

    DJANGO_APPS = [
        #'django_admin_bootstrapped.bootstrap3',
        'django_admin_bootstrapped',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'django.contrib.sites',
        'django.contrib.admindocs',
        'django.contrib.gis',
    ]

    LOCAL_APPS = [
        'rookie_booking.booking_calendar',
        'rookie_booking.userprofile',
        # 'rookie_booking.commentry',
        'rookie_booking.core',
        'rookie_booking.dashboard',
    ]

    THIRD_PARTY_APPS = [
        # 'django_comments',
        'bootstrap3',
        'widget_tweaks',
        'gunicorn',
        'configurations',
        'mptt',
        'django_mptt_admin',
        'crispy_forms',
        'versatileimagefield',
        'materializecssform',
        'webpack_loader',

        'allauth',
        'allauth.account',
        'allauth.socialaccount',
        'allauth.socialaccount.providers.facebook',
        'allauth.socialaccount.providers.twitter',
        'allauth.socialaccount.providers.google',
        'allauth.socialaccount.providers.slack',

    ]

    INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS + THIRD_PARTY_APPS

    COMMENTS_APP = 'rookie_booking.commentry'

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    TEMPLATES = [

        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                os.path.join(BASE_DIR, 'templates'),
                os.path.join(BASE_DIR, 'rookie_booking', 'commentry', 'templates'),
                os.path.join(BASE_DIR, 'templates', 'allauth'),
            ],
            'OPTIONS': {
                'context_processors': [
                    'django.contrib.auth.context_processors.auth',
                    'django.template.context_processors.debug',
                    'django.template.context_processors.i18n',
                    'django.template.context_processors.media',
                    'django.template.context_processors.static',
                    'django.template.context_processors.tz',
                    'django.contrib.messages.context_processors.messages',
                    'django.template.context_processors.request',
                ],
                'debug':  DEBUG,
                'string_if_invalid':  "<< MISSING VARIABLE >>",
                'loaders': [
                    'django.template.loaders.filesystem.Loader',
                    'django.template.loaders.app_directories.Loader',
                ],
            },
        },
    ]

    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )

    STATIC_URL = '/static/'

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, "rookie_booking", "static"),
        os.path.join(BASE_DIR, "rookie_booking", "commentry", "static"),
        # os.path.join(BASE_DIR, "rookie_booking", "react-redux", "dist"),
    )

    STATIC_ROOT = join(BASE_DIR,'static_site_wide')

    MEDIA_ROOT = join(PROJECT_DIR,'media')

    MEDIA_URL = '/media/'

    ROOT_URLCONF = 'rookie_booking.urls'

    WSGI_APPLICATION = 'rookie_booking.wsgi.application'

    LOGIN_URL = '/accounts/login/'

    LOGIN_REDIRECT_URL = 'home' #named url

    AUTH_USER_MODEL = 'userprofile.User'

    AUTHENTICATION_BACKENDS = (
         "django.contrib.auth.backends.ModelBackend",
         "allauth.account.auth_backends.AuthenticationBackend",
    )

    # ACCOUNT_ADAPTER = "userprofile.adapter.UserProfileAccountAdapter"
    ACCOUNT_ADAPTER = "allauth.account.adapter.DefaultAccountAdapter"
    ACCOUNT_AUTHENTICATION_METHOD ="email"
    ACCOUNT_CONFIRM_EMAIL_ON_GET =True
    ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL
    ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL =None
    ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS =3
    ACCOUNT_EMAIL_REQUIRED =True
    ACCOUNT_EMAIL_VERIFICATION ="mandatory"
    ACCOUNT_EMAIL_SUBJECT_PREFIX ="[Site]"
    ACCOUNT_DEFAULT_HTTP_PROTOCOL ="http"
    ACCOUNT_FORMS ={}
    ACCOUNT_LOGOUT_ON_GET =False
    ACCOUNT_LOGOUT_REDIRECT_URL ="/"
    ACCOUNT_SIGNUP_FORM_CLASS =None
    ACCOUNT_SIGNUP_PASSWORD_VERIFICATION =True
    ACCOUNT_UNIQUE_EMAIL =True
    ACCOUNT_USER_MODEL_USERNAME_FIELD ="username"
    ACCOUNT_USER_MODEL_EMAIL_FIELD ="email"
    #ACCOUNT_USER_DISPLAY =a callable returning user.username
    ACCOUNT_USERNAME_MIN_LENGTH =1
    ACCOUNT_USERNAME_BLACKLIST =[]
    ACCOUNT_USERNAME_REQUIRED =True
    ACCOUNT_PASSWORD_INPUT_RENDER_VALUE =False
    ACCOUNT_PASSWORD_MIN_LENGTH =6
    ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION =True
    ACCOUNT_SESSION_REMEMBER =None
    ACCOUNT_SESSION_COOKIE_AGE =1814400
    SOCIALACCOUNT_ADAPTER ="userprofile.adapter.UserProfileSocialAccountAdapter"
    #SOCIALACCOUNT_ADAPTER ="allauth.socialaccount.adapter.DefaultSocialAccountAdapter"
    SOCIALACCOUNT_QUERY_EMAIL =ACCOUNT_EMAIL_REQUIRED
    SOCIALACCOUNT_AUTO_SIGNUP =True
    SOCIALACCOUNT_EMAIL_REQUIRED =ACCOUNT_EMAIL_REQUIRED ############
    SOCIALACCOUNT_EMAIL_VERIFICATION ='optional' #################
    SOCIALACCOUNT_FORMS ={}
    SOCIALACCOUNT_PROVIDERS = dict
    SOCIALACCOUNT_STORE_TOKENS =True

    AUTOSLUG_SLUGIFY_FUNCTION = "slugify.slugify"

    WEBPACK_LOADER = {
        'DEFAULT': {
            'CACHE': not DEBUG,
            'BUNDLE_DIR_NAME': 'js/react/',  # must end with slash
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
            'POLL_INTERVAL': 0.1,
            'TIMEOUT': None,
            'IGNORE': ['.+\.hot-update.js', '.+\.map']
        }
    }
Example #18
0
class Common(Static, Configuration):

    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '9ne67900mr&nfg+ajo7(+r75mf$^k+&zspexjl)+on#%685!86'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    TEMPLATE_DEBUG = DEBUG

    ALLOWED_HOSTS = []

    AUTH_USER_MODEL = 'core.User'

    # Application definition

    INSTALLED_APPS = ('django.contrib.admin', 'django.contrib.auth',
                      'django.contrib.contenttypes', 'django.contrib.sessions',
                      'django.contrib.messages', 'django.contrib.staticfiles',
                      'pipeline', 'django_extensions', 'rest_framework',
                      'rest_framework.authtoken', 'api', 'core')

    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )

    ROOT_URLCONF = 'keepcalm.urls'

    WSGI_APPLICATION = 'keepcalm.wsgi.application'

    # Database
    # https://docs.djangoproject.com/en/1.6/ref/settings/#databases
    # http://django-configurations.readthedocs.org/en/latest/values/#configurations.values.DatabaseURLValue

    DATABASES = values.DatabaseURLValue('sqlite:///%s' %
                                        os.path.join(BASE_DIR, 'db.sqlite3'),
                                        environ=True)

    # Internationalization
    # https://docs.djangoproject.com/en/1.6/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    LANGUAGES = (
        ('es', _('Spanish')),
        ('en', _('English')),
    )

    LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'))

    #customizations to prevent automatic attack vector, due to public var names.
    DEFAULT_FROM_EMAIL = '*****@*****.**'

    LANGUAGE_COOKIE_NAME = '{}_language'.format(APP_NAME)

    SESSION_COOKIE_NAME = '{}_session'.format(APP_NAME)

    CSRF_COOKIE_NAME = '{}_token'.format(APP_NAME)

    SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

    # CACHES = {
    #     'default': {
    #         'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
    #         'KEY_PREFIX': '{}_'.format(APP_NAME),
    #         'LOCATION': '127.0.0.1:11211',
    #     }
    # }

    #notifications
    SERVER_EMAIL = '*****@*****.**'

    ADMINS = (
        ('Diego Navarro', '*****@*****.**'),
        ('Enrique Paredes', '*****@*****.**'),
    )

    MANAGERS = ADMINS

    KEEPCALM_PAYLOADS = [
        'core.payloads.dummy.LogPayload',
    ]
class ProjectDefault(Configuration):
    """
    The default settings from the Django project template.

    Django Configurations
    https://django-configurations.readthedocs.io
    """

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/{{docs_version}}/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = values.ListValue([])

    # Application definition

    INSTALLED_APPS = [
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "django.contrib.staticfiles",
    ]

    MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
    ]

    ROOT_URLCONF = "{{project_name}}.urls"

    TEMPLATES = [{
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ]
        },
    }]

    WSGI_APPLICATION = "{{project_name}}.wsgi.application"

    # Database
    # https://docs.djangoproject.com/en/{{docs_version}}/ref/settings/#databases

    DATABASES = values.DatabaseURLValue()

    # Password validation
    # https://docs.djangoproject.com/en/{{docs_version}}/ref/settings/#auth-password-validators  # noqa
    # fmt: off
    AUTH_PASSWORD_VALIDATORS = [
        {
            "NAME":
            "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",  # noqa
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.MinimumLengthValidator",
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.CommonPasswordValidator",
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.NumericPasswordValidator",
        },
    ]
    # fmt: on
    # Internationalization
    # https://docs.djangoproject.com/en/{{docs_version}}/topics/i18n/

    LANGUAGE_CODE = "en-us"

    TIME_ZONE = "UTC"

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/{{docs_version}}/howto/static-files/

    STATIC_URL = "/static/"

    STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, "static"))

    STATICFILES_STORAGE = (
        "django.contrib.staticfiles.storage.ManifestStaticFilesStorage")

    # Stored files
    # https://docs.djangoproject.com/en/{{docs_version}}/topics/files/

    # MEDIA_URL = "/media/"

    # MEDIA_ROOT = os.path.abspath(os.path.join(BASE_DIR, "media"))

    # Email Settings
    # https://docs.djangoproject.com/en/{{docs_version}}/topics/email/

    SERVER_EMAIL = values.EmailValue()

    DEFAULT_NAME = "{{project_name}}"

    DEFAULT_FROM_EMAIL = f"{DEFAULT_NAME} <{SERVER_EMAIL}>"

    EMAIL_SUBJECT_PREFIX = f"[{DEFAULT_NAME}] "

    ERROR_EMAIL = SERVER_EMAIL

    EMAIL_SIGNATURE = f"\n-- \n{DEFAULT_FROM_EMAIL}"

    MANAGERS = ((DEFAULT_NAME, ERROR_EMAIL), )

    ADMINS = MANAGERS

    EMAIL_USE_LOCALTIME = True
Example #20
0
class Production(Common):
    DEBUG = False

    # Honor the 'X-Forwarded-Proto' header for request.is_secure()
    # https://devcenter.heroku.com/articles/getting-started-with-django
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    INSTALLED_APPS = Common.INSTALLED_APPS
    SECRET_KEY = values.SecretValue()

    DATABASES = values.DatabaseURLValue()

    # django-secure
    # http://django-secure.readthedocs.org/en/v0.1.2/settings.html
    INSTALLED_APPS += ("djangosecure", )

    SECURE_HSTS_SECONDS = 60
    SECURE_HSTS_INCLUDE_SUBDOMAINS = values.BooleanValue(True)
    SECURE_FRAME_DENY = values.BooleanValue(True)
    SECURE_CONTENT_TYPE_NOSNIFF = values.BooleanValue(True)
    SECURE_BROWSER_XSS_FILTER = values.BooleanValue(True)
    SESSION_COOKIE_SECURE = values.BooleanValue(True)
    SESSION_COOKIE_HTTPONLY = values.BooleanValue(True)
    SECURE_SSL_REDIRECT = values.BooleanValue(True)
    CSRF_COOKIE_SECURE = values.BooleanValue(True)
    CSRF_COOKIE_DOMAIN = '*.stanford.edu'
    CSRF_TRUSTED_ORIGINS = ['scholar.stanford.edu', 'scholar.5harad.com']

    # Site
    # https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
    ALLOWED_HOSTS = ["*"]

    INSTALLED_APPS += ("gunicorn", )

    # Template
    # https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
    # TEMPLATE_LOADERS = (
    #     ('django.template.loaders.cached.Loader', (
    #         'django.template.loaders.filesystem.Loader',
    #         'django.template.loaders.app_directories.Loader',
    #     )),
    # )

    # Media files
    # http://django-storages.readthedocs.org/en/latest/index.html
    # INSTALLED_APPS += ('storages',)
    # DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
    # AWS_ACCESS_KEY_ID = values.Value('DJANGO_AWS_ACCESS_KEY_ID')
    # AWS_SECRET_ACCESS_KEY = values.Value('DJANGO_AWS_SECRET_ACCESS_KEY')
    # AWS_STORAGE_BUCKET_NAME = values.Value('DJANGO_AWS_STORAGE_BUCKET_NAME')
    # AWS_DEFAULT_ACL = values.Value('public-read')
    # AWS_AUTO_CREATE_BUCKET = True
    # AWS_QUERYSTRING_AUTH = False
    # MEDIA_URL = 'https://s3.amazonaws.com/{}/'.format(AWS_STORAGE_BUCKET_NAME)
    # AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat()

    # https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#cache-control
    # Response can be cached by browser and any intermediary caches (i.e. it is "public") for up to 1 day
    # 86400 = (60 seconds x 60 minutes x 24 hours)
    # AWS_HEADERS = {
    #     'Cache-Control': 'max-age=86400, s-maxage=86400, must-revalidate',
    # }

    # Static files
    # STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

    # Caching
    # redis_url = urlparse.urlparse(os.environ.get('REDISTOGO_URL', 'redis://localhost:6379'))
    # CACHES = {
    #     'default': {
    #         'BACKEND': 'redis_cache.RedisCache',
    #         'LOCATION': '{}:{}'.format(redis_url.hostname, redis_url.port),
    #         'OPTIONS': {
    #             'DB': 0,
    #             'PASSWORD': redis_url.password,
    #             'PARSER_CLASS': 'redis.connection.HiredisParser',
    #             'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool',
    #             'CONNECTION_POOL_CLASS_KWARGS': {
    #                 'max_connections': 50,
    #                 'timeout': 20,
    #             }
    #         }
    #     }
    # }

    # Django RQ production settings
    # RQ_QUEUES = {
    #     'default': {
    #         'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379'),
    #         'DB': 0,
    #         'DEFAULT_TIMEOUT': 500,
    #     },
    # }

    Common.VERSATILEIMAGEFIELD_SETTINGS['create_images_on_demand'] = False

    EMAIL_USE_TLS = True
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_HOST_USER = '******'
    EMAIL_HOST_PASSWORD = values.Value('DJANGO_EMAIL_HOST_PASSWORD')
    EMAIL_PORT = 587
    DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
    SERVER_EMAIL = EMAIL_HOST_USER
Example #21
0
class Common(Configuration):

    ########## APP CONFIGURATION
    DJANGO_APPS = (
        # Default Django apps:
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',

        # Useful template tags:
        # 'django.contrib.humanize',

        # Admin
        'django.contrib.admin',
    )
    THIRD_PARTY_APPS = (
        'south',  # Database migration helpers:
        'crispy_forms',  # Form layouts
        'avatar',  # for user avatars
    )

    # Apps specific for this project go here.
    LOCAL_APPS = (
        'users',  # custom users app
        # Your stuff: custom apps go here
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
    INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

    INSTALLED_APPS += (
        # Needs to come last for now because of a weird edge case between
        #   South and allauth
        'allauth',  # registration
        'allauth.account',  # registration
        'allauth.socialaccount',  # registration
    )
    ########## END APP CONFIGURATION

    ########## MIDDLEWARE CONFIGURATION
    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )
    ########## END MIDDLEWARE CONFIGURATION

    ########## DEBUG
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
    DEBUG = values.BooleanValue(True)

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
    TEMPLATE_DEBUG = DEBUG
    ########## END DEBUG

    ########## SECRET CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
    # Note: This key only used for development and testing.
    #       In production, this is changed to a values.SecretValue() setting
    SECRET_KEY = "CHANGEME!!!"
    ########## END SECRET CONFIGURATION

    ########## FIXTURE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
    FIXTURE_DIRS = (
        join(BASE_DIR, 'fixtures'),
    )
    ########## END FIXTURE CONFIGURATION

    ########## EMAIL CONFIGURATION
    EMAIL_BACKEND = values.Value('django.core.mail.backends.smtp.EmailBackend')
    ########## END EMAIL CONFIGURATION

    ########## MANAGER CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
    ADMINS = (
        ('{{cookiecutter.author_name}}', '{{cookiecutter.email}}'),
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
    MANAGERS = ADMINS
    ########## END MANAGER CONFIGURATION

    ########## DATABASE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
    DATABASES = values.DatabaseURLValue('mysql://root:@127.0.0.1/{{cookiecutter.repo_name}}', engine='django_mysqlpool.backends.mysqlpool')
    # DATABASES['default']['ENGINE'] = 'django_mysqlpool.backends.mysqlpool'

    SOUTH_DATABASE_ADAPTERS = {
        'default': "south.db.mysql"
    }
    ########## END DATABASE CONFIGURATION

    ########## CACHING
    # Do this here because thanks to django-pylibmc-sasl and pylibmc memcacheify is painful to install on windows.
    # memcacheify is what's used in Production
    CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': ''
        }
    }
    ########## END CACHING

    ########## GENERAL CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
    TIME_ZONE = 'America/Los_Angeles'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
    LANGUAGE_CODE = 'en-us'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
    SITE_ID = 1

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
    USE_I18N = True

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
    USE_L10N = True

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
    USE_TZ = True
    ########## END GENERAL CONFIGURATION

    ########## TEMPLATE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
    TEMPLATE_CONTEXT_PROCESSORS = (
        'django.contrib.auth.context_processors.auth',
        "allauth.account.context_processors.account",
        "allauth.socialaccount.context_processors.socialaccount",
        'django.core.context_processors.debug',
        'django.core.context_processors.i18n',
        'django.core.context_processors.media',
        'django.core.context_processors.static',
        'django.core.context_processors.tz',
        'django.contrib.messages.context_processors.messages',
        'django.core.context_processors.request',
        # Your stuff: custom template context processers go here
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
    TEMPLATE_DIRS = (
        join(BASE_DIR, 'templates'),
    )

    TEMPLATE_LOADERS = (
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        )

    # See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs
    CRISPY_TEMPLATE_PACK = 'bootstrap3'
    ########## END TEMPLATE CONFIGURATION

    ########## STATIC FILE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
    STATIC_ROOT = join(os.path.dirname(BASE_DIR), 'staticfiles')

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
    STATIC_URL = '/static/'

    # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
    STATICFILES_DIRS = (
        join(BASE_DIR, 'static'),
    )

    # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )
    ########## END STATIC FILE CONFIGURATION

    ########## MEDIA CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
    MEDIA_ROOT = join(BASE_DIR, 'media')

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
    MEDIA_URL = '/media/'
    ########## END MEDIA CONFIGURATION

    ########## URL Configuration
    ROOT_URLCONF = 'config.urls'

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
    WSGI_APPLICATION = 'config.wsgi.application'
    ########## End URL Configuration

    ########## AUTHENTICATION CONFIGURATION
    AUTHENTICATION_BACKENDS = (
        "django.contrib.auth.backends.ModelBackend",
        "allauth.account.auth_backends.AuthenticationBackend",
    )

    # Some really nice defaults
    ACCOUNT_AUTHENTICATION_METHOD = "username"
    ACCOUNT_EMAIL_REQUIRED = True
    ACCOUNT_EMAIL_VERIFICATION = "mandatory"
    ########## END AUTHENTICATION CONFIGURATION

    ########## Custom user app defaults
    # Select the correct user model
    AUTH_USER_MODEL = "users.User"
    LOGIN_REDIRECT_URL = "users:redirect"
    ########## END Custom user app defaults

    ########## SLUGLIFIER
    AUTOSLUG_SLUGIFY_FUNCTION = "slugify.slugify"
    ########## END SLUGLIFIER

    ########## LOGGING CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
    # A sample logging configuration. The only tangible logging
    # performed by this configuration is to send an email to
    # the site admins on every HTTP 500 error when DEBUG=False.
    # See http://docs.djangoproject.com/en/dev/topics/logging for
    # more details on how to customize your logging configuration.
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse'
            }
        },
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'filters': ['require_debug_false'],
                'class': 'django.utils.log.AdminEmailHandler'
            }
        },
        'loggers': {
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
        }
    }
Example #22
0
class Test(BaseSettings):
    MEDIA_ROOT = tempfile.mkdtemp()
    SECRET_KEY = 'test'
    DATABASES = values.DatabaseURLValue(
        'postgresql://*****:*****@localhost:15432/dev')
Example #23
0
class Common(Configuration):

    VERSION = values.Value('0.0.0-x', environ_prefix='ID')
    SITE_NAME = values.Value('Investigative Dashboard', environ_prefix='ID')

    INSTALLED_APPS = (
        'django.contrib.contenttypes',
        'django.contrib.auth',

        # Third party apps
        'rest_framework',
        'corsheaders',
        'django_filters',
        'social_django',
        'activity',

        # Your apps
        'api_v3',
    )

    MIDDLEWARE = (
        'django.middleware.security.SecurityMiddleware',
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
    )

    ALLOWED_HOSTS = ["*"]
    ROOT_URLCONF = 'api_v3.urls'
    SECRET_KEY = values.SecretValue()
    WSGI_APPLICATION = 'api_v3.wsgi.application'
    USE_X_FORWARDED_HOST = True
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    ROUTER_CLASS = 'rest_framework.routers.DefaultRouter'

    # Email
    EMAIL = values.EmailURLValue('console://')
    DEFAULT_FROM_EMAIL = values.EmailValue('',
                                           environ_prefix='ID',
                                           environ_required=True)
    DEFAULT_FROM = '{} <{}>'.format(SITE_NAME, DEFAULT_FROM_EMAIL)

    ADMINS = []

    # Postgres
    DATABASES = values.DatabaseURLValue(
        'postgres://postgres:@postgres:5432/postgres')

    # CORS
    CORS_ALLOW_CREDENTIALS = True
    CORS_ORIGIN_WHITELIST = values.ListValue(['localhost:8000'])
    CORS_ORIGIN_ALLOW_ALL = values.BooleanValue(False)

    # Sentry
    RAVEN_CONFIG = {
        'dsn': values.Value('', environ_name='SENTRY_DSN', environ_prefix=''),
        'release': VERSION,
    }

    # General
    APPEND_SLASH = False
    TIME_ZONE = 'UTC'
    LANGUAGE_CODE = 'en-us'
    # If you set this to False, Django will make some optimizations so as not
    # to load the internationalization machinery.
    USE_I18N = False
    USE_L10N = False
    USE_TZ = False

    # Media files: max. size of 500MB
    MEDIA_ROOT = values.Value(environ_name='MEDIA_ROOT',
                              environ_prefix='',
                              environ_required=True)
    MAX_UPLOAD_SIZE = 1024 * 1024 * 500
    STATIC_URL = '/api/static/'

    DEBUG = values.BooleanValue(False)

    TEMPLATES = [
        {
            'BACKEND':
            'django.template.backends.django.DjangoTemplates',
            'APP_DIRS':
            True,
            'DIRS': [
                os.path.abspath(
                    os.path.join(os.path.dirname(__file__), '..',
                                 'templates')),
            ],
        },
    ]

    # Logging
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'require_debug_true': {
                '()': 'django.utils.log.RequireDebugTrue',
            },
        },
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
            },
        },
        'loggers': {
            '': {
                'handlers': ['console'],
                'level': 'DEBUG',
                'propagate': True,
            },
        }
    }

    # Custom user app
    AUTH_USER_MODEL = 'api_v3.Profile'

    # Authentication
    AUTHENTICATION_BACKENDS = values.ListValue([
        'api_v3.misc.oauth2.KeycloakOAuth2',
    ])
    SOCIAL_AUTH_KEYCLOAK_BASE = values.Value('', environ_prefix='')
    SOCIAL_AUTH_KEYCLOAK_KEY = values.Value('', environ_prefix='')
    SOCIAL_AUTH_KEYCLOAK_SECRET = values.Value('', environ_prefix='')

    SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = values.Value('', environ_prefix='')
    SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = values.Value('', environ_prefix='')

    # Username is not used.
    SOCIAL_AUTH_USER_FIELDS = ['email']

    # See: http://python-social-auth.readthedocs.io/en/latest/pipeline.html
    SOCIAL_AUTH_PIPELINE = (
        'social_core.pipeline.social_auth.social_details',
        'social_core.pipeline.social_auth.social_uid',
        'social_core.pipeline.social_auth.social_user',
        'social_core.pipeline.social_auth.associate_by_email',
        'social_core.pipeline.user.create_user',
        'social_core.pipeline.social_auth.associate_user',
        'social_core.pipeline.user.user_details',
        'api_v3.misc.oauth2.activate_user',
        'api_v3.misc.oauth2.map_email_to_subscriber',
    )

    # Django Rest Framework
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ],
        'DEFAULT_AUTHENTICATION_CLASSES':
        ('rest_framework.authentication.SessionAuthentication', )
    }

    # JSON API DRF
    JSON_API_FORMAT_KEYS = 'dasherize'
    JSON_API_FORMAT_TYPES = 'dasherize'
    JSON_API_PLURALIZE_TYPES = True
Example #24
0
class Common(Configuration):
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = values.BooleanValue(False)

    ALLOWED_HOSTS = []

    # Application definition
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.humanize',
        'django.contrib.sites',
        'whitenoise.runserver_nostatic',
        'django.contrib.staticfiles',
        'compressor',
        'bootstrap4',
        'django_extensions',
        'podcastarchive.users',
        'podcasts',
        'background_task',
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.middleware.locale.LocaleMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'podcastarchive.users.middleware.LoginRequiredMiddleware',
    ]

    ROOT_URLCONF = 'podcastarchive.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                os.path.join(BASE_DIR, 'templates'),
            ],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'podcastarchive.wsgi.application'

    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
    DATABASES = values.DatabaseURLValue('sqlite:///{}'.format(
        os.path.join(BASE_DIR, 'db.sqlite3')))

    # Password validation
    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME':
            'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]

    LOGIN_EXEMPT_URLS = ['admin/']

    SITE_ID = 1

    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/
    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'Europe/Berlin'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    LANGUAGES = [
        ('de', _('German')),
        ('en', _('English')),
    ]

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

    STATICFILES_FINDERS = [
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
        'compressor.finders.CompressorFinder',
    ]

    COMPRESS_ROOT = os.path.join(BASE_DIR, 'assets')
    COMPRESS_PRECOMPILERS = (('text/x-scss', 'django_libsass.SassCompiler'), )

    COMPRESS_CACHEABLE_PRECOMPILERS = COMPRESS_PRECOMPILERS
    LIBSASS_PRECISION = 8

    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')

    AUTH_USER_MODEL = 'users.User'

    DEBUG_TOOLBAR_CONFIG = {
        'JQUERY_URL': '',
    }

    # Project settings
    COVER_IMAGE_SIZE = (500, 500)
Example #25
0
class Common(Configuration):
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = values.BooleanValue(False)

    ALLOWED_HOSTS = values.ListValue([])

    # Application definition
    INSTALLED_APPS = [
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "whitenoise.runserver_nostatic",
        "django.contrib.staticfiles",
        "django_extensions",
        "debug_toolbar",
        "ckeditor",
        "reversion",
        "django_select2",
        "suministrospr.users",
        "suministrospr.suministros",
        "suministrospr.utils",
    ]

    MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "whitenoise.middleware.WhiteNoiseMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
        "debug_toolbar.middleware.DebugToolbarMiddleware",
    ]

    ROOT_URLCONF = "suministrospr.urls"

    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "DIRS": [
                os.path.join(BASE_DIR, "templates"),
            ],
            "APP_DIRS": True,
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.debug",
                    "django.template.context_processors.request",
                    "django.contrib.auth.context_processors.auth",
                    "django.contrib.messages.context_processors.messages",
                ],
            },
        },
    ]

    WSGI_APPLICATION = "suministrospr.wsgi.application"

    # Database
    # https://docs.djangoproject.com/en/3.0/ref/settings/#databases
    DATABASES = values.DatabaseURLValue("sqlite:///{}".format(
        os.path.join(BASE_DIR, "db.sqlite3")))

    # Password validation
    # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
    AUTH_PASSWORD_VALIDATORS = [
        {
            "NAME":
            "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.MinimumLengthValidator",
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.CommonPasswordValidator",
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.NumericPasswordValidator",
        },
    ]

    # Internationalization
    # https://docs.djangoproject.com/en/3.0/topics/i18n/
    LANGUAGE_CODE = "en-us"

    TIME_ZONE = "UTC"

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/3.0/howto/static-files/
    STATIC_URL = "/static/"
    STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
    STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), )
    STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

    AUTH_USER_MODEL = "users.User"

    DEBUG_TOOLBAR_CONFIG = {
        "SHOW_TOOLBAR_CALLBACK":
        "suministrospr.utils.debug_toolbar.show_toolbar"
    }

    CKEDITOR_CONFIGS = {
        "default": {
            "removeDialogTabs":
            "link:advanced;link:target",
            "removePlugins":
            "elementspath,magicline",
            "width":
            "auto",
            "toolbar":
            "Custom",
            "toolbar_Custom": [
                [
                    "Bold",
                    "Italic",
                    "Underline",
                    "Strike",
                    "-",
                    "RemoveFormat",
                ],
                ["NumberedList", "BulletedList", "Outdent", "Indent", "-"],
                ["Link", "Unlink", "-", "HorizontalRule"],
            ],
        },
    }

    REDIS_URL = values.Value(environ_prefix=None)

    SENTRY_DSN = values.Value(None, environ_prefix=None)

    CACHE_MIXIN_TIMEOUT = values.IntegerValue(300, environ_prefix=None)

    SELECT2_CACHE_BACKEND = "default"

    @property
    def CACHES(self):
        if not self.REDIS_URL:
            return {
                "default": {
                    "BACKEND": "django.core.cache.backends.locmem.LocMemCache"
                }
            }

        return {
            "default": {
                "BACKEND": "django_redis.cache.RedisCache",
                "LOCATION": f"{self.REDIS_URL}/1]0",
                "OPTIONS": {
                    "CLIENT_CLASS": "django_redis.client.DefaultClient"
                },
            }
        }

    @classmethod
    def post_setup(cls):
        super().post_setup()

        if cls.SENTRY_DSN:
            sentry_sdk.init(dsn=cls.SENTRY_DSN,
                            integrations=[DjangoIntegration()])
Example #26
0
class ProjectConfiguration(Configuration):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    # dynamic params
    DEBUG = values.BooleanValue(default=True, environ_prefix=SETTINGS_PREFIX)
    SECRET_KEY = values.Value(default="12456", environ_prefix=SETTINGS_PREFIX)
    # database
    DATABASES = values.DatabaseURLValue(
        default="postgres://*****:*****@127.0.0.1/ubex_authapi",
        environ_name="DATABASE_URL",
    )

    # static params
    ALLOWED_HOSTS = ["*"]  # no production
    INSTALLED_APPS = [
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "django.contrib.staticfiles",
        # libs
        "rest_framework",
        "django_filters",
        "drf_yasg",
        # applications
        "api",
    ]

    MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
    ]

    ROOT_URLCONF = "project.urls"
    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "DIRS": [],
            "APP_DIRS": True,
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.debug",
                    "django.template.context_processors.request",
                    "django.contrib.auth.context_processors.auth",
                    "django.contrib.messages.context_processors.messages",
                ],
            },
        },
    ]

    WSGI_APPLICATION = "project.wsgi.application"

    AUTH_PASSWORD_VALIDATORS = [
        {
            "NAME": (
                "django.contrib."
                "auth.password_validation.UserAttributeSimilarityValidator"
            ),
        },
        {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
        {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
        {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
    ]

    LANGUAGE_CODE = "en-us"
    TIME_ZONE = "UTC"
    USE_I18N = True
    USE_L10N = True
    USE_TZ = True

    REST_FRAMEWORK = {
        "DEFAULT_FILTER_BACKENDS": (
            "django_filters.rest_framework.DjangoFilterBackend",
        ),
    }

    STATIC_ROOT = "static"
    STATIC_URL = "/static/"
class Common(Configuration):

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # SECURITY WARNING: do not run with debug turned on in production!
    DEBUG = values.BooleanValue(False)

    ALLOWED_HOSTS = ["localhost", "127.0.0.1", "0.0.0.0", "zap"]

    # Application definition
    INSTALLED_APPS = [
        "django.contrib.sites",
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "whitenoise.runserver_nostatic",
        "django.contrib.staticfiles",
        "rest_framework",
        "rest_framework_swagger",
        "rest_framework.authtoken",
        "rest_registration",
        "rest_framework_jwt",
        "django_extensions",
        "django_celery_results",
        "cacheops",
        "debug_toolbar",
        "drf_network_pipeline.users",
        "drf_network_pipeline.pipeline",
    ]

    MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "whitenoise.middleware.WhiteNoiseMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
    ]

    ROOT_URLCONF = "drf_network_pipeline.urls"

    TEMPLATE_LOADERS = (
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )
    TEMPLATES = [
        {
            "BACKEND":
            "django.template.backends.django.DjangoTemplates",
            "DIRS": [
                "drf_network_pipeline/templates",
                "drf_network_pipeline/docs/build/html",
                "drf_network_pipeline/docs/build/html/modules"
            ],
            "APP_DIRS":
            True,
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.debug",
                    "django.template.context_processors.request",
                    "django.contrib.auth.context_processors.auth",
                    "django.contrib.messages.context_processors.messages",
                ],
            },
        },
    ]

    WSGI_APPLICATION = "drf_network_pipeline.wsgi.application"

    # Database
    # https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#databases  # noqa E501
    DATABASES = values.DatabaseURLValue("sqlite:///{}".format(
        os.path.join(BASE_DIR, "db.sqlite3")))

    if os.environ.get("POSTGRES_DB", "") != "":
        DATABASES = {
            "default": {
                "ENGINE": "django.db.backends.postgresql_psycopg2",
                "NAME": os.environ.get("POSTGRES_DB", "webapp"),
                "USER": os.environ.get("POSTGRES_USER", "postgres"),
                "PASSWORD": os.environ.get("POSTGRES_PASSWORD", "postgres"),
                "HOST": os.environ.get("POSTGRES_HOST", "localhost"),
                "PORT": os.environ.get("POSTGRES_PORT", "5432"),
            },
        }
        # end of loading postgres
    # end of using the postgres db

    # Password validation
    # https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#auth-password-validators # noqa
    AUTH_PASSWORD_VALIDATORS = [
        {
            "NAME":
            "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",  # noqa
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.MinimumLengthValidator",  # noqa
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.CommonPasswordValidator",  # noqa
        },
        {
            "NAME":
            "django.contrib.auth.password_validation.NumericPasswordValidator",  # noqa
        },
    ]

    SITE_ID = 1

    # Internationalization
    # https://docs.djangoproject.com/en/{{ docs_version }}/topics/i18n/
    LANGUAGE_CODE = "en-us"

    TIME_ZONE = "UTC"

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/{{ docs_version }}/howto/static-files/
    STATIC_URL = "/static/"
    STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
    STATICFILES_STORAGE = \
        "whitenoise.storage.CompressedManifestStaticFilesStorage"
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "drf_network_pipeline/docs/build/html/_static")
    ]
    MEDIA_URL = "/media/"
    MEDIA_ROOT = "{}/media".format(BASE_DIR)

    AUTH_USER_MODEL = "users.User"

    # https://github.com/szopu/django-rest-registration#configuration
    REST_REGISTRATION = {
        "REGISTER_VERIFICATION_ENABLED": False,
        "RESET_PASSWORD_VERIFICATION_URL": "/reset-password/",
        "REGISTER_EMAIL_VERIFICATION_ENABLED": False,
        "VERIFICATION_FROM_EMAIL": "*****@*****.**",
    }

    # http://getblimp.github.io/django-rest-framework-jwt/
    REST_FRAMEWORK = {
        "DEFAULT_PERMISSION_CLASSES": (
            "rest_framework.permissions.AllowAny",
            "rest_framework.permissions.IsAuthenticated",
        ),
        "DEFAULT_AUTHENTICATION_CLASSES": (
            "rest_framework_jwt.authentication.JSONWebTokenAuthentication",
            "rest_framework.authentication.TokenAuthentication",
            "rest_framework.authentication.BasicAuthentication",
            "rest_framework.authentication.SessionAuthentication",
        ),
        "DEFAULT_RENDERER_CLASSES": (
            "rest_framework.renderers.JSONRenderer",
            "rest_framework.renderers.BrowsableAPIRenderer",
        ),
    }

    # http://getblimp.github.io/django-rest-framework-jwt/
    """

    One of these is breaking the api-token-auth - 2018-02-02

    JWT_AUTH = {
        "JWT_ENCODE_HANDLER":
        "rest_framework_jwt.utils.jwt_encode_handler",
        "JWT_DECODE_HANDLER":
        "rest_framework_jwt.utils.jwt_decode_handler",
        "JWT_PAYLOAD_HANDLER":
        "rest_framework_jwt.utils.jwt_payload_handler",
        "JWT_PAYLOAD_GET_USER_ID_HANDLER":
        "rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler",
        "JWT_RESPONSE_PAYLOAD_HANDLER":
        "rest_framework_jwt.utils.jwt_response_payload_handler",
        "JWT_SECRET_KEY": SECRET_KEY,
        "JWT_GET_USER_SECRET_KEY": None,
        "JWT_PUBLIC_KEY": None,
        "JWT_PRIVATE_KEY": None,
        "JWT_ALGORITHM": "HS256",
        "JWT_VERIFY": True,
        "JWT_VERIFY_EXPIRATION": True,
        "JWT_LEEWAY": 0,
        "JWT_EXPIRATION_DELTA": datetime.timedelta(seconds=300),
        "JWT_AUDIENCE": None,
        "JWT_ISSUER": None,
        "JWT_ALLOW_REFRESH": False,
        "JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=7),
        "JWT_AUTH_HEADER_PREFIX": "JWT",
        "JWT_AUTH_COOKIE": None,
    }
    """

    INCLUDE_ML_MODEL = True
    INCLUDE_ML_WEIGHTS = True
    MAX_RECS_ML_PREPARE = 20
    MAX_RECS_ML_JOB = 20
    MAX_RECS_ML_JOB_RESULT = 20

    # for saving images to the host
    # on vbox
    if os.path.exists("/media/sf_shared"):
        IMAGE_SAVE_DIR = "/media/sf_shared"
    else:
        IMAGE_SAVE_DIR = os.getenv("IMAGE_SAVE_DIR", "/tmp")
    # end of image save path

    REDIS_HOST = os.environ.get("REDIS_HOST", "localhost")
    REDIS_PORT = int(os.environ.get("REDIS_PORT", "6379"))
    REDIS_BROKER_DB = int(os.environ.get("REDIS_BROKER_DB", "9"))
    REDIS_RESULT_DB = int(os.environ.get("REDIS_RESULT_DB", "10"))
    REDIS_PASSWORD = os.environ.get("REDIS_PASSWORD", "")
    if REDIS_PASSWORD == "":
        REDIS_PASSWORD = None

    # Sensible settings for celery
    CELERY_ENABLED = bool(os.environ.get("CELERY_ENABLED", "0") == "1")
    CELERY_ALWAYS_EAGER = False
    CELERY_ACKS_LATE = True
    CELERY_TASK_PUBLISH_RETRY = True
    CELERY_DISABLE_RATE_LIMITS = False

    # timeout for getting task results
    CELERY_GET_RESULT_TIMEOUT = 1.0

    # If you want to see results and try out tasks interactively,
    # change it to False
    # Or change this setting on tasks level
    # CELERY_IGNORE_RESULT = True
    CELERY_SEND_TASK_ERROR_EMAILS = False
    # CELERY_TASK_RESULT_EXPIRES = 600

    # Set redis as celery result backend
    CELERY_BROKER_URL = os.getenv("BROKER_URL", ("redis://{}:{}/{}").format(
        REDIS_HOST, REDIS_PORT, REDIS_BROKER_DB))
    CELERY_RESULT_BACKEND = os.getenv("BACKEND_URL",
                                      ("redis://{}:{}/{}").format(
                                          REDIS_HOST, REDIS_PORT,
                                          REDIS_RESULT_DB))

    # CELERY_REDIS_MAX_CONNECTIONS = 1

    # Do not use pickle as serializer, json is much safer
    CELERY_TASK_SERIALIZER = "json"
    CELERY_ACCEPT_CONTENT = ["application/json"]

    CELERYD_HIJACK_ROOT_LOGGER = False
    CELERYD_PREFETCH_MULTIPLIER = 1
    CELERYD_MAX_TASKS_PER_CHILD = 1000

    # Django Cacheops
    # https://github.com/Suor/django-cacheops
    # https://github.com/Suor/django-cacheops/blob/master/LICENSE
    CACHEOPS_ENABLED = bool(os.environ.get("CACHEOPS_ENABLED", "0") == "1")
    if CACHEOPS_ENABLED:
        CACHEOPS_REDIS = {
            "host": os.getenv("REDIS_CACHE_HOST", REDIS_HOST),
            "port": int(os.getenv("REDIS_CACHE_PORT", REDIS_PORT)),
            "db": int(os.getenv("REDIS_CACHE_DB", "8")),
            "socket_timeout": int(os.getenv("REDIS_CACHE_TIMEOUT", "3"))
        }
        CACHEOPS_DEFAULTS = {"timeout": 60 * 60}
        CACHEOPS = {
            "auth.user": {
                "ops": "get",
                "timeout": 60 * 15
            },
            "auth.*": {
                "ops": ("fetch", "get")
            },
            "auth.permission": {
                "ops": "all"
            },
            "*.*": {},
        }
    # end of if CACHEOPS_ENABLED

    # AntiNex Worker settings - Optional
    ANTINEX_API_NAME = os.getenv("ANTINEX_API_SOURCE_NAME", "drf")
    ANTINEX_WORKER_ENABLED = bool(
        os.getenv("ANTINEX_WORKER_ENABLED", "0") == "1")

    # bypass the django train + predict and only use the worker
    # note - no predictions will be stored in the database
    ANTINEX_WORKER_ONLY = bool(os.getenv("ANTINEX_WORKER_ONLY", "0") == "1")

    ANTINEX_AUTH_URL = os.getenv("ANTINEX_AUTH_URL",
                                 "redis://localhost:6379/6")
    ANTINEX_RESULT_AUTH_URL = os.getenv("ANTINEX_RESULT_AUTH_URL",
                                        "redis://localhost:6379/9")

    # AntiNex routing
    ANTINEX_EXCHANGE_NAME = os.getenv("ANTINEX_EXCHANGE_NAME",
                                      "webapp.predict.requests")
    ANTINEX_EXCHANGE_TYPE = os.getenv("ANTINEX_EXCHANGE_TYPE", "topic")
    ANTINEX_ROUTING_KEY = os.getenv("ANTINEX_ROUTING_KEY",
                                    "webapp.predict.requests")
    ANTINEX_QUEUE_NAME = os.getenv("ANTINEX_QUEUE_NAME",
                                   "webapp.predict.requests")
    ANTINEX_RESULT_EXCHANGE_NAME = os.getenv(
        "ANTINEX_RESULT_EXCHANGE_NAME",
        "drf_network_pipeline.pipeline.tasks.task_ml_process_results")
    ANTINEX_RESULT_EXCHANGE_TYPE = os.getenv("ANTINEX_RESULT_EXCHANGE_TYPE",
                                             "topic")
    ANTINEX_RESULT_ROUTING_KEY = os.getenv(
        "ANTINEX_RESULT_ROUTING_KEY",
        "drf_network_pipeline.pipeline.tasks.task_ml_process_results")
    ANTINEX_RESULT_QUEUE_NAME = os.getenv(
        "ANTINEX_RESULT_QUEUE_NAME",
        "drf_network_pipeline.pipeline.tasks.task_ml_process_results")
    ANTINEX_RESULT_TASK_NAME = os.getenv(
        "ANTINEX_RESULT_TASK_NAME",
        "drf_network_pipeline.pipeline.tasks.task_ml_process_results")

    # By default persist messages to disk
    ANTINEX_PERSISTENT_MESSAGES = 2
    ANTINEX_NON_PERSISTENT_MESSAGES = 1
    ANTINEX_DELIVERY_MODE = ANTINEX_PERSISTENT_MESSAGES
    ANTINEX_RESULT_DELIVERY_MODE = ANTINEX_PERSISTENT_MESSAGES
    antinex_default_delivery_method = os.getenv("ANTINEX_DELIVERY_MODE",
                                                "persistent").lower()
    if antinex_default_delivery_method != "persistent":
        ANTINEX_DELIVERY_MODE = ANTINEX_NON_PERSISTENT_MESSAGES
        ANTINEX_RESULT_DELIVERY_MODE = ANTINEX_NON_PERSISTENT_MESSAGES

    # AntiNex SSL Configuration - Not Required for Redis
    ANTINEX_WORKER_SSL_ENABLED = bool(
        os.getenv("ANTINEX_WORKER_SSL_ENABLED", "0") == "1")

    antinex_default_ca_certs = "/etc/pki/ca-trust/source/anchors/antinex.ca"
    antinex_default_keyfile = "/etc/pki/tls/private/antinex.io.crt"
    antinex_default_certfile = "/etc/pki/tls/certs/antinex.io.pem"

    ANTINEX_CA_CERTS = os.getenv("ANTINEX_CA_CERTS", None)
    ANTINEX_KEYFILE = os.getenv("ANTINEX_KEYFILE", None)
    ANTINEX_CERTFILE = os.getenv("ANTINEX_CERTFILE", None)
    ANTINEX_TLS_PROTOCOL = ssl.PROTOCOL_TLSv1_2
    ANTINEX_CERT_REQS = ssl.CERT_REQUIRED

    antinex_tls_protocol_str = os.getenv("ANTINEX_TLS_PROTOCOL", "tls1.2")
    if antinex_tls_protocol_str == "tls1":
        ANTINEX_TLS_PROTOCOL = ssl.PROTOCOL_TLSv1
    elif antinex_tls_protocol_str == "tls1.1":
        ANTINEX_TLS_PROTOCOL = ssl.PROTOCOL_TLSv1_1

    antinex_cert_reqs_str = os.getenv("ANTINEX_CERT_REQS",
                                      "CERT_REQUIRED").lower()
    if antinex_cert_reqs_str == "cert_none":
        ANTINEX_CERT_REQS = ssl.CERT_NONE
    elif antinex_cert_reqs_str == "cert_optional":
        ANTINEX_CERT_REQS = ssl.CERT_OPTIONAL

    ANTINEX_SSL_OPTIONS = {}
    ANTINEX_RESULT_SSL_OPTIONS = {}
    if ANTINEX_WORKER_SSL_ENABLED:
        ANTINEX_SSL_OPTIONS = {
            "ssl_version": ANTINEX_TLS_PROTOCOL,
            "cert_reqs": ANTINEX_CERT_REQS
        }
        if ANTINEX_CA_CERTS:
            ANTINEX_SSL_OPTIONS["ca_certs"] = ANTINEX_CA_CERTS
        if ANTINEX_KEYFILE:
            ANTINEX_SSL_OPTIONS["keyfile"] = ANTINEX_KEYFILE
        if ANTINEX_CERTFILE:
            ANTINEX_SSL_OPTIONS["certfile"] = ANTINEX_CERTFILE
    # end of setting if ssl is enabled

    ANTINEX_RESULT_SSL_OPTIONS = ANTINEX_SSL_OPTIONS

    # end of AntiNex Worker settings

    # Add custom routing here
    CELERY_CREATE_MISSING_QUEUES = True
    CELERY_QUEUES = (Queue("default",
                           Exchange("default"),
                           routing_key="default"),
                     Queue(("drf_network_pipeline.users.tasks."
                            "task_get_user"),
                           Exchange("drf_network_pipeline.users.tasks."
                                    "task_get_user"),
                           routing_key=("drf_network_pipeline.users.tasks."
                                        "task_get_user")),
                     Queue(("drf_network_pipeline.pipeline.tasks."
                            "task_ml_prepare"),
                           Exchange("drf_network_pipeline.pipeline.tasks."
                                    "task_ml_prepare"),
                           routing_key=("drf_network_pipeline.pipeline.tasks."
                                        "task_ml_prepare")),
                     Queue(("drf_network_pipeline.pipeline.tasks."
                            "task_ml_job"),
                           Exchange("drf_network_pipeline.pipeline.tasks."
                                    "task_ml_job"),
                           routing_key=("drf_network_pipeline.pipeline.tasks."
                                        "task_ml_job")),
                     Queue(("drf_network_pipeline.pipeline.tasks."
                            "task_ml_process_results"),
                           Exchange("drf_network_pipeline.pipeline.tasks."
                                    "task_ml_process_results"),
                           routing_key=("drf_network_pipeline.pipeline.tasks."
                                        "task_ml_process_results")),
                     Queue(("drf_network_pipeline.pipeline.tasks."
                            "task_publish_to_core"),
                           Exchange("drf_network_pipeline.pipeline.tasks."
                                    "task_publish_to_core"),
                           routing_key=("drf_network_pipeline.pipeline.tasks."
                                        "task_publish_to_core")))

    CELERY_ROUTES = {
        ("drf_network_pipeline.users.tasks."
         "task_get_user"): {
            "queue": ("drf_network_pipeline.users.tasks."
                      "task_get_user")
        },
        ("drf_network_pipeline.pipeline.tasks."
         "task_ml_prepare"): {
            "queue": ("drf_network_pipeline.pipeline.tasks."
                      "task_ml_prepare")
        },
        ("drf_network_pipeline.pipeline.tasks."
         "task_ml_job"): {
            "queue": ("drf_network_pipeline.pipeline.tasks."
                      "task_ml_job")
        },
        ("drf_network_pipeline.pipeline.tasks."
         "task_publish_to_core"): {
            "queue": ("drf_network_pipeline.pipeline.tasks."
                      "task_publish_to_core")
        },
        ("drf_network_pipeline.pipeline.tasks."
         "task_ml_process_results"): {
            "queue": ("drf_network_pipeline.pipeline.tasks."
                      "task_ml_process_results")
        }
    }

    TEMPLATE_DIRS = ["drf_network_pipeline/templates"]
    INCLUDE_DOCS = bool(os.getenv("INCLUDE_DOCS", "1") == "1")
    if INCLUDE_DOCS:
        DOCS_ROOT = os.path.join(
            BASE_DIR,
            "{}/drf_network_pipeline/docs/build/html".format(BASE_DIR))
        DOCS_ACCESS = "public"
        DOC_START_DIR = "drf_network_pipeline/docs/build/html"
        TEMPLATE_DIRS.append(DOC_START_DIR)
        # noqa https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory
        ADD_THESE_DOC_DIRS = []
        for d in os.walk(DOC_START_DIR):
            if "static" not in d[0]:
                ADD_THESE_DOC_DIRS.append(d[0])

        DEFAULT_DOC_INDEX_HTML = "{}/{}".format(
            BASE_DIR, "drf_network_pipeline/docs/build/html/index.html")

        TEMPLATE_DIRS = TEMPLATE_DIRS + ADD_THESE_DOC_DIRS
        if not os.path.exists(DEFAULT_DOC_INDEX_HTML):
            print(("Failed to find sphinx index "
                   "BASE_DIR={} full_path={} docs "
                   "failed to load").format(BASE_DIR, DEFAULT_DOC_INDEX_HTML))
Example #28
0
class Base(Core):
    """Settings that may change per-environment, some with defaults."""
    @classmethod
    def setup(cls):
        super(Base, cls).setup()

        # For the sake of convenience we want to make UPLOAD_TRY_SYMBOLS_URL
        # optional as an environment variable. If it's not set, set it
        # by taking the UPLOAD_DEFAULT_URL and adding the prefix "/try"
        # right after the bucket name.
        if not cls.UPLOAD_TRY_SYMBOLS_URL:
            default_url = urlparse(cls.UPLOAD_DEFAULT_URL)
            path = default_url.path.split("/")
            # Since it always start with '/', the point after the bucket
            # name is the 3rd one.
            path.insert(2, "try")
            # Note `._replace` is actually not a private method.
            try_url = default_url._replace(path="/".join(path))
            cls.UPLOAD_TRY_SYMBOLS_URL = try_url.geturl()

    SECRET_KEY = values.SecretValue()

    DEBUG = values.BooleanValue(default=False)
    DEBUG_PROPAGATE_EXCEPTIONS = values.BooleanValue(default=False)

    ALLOWED_HOSTS = values.ListValue([])

    DATABASES = values.DatabaseURLValue("postgres://postgres@db/postgres")
    CONN_MAX_AGE = values.IntegerValue(60)

    REDIS_URL = values.Value("redis://redis-cache:6379/0")
    REDIS_STORE_URL = values.Value("redis://redis-store:6379/0")

    # Use redis as the Celery broker.
    @property
    def CELERY_BROKER_URL(self):
        return self.REDIS_URL

    @property
    def CACHES(self):
        return {
            "default": {
                "BACKEND": "django_redis.cache.RedisCache",
                "LOCATION": self.REDIS_URL,
                "OPTIONS": {
                    "COMPRESSOR":
                    "django_redis.compressors.zlib.ZlibCompressor",  # noqa
                    "SERIALIZER":
                    "django_redis.serializers.msgpack.MSGPackSerializer",  # noqa
                },
            },
            "store": {
                "BACKEND": "django_redis.cache.RedisCache",
                "LOCATION": self.REDIS_STORE_URL,
                "OPTIONS": {
                    "COMPRESSOR":
                    "django_redis.compressors.zlib.ZlibCompressor",  # noqa
                    "SERIALIZER":
                    "django_redis.serializers.msgpack.MSGPackSerializer",  # noqa
                },
            },
        }

    LOGGING_USE_JSON = values.BooleanValue(False)

    LOGGING_DEFAULT_LEVEL = values.Value("INFO")

    def LOGGING(self):
        return {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "json": {
                    "()": "dockerflow.logging.JsonLogFormatter",
                    "logger_name": "tecken",
                },
                "verbose": {
                    "format": "%(levelname)s %(asctime)s %(name)s %(message)s"
                },
            },
            "handlers": {
                "console": {
                    "level": self.LOGGING_DEFAULT_LEVEL,
                    "class": "logging.StreamHandler",
                    "formatter":
                    ("json" if self.LOGGING_USE_JSON else "verbose"),
                },
                "sentry": {
                    "level":
                    "ERROR",
                    "class": ("raven.contrib.django.raven_compat.handlers"
                              ".SentryHandler"),
                },
                "null": {
                    "class": "logging.NullHandler"
                },
            },
            "root": {
                "level": "INFO",
                "handlers": ["sentry", "console"]
            },
            "loggers": {
                "django": {
                    "level": "WARNING",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "django.db.backends": {
                    "level": "ERROR",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "django.request": {
                    "level": "ERROR",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "raven": {
                    "level": "DEBUG",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "sentry.errors": {
                    "level": "DEBUG",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "tecken": {
                    "level": "DEBUG",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "mozilla_django_oidc": {
                    "level": "DEBUG",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "celery.task": {
                    "level": "DEBUG",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "markus": {
                    "level": "INFO",
                    "handlers": ["console"],
                    "propagate": False,
                },
                "request.summary": {
                    "handlers": ["console"],
                    "level": "DEBUG",
                    "propagate": False,
                },
                "django.security.DisallowedHost": {
                    "handlers": ["null"],
                    "propagate": False,
                },
            },
        }

    CSRF_FAILURE_VIEW = "tecken.views.csrf_failure"
    CSRF_USE_SESSIONS = values.BooleanValue(True)

    # The order here matters. Symbol download goes through these one
    # at a time.
    # Ideally you want the one most commonly hit first unless there's a
    # cascading reason you want other buckets first.
    # By default, each URL is assumed to be private!
    # If there's a bucket you want to include that should be accessed
    # by HTTP only, add '?access=public' to the URL.
    # Note that it's empty by default which is actually not OK.
    # For production-like environments this must be something or else
    # Django won't start. (See tecken.apps.TeckenAppConfig)
    #
    SYMBOL_URLS = values.ListValue([])

    # Same as with SYMBOL_URLS, this has to be set to something
    # or else Django won't start.
    UPLOAD_DEFAULT_URL = values.Value()

    # When an upload comes in with symbols from a Try build, these symbols
    # mustn't be uploaded with the "regular symbols".
    # This value can be very similar to UPLOAD_DEFAULT_URL in that
    # it can use the exact same S3 bucket but have a different prefix.
    #
    # Note! By default the value for 'UPLOAD_TRY_SYMBOLS_URL' becomes
    # the value of 'UPLOAD_DEFAULT_URL' but with a '/try' suffix added.
    UPLOAD_TRY_SYMBOLS_URL = values.Value()
    # # The reason for this is to simplify things in local dev and non-Prod
    # # environments where the location isn't as important.
    # # Basically, if don't set this, the value
    # # becomes `settings.UPLOAD_DEFAULT_URL + '/try'` (but carefully so)
    # @property
    # def UPLOAD_TRY_SYMBOLS_URL(self):
    #     print(Configuration.LANGUAGES)
    #     print(Configuration.UPLOAD_TRY_SYMBOLS_URL)
    #     # # super()
    #     # print(dir(self))
    #     # print(self.UPLOAD_TRY_SYMBOLS_URL.value.copy())
    #     return '/TRY'
    #     value = super().value
    #     return value + '/TRY'

    # The config is a list of tuples like this:
    # 'email:url' where the email part can be a glob like regex
    # For example '*@example.com:https://s3-us-west-2.amazonaws.com/mybucket'
    # will upload all symbols to a bucket called 'mybucket' for anybody
    # with a @example.com email.

    # This is a config that, typed as a Python dictionary, specifies
    # specific email addresses or patterns to custom URLs.
    # For example '{"*****@*****.**": "https://s3.amazonaws.com/mybucket"}'
    # or '{"*@example.com": "https://s3.amazonaws.com/otherbucket"}' for
    # anybody uploading with an @example.com email address.
    UPLOAD_URL_EXCEPTIONS = values.DictValue({})

    # When an upload comes in, we need to store it somewhere that it
    # can be shared between the webapp and the Celery worker.
    # In production-like environments this can't be a local filesystem
    # path but needs to one that is shared across servers. E.g. EFS.
    UPLOAD_INBOX_DIRECTORY = values.Value("./upload-inbox")

    # The default prefix for locating all symbols
    SYMBOL_FILE_PREFIX = values.Value("v1")

    # During upload, for each file in the archive, if the extension
    # matches this list, the file gets gzip compressed before uploading.
    COMPRESS_EXTENSIONS = values.ListValue(["sym"])

    # For specific file uploads, override the mimetype.
    # For .sym files, for example, if S3 knows them as 'text/plain'
    # they become really handy to open in a browser and view directly.
    MIME_OVERRIDES = values.DictValue({"sym": "text/plain"})

    # Number of seconds to wait for a symbol download. If this
    # trips, no error will be raised and we'll just skip using it
    # as a known symbol file.
    # The value gets cached as an empty dict for one hour.
    SYMBOLS_GET_TIMEOUT = values.Value(5)

    # Individual strings that can't be allowed in any of the lines in the
    # content of a symbols archive file.
    DISALLOWED_SYMBOLS_SNIPPETS = values.ListValue([
        # https://bugzilla.mozilla.org/show_bug.cgi?id=1012672
        "qcom/proprietary"
    ])

    DOCKERFLOW_CHECKS = [
        "dockerflow.django.checks.check_database_connected",
        "dockerflow.django.checks.check_migrations_applied",
        "dockerflow.django.checks.check_redis_connected",
        "tecken.dockerflow_extra.check_redis_store_connected",
        "tecken.dockerflow_extra.check_s3_urls",
    ]

    # We can cache quite aggressively here because the SymbolDownloader
    # has chance to invalidate certain keys.
    # Also, any time a symbol archive file is upload, for each file within
    # that we end up uploading to S3 we also cache invalidate.
    SYMBOLDOWNLOAD_EXISTS_TTL_SECONDS = values.IntegerValue(60 * 60 * 6)

    # Whether to start a background task to search for symbols
    # on Microsoft's server is protected by an in-memory cache.
    # This is quite important. Don't make it too long or else clients
    # won't be able retry to see if a Microsoft symbol has been successfully
    # downloaded by the background job.
    # We can tweak this when we later learn more about the amount
    # attempted symbol downloads for .pdb files we get that 404.
    MICROSOFT_DOWNLOAD_CACHE_TTL_SECONDS = values.IntegerValue(60)

    # cabextract is installed by Docker and used to unpack .pd_ files to .pdb
    # It's assumed to be installed on $PATH.
    CABEXTRACT_PATH = values.Value("cabextract")

    # dump_syms is downloaded and installed by docker/build_dump_syms.sh
    # and by default gets to put this specific location.
    # If you change this, please make sure it works with
    # how docker/build_dump_syms.sh works.
    DUMP_SYMS_PATH = values.Value("/dump_syms/dump_syms")

    # How many uploads to display per page when paginating through
    # past uploads.
    API_UPLOADS_BATCH_SIZE = 20
    API_UPLOADS_CREATED_BATCH_SIZE = 20
    API_FILES_BATCH_SIZE = 40
    API_DOWNLOADS_MISSING_BATCH_SIZE = 20
    API_DOWNLOADS_MICROSOFT_BATCH_SIZE = 20

    # Every time we do a symbol upload, we also take a look to see if there
    # are incomplete uploads that could have failed due to some unlucky
    # temporary glitch.
    # When we do the reattempt, we need to wait sufficiently long because
    # the upload might just be incomplete because it's in the queue, not
    # because it failed.
    # Note also, if the job is put back into a celery job, we also log
    # this in the cache so that it doesn't add it more than once. That
    # caching uses this same timeout.
    UPLOAD_REATTEMPT_LIMIT_SECONDS = values.IntegerValue(60 * 60 * 12)

    # When you "upload by download", the URL's domain needs to be in this
    # whitelist. This is to double-check that we don't allow downloads from
    # domains we don't fully trust.
    ALLOW_UPLOAD_BY_DOWNLOAD_DOMAINS = values.ListValue(
        ["queue.taskcluster.net"])

    # A list of file extensions that if a file is NOT one of these extensions
    # we can immediately return 404 and not bother to process for anything
    # else.
    # It's case sensitive and has to be lower case.
    # As a way to get marginal optimization of this, make sure '.sym' is
    # first in the list since it's the most common.
    DOWNLOAD_FILE_EXTENSIONS_WHITELIST = values.ListValue(
        [".sym", ".dl_", ".ex_", ".pd_", ".dbg.gz", ".tar.bz2"])
Example #29
0
class Common(Configuration):

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = values.SecretValue()

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = values.BooleanValue(False)

    ALLOWED_HOSTS = []

    #Trying to set up email contact for the website
    SENDGRID_API_KEY = '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'

    EMAIL_HOST = 'smtp.sendgrid.net'
    EMAIL_HOST_USER = '******'
    EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
    EMAIL_PORT = 587
    EMAIL_USE_TLS = True

    # Application definition
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'whitenoise.runserver_nostatic',
        'django.contrib.staticfiles',
        'django_extensions',
        'django_select2',
        'webpack_loader',
        'web_omics.users',
        'registration',
        'rest_framework',
        'django_spaghetti',
        'met_explore',
    ]

    SPAGHETTI_SAUCE = {
        'apps': ['met_explore'],
        'show_fields': True,
        'exclude': {
            'auth': ['user']
        }
    }

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
            },
        },
        # If an env_variable is not set use 'INFO' - set in PyCharm run configurations
        'root': {
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
            'handlers': ['console']
        }
    }

    WEBPACK_LOADER = {
        'DEFAULT': {
            'BUNDLE_DIR_NAME': 'bundles/',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        }
    }

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    ROOT_URLCONF = 'web_omics.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'web_omics.wsgi.application'

    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
    DATABASES = values.DatabaseURLValue('sqlite:///{}'.format(
        os.path.join(BASE_DIR, 'db.sqlite3')))

    # Password validation
    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME':
            'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME':
            'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]

    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/
    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/
    STATIC_URL = '/static/'
    STATIC_PATH = os.path.join(BASE_DIR, 'static')
    STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
    STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

    STATICFILES_DIRS = (STATIC_PATH, )

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
            'LOCATION': os.path.join(BASE_DIR, 'django_cache'),
            'TIMEOUT': CACHE_DURATION
        }
    }

    # For file upload
    # See https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

    AUTH_USER_MODEL = 'users.User'
    LOGIN_URL = reverse_lazy('login')
Example #30
0
class Common(Configuration):

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'django.contrib.sites',

        # Auth and users
        'rest_framework',            # utilities for rest apis
        'rest_framework.authtoken',  # token authentication
        'allauth',
        'allauth.account',
        'rest_auth',
        'rest_auth.registration',

        # Third party apps
        'django_rq',                 # asynchronous queuing
        'versatileimagefield',       # image manipulation

        # Your apps
        'users',
        'stories'
    )

    # https://docs.djangoproject.com/en/1.8/topics/http/middleware/
    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'django.middleware.security.SecurityMiddleware'
    )

    ROOT_URLCONF = 'urls'

    SECRET_KEY = 'Not a secret'
    WSGI_APPLICATION = 'wsgi.application'

    # Email
    EMAIL_BACKEND = values.Value('django.core.mail.backends.smtp.EmailBackend')

    MANAGERS = (
        ('Author', '*****@*****.**'),
    )

    # Postgres
    DATABASES = values.DatabaseURLValue('postgres://localhost/baretravel')

    # General
    APPEND_SLASH = values.BooleanValue(False)
    TIME_ZONE = 'UTC'
    LANGUAGE_CODE = 'en-us'
    # If you set this to False, Django will make some optimizations so as not
    # to load the internationalization machinery.
    USE_I18N = False
    USE_L10N = True
    USE_TZ = True
    LOGIN_REDIRECT_URL = '/'

    # Static Files
    STATIC_ROOT = join(os.path.dirname(BASE_DIR), 'staticfiles')
    STATICFILES_DIRS = [join(os.path.dirname(BASE_DIR), 'static'), ]
    STATIC_URL = '/static/'
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )

    # Media files
    MEDIA_ROOT = join(os.path.dirname(BASE_DIR), 'media')
    MEDIA_URL = '/media/'

    SITE_ID = 1

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [STATICFILES_DIRS],
            'OPTIONS': {
                'context_processors': [
                    'django.contrib.auth.context_processors.auth',
                    'django.template.context_processors.debug',
                    'django.template.context_processors.i18n',
                    'django.template.context_processors.media',
                    'django.template.context_processors.static',
                    'django.template.context_processors.tz',
                    'django.contrib.messages.context_processors.messages'
                ],
                'loaders':[
                    ('django.template.loaders.cached.Loader', [
                        'django.template.loaders.filesystem.Loader',
                        'django.template.loaders.app_directories.Loader',
                    ]),
                ],
            },
        },
    ]

    # Set DEBUG to False as a default for safety
    # https://docs.djangoproject.com/en/dev/ref/settings/#debug
    DEBUG = values.BooleanValue(False)
    for config in TEMPLATES:
        config['OPTIONS']['debug'] = DEBUG

    # Logging
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse'
            }
        },
        'formatters': {
            'verbose': {
                'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
            },
            'simple': {
                'format': '%(levelname)s %(message)s'
            },
            'rq_console': {
                'format': '%(asctime)s %(message)s',
                'datefmt': '%H:%M:%S',
            },
        },
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'filters': ['require_debug_false'],
                'class': 'django.utils.log.AdminEmailHandler'
            },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'rq_console': {
                'level': 'DEBUG',
                'class': 'rq.utils.ColorizingStreamHandler',
                'formatter': 'rq_console',
                'exclude': ['%(asctime)s'],
            },
        },
        'loggers': {
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True
            },
            'rq.worker': {
                'handlers': ['rq_console'],
                'level': 'DEBUG'
            },
        }
    }

    # Custom user app
    AUTH_USER_MODEL = 'users.User'

    # Django Rest Framework
    REST_FRAMEWORK = {
        'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
        'PAGE_SIZE': 100,
        'DATETIME_FORMAT': '%Y-%m-%dT%H:%M:%S%z',
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework.renderers.JSONRenderer',
            'rest_framework.renderers.BrowsableAPIRenderer',
        ),
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ],
        'DEFAULT_AUTHENTICATION_CLASSES': (
            # 'rest_framework.authentication.SessionAuthentication',
            # 'rest_framework.authentication.TokenAuthentication',
            'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        )
    }

    # Rest auth
    REST_USE_JWT = True

    # Versatile Image Field
    VERSATILEIMAGEFIELD_SETTINGS = {
        # The amount of time, in seconds, that references to created images
        # should be stored in the cache. Defaults to `2592000` (30 days)
        'cache_length': 2592000,
        'cache_name': 'versatileimagefield_cache',
        'jpeg_resize_quality': 70,
        'sized_directory_name': '__sized__',
        'filtered_directory_name': '__filtered__',
        'placeholder_directory_name': '__placeholder__',
        'create_images_on_demand': False
    }