class Prod(Base): """Production settings (override default values with environment vars""" SECRET_KEY = values.SecretValue() DEBUG = False SASS_OUTPUT_STYLE = 'compressed' # Set like this: DJANGO_ADMINS=Foo,[email protected];Bar,[email protected] ADMINS = values.SingleNestedTupleValue() # Set like this: DJANGO_ALLOWED_HOSTS=foo.com,bar.net ALLOWED_HOSTS = values.ListValue([ '127.0.0.1', 'localhost', 'oldp.local', 'de.oldp.local' ]) # Set like this: DJANGO_LANGUAGES_DOMAINS="{'de.foo.com':'de','fr.foo.com':'fr'}" LANGUAGES_DOMAINS = values.DictValue({ 'localhost:8000': 'en', 'oldp.local:8000': 'en', 'de.oldp.local:8000': 'de', '127.0.0.1:8000': 'de', })
class Prod(Base): """Production settings (override default values with environment vars""" SECRET_KEY = values.SecretValue() DEBUG = False # Set like this: DJANGO_ADMINS=Foo,[email protected];Bar,[email protected] ADMINS = values.SingleNestedTupleValue()
class Prod(Common): """ The in-production settings """ DEBUG = False SECRET_KEY = values.SecretValue() ADMINS = values.SingleNestedTupleValue() ALLOWED_HOSTS = values.ListValue() DATABASES = values.DatabaseURLValue() EMAIL = values.EmailURLValue() REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), } STATIC_ROOT = values.PathValue() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'pilotwire_handler': { 'level': 'INFO', 'class': 'heating.log.PilotwireHandler', 'logLength': 500, }, }, 'loggers': { 'heating.pilotwire': { 'handlers': ['pilotwire_handler'], 'level': 'INFO', }, }, } # Authentication AUTHENTICATION_BACKENDS = [ 'core.auth.backends.SettingsBackend', ] + Common.AUTHENTICATION_BACKENDS # pylint: disable=no-member ADMIN_LOGIN = values.Value() ADMIN_PASSWORD = values.SecretValue()
class Production(Base): CSRF_COOKIE_SECURE = values.BooleanValue(True) SESSION_COOKIE_SECURE = values.BooleanValue(True) ADMINS = values.SingleNestedTupleValue() MANAGERS = ADMINS IGNORABLE_404_URLS = [ re.compile(r'^/apple-touch-icon.*\.png$'), re.compile(r'^/favicon.ico$'), re.compile(r'^/robots.txt$'), re.compile(r'^/phpmyadmin/'), re.compile(r'\.(cgi|php|pl)$'), ] CORS_ORIGIN_WHITELIST = values.ListValue()
class Production(Common): INSTALLED_APPS = Common.INSTALLED_APPS SECRET_KEY = values.SecretValue() GEOS_LIBRARY_PATH = values.Value('', environ_prefix=False) GDAL_LIBRARY_PATH = values.Value('', environ_prefix=False) PROJ4_LIBRARY_PATH = values.Value('', environ_prefix=False) ALLOWED_HOSTS = ['beta.tulsawebdevs.org', 'twd.destos.com'] # django-secure # This ensures that Django will be able to detect a secure connection # properly on Heroku. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Django secure disabled for now TODO, get ssl key for beta server # INSTALLED_APPS += ("djangosecure", ) # set this to 60 seconds and then to 518400 when you can prove it works 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(False) SESSION_COOKIE_HTTPONLY = values.BooleanValue(True) SECURE_SSL_REDIRECT = values.BooleanValue(True) # end django-secure INSTALLED_APPS += ("gunicorn", ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' ADMINS = values.SingleNestedTupleValue()
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: BASE_DIR / "subdir". BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/stable/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 = values.BooleanValue(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 = "{{cookiecutter.project_slug}}.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 = "{{cookiecutter.project_slug}}.wsgi.application" # Database # https://docs.djangoproject.com/en/stable/ref/settings/#databases DATABASES = values.DatabaseURLValue() # Password validation # https://docs.djangoproject.com/en/stable/ref/settings/#auth-password-validators # 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/stable/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/stable/howto/static-files/ STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "static" STATICFILES_STORAGE = ( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) # Stored files # https://docs.djangoproject.com/en/stable/topics/files/{% if cookiecutter.use_media_volume == "Yes" %} # noqa MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media" # noqa{% else %} # MEDIA_URL = "/media/" # MEDIA_ROOT = BASE_DIR / "media"{% endif %} # Email Settings # https://docs.djangoproject.com/en/stable/topics/email/ ADMINS = values.SingleNestedTupleValue( (("admin", "errors@{{cookiecutter.domain_url}}"),) ) DEFAULT_FROM_EMAIL = values.EmailValue("info@{{cookiecutter.domain_url}}") EMAIL_SUBJECT_PREFIX = "[{{cookiecutter.project_name}}] " EMAIL_USE_LOCALTIME = True SERVER_EMAIL = values.EmailValue("server@{{cookiecutter.domain_url}}") # Email URL # https://django-configurations.readthedocs.io/en/stable/values/ EMAIL = values.EmailURLValue("console://") # Translation # https://docs.djangoproject.com/en/stable/topics/i18n/translation/ # LANGUAGES = (("en", "English"), ("it", "Italiano")) # Clickjacking Protection # https://docs.djangoproject.com/en/stable/ref/clickjacking/ X_FRAME_OPTIONS = "SAMEORIGIN" # Default: 'SAMEORIGIN'
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', # redirects app 'django.contrib.redirects', # Useful template tags: # 'django.contrib.humanize', # Admin 'suitlocale', 'suit', 'django.contrib.admin', ) THIRD_PARTY_APPS = ( 'crispy_forms', 'allauth', # 'allauth.account', 'sorl.thumbnail', 'envelope', 'solo', 'django_perseus', 'rest_framework', 'ckeditor', 'widget_tweaks', 'wkhtmltopdf', 'taggit' ) # Apps specific for this project go here. LOCAL_APPS = ( 'pdf_kit', 'cacao', 'configuracion', ) # 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', # redirect middleware 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', ) # 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 = values.SingleNestedTupleValue(( ('Alice', 'alice@localhost'), ('Bob', 'bob@localhost'), )) # 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/cacao_app') # 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 = 'es-NI' # 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", '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 'context.guia_items', ) # 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', ) # 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 LOGIN_REDIRECT_URL = "/" 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, }, } } # Django REST Framework hide API docs REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } # END LOGGING CONFIGURATION # Your common stuff: Below this line define 3rd party library settings SUIT_CONFIG = { 'ADMIN_NAME': 'Cacao', 'SHOW_REQUIRED_ASTERISK': True, 'CONFIRM_UNSAVED_CHANGES': True, 'MENU': ( {'app': 'cacao', 'label': 'Guias de Cacao', 'icon': 'icon-leaf'}, {'app': 'configuracion', 'icon': 'icon-cog'}, {'label': 'Archivos estaticos', 'icon': 'icon-globe', 'models': ( {'label': 'Generar archivos estaticos', 'url': '/admin/static-generator/'}, )}, {'app': 'auth', 'label': 'Usuarios y Grupos', 'icon': 'icon-lock'}, {'app': 'sites', 'icon': 'icon-chevron-right'}, {'app': 'redirects', 'icon': 'icon-repeat'}, ), # misc 'LIST_PER_PAGE': 15, 'HEADER_DATE_FORMAT': 'l, j, F Y', } # CKEditor CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' CKEDITOR_CONFIGS = { 'default': { 'toolbar': [ ['Format', 'Bold', 'Italic', 'Underline', 'SpellChecker', '-', 'NumberedList', 'BulletedList', 'Indent', 'Outdent', 'JustifyLeft', 'JustifyCenter', '-', 'JustifyRight', 'JustifyBlock', 'PasteText', 'PasteFromWord', '-', 'Find', 'Replace', 'Cut', 'Copy', 'Paste', '-', 'Image', 'Table', 'Link', 'Unlink', 'SectionLink', 'Undo', 'Redo', 'Source', 'Maximize', ], ], 'width': 'auto', 'allowedContent': True, 'removePlugins': 'stylesheetparser', 'extraAllowedContent': 'iframe[*]', }, } # FB App ID FB_APP_ID = values.SecretValue() # GA APP ID GA_APP_ID = values.SecretValue() # used for the views delete folders and open the guide folder PROJECT_DIR = dirname(dirname(abspath(__file__))) PERSEUS_BUILD_DIR = '/tmp/ihcafe/build' PERSEUS_SOURCE_DIR = '/tmp/ihcafe/guia' # config for create pdf's PDF_KIT_MODEL = 'cacao.Content' THUMBNAIL_DEBUG = True
class Prod(Configuration): """ Configuration settings used in production. This should include all the settings needed in production. To keep `Dev` and `Test` settings as close as possible to those in production we use `Prod` as a base and only override as needed. """ BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ########################################################################### # Core Django settings # # For a complete list see https://docs.djangoproject.com/en/2.2/ref/settings/ ########################################################################### # Ensure debug is always false in production (overridden in development) DEBUG = False # Require that a `DJANGO_SECRET_KEY` environment # variable is set during production SECRET_KEY = values.SecretValue() # In production, use wildcard because load balancers # perform health checks without host specific Host header value ALLOWED_HOSTS = ["*"] # It is being run behind Google Cloud Load Balancer, so look for this header SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # Enforce HTTPS # Allow override to be able to test other prod settings during development # in a Docker container (ie. locally not behind a HTTPS load balancer) # See `make run-prod` SECURE_SSL_REDIRECT = values.BooleanValue(True) # Do not redirect the status check and other internal URLs # to HTTPS so that HTTP health checks and metric scraping work. SECURE_REDIRECT_EXEMPT = [ r"^api/status/?$", r"^api/workers/", r"^api/jobs/", r"^internal/", r"^/?$", ] INSTALLED_APPS = [ # Django contrib apps "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", # Required by allauth "django.contrib.humanize", # Third party apps "allauth", "allauth.account", "allauth.socialaccount", # Social account providers. See # http://django-allauth.readthedocs.org/en/latest/providers.html # When you add an item here you must: # - add an entry in SOCIALACCOUNT_PROVIDERS below # - register Stencila as an API client or app with the provider # - add a SocialApp instance (/admin/socialaccount/socialapp/add/) "allauth.socialaccount.providers.github", "allauth.socialaccount.providers.google", "allauth.socialaccount.providers.orcid", "allauth.socialaccount.providers.twitter", "avatar", "crispy_forms", "crispy_forms_bulma", "polymorphic", "storages", "rest_framework", "drf_yasg", "knox", "django_celery_beat", "django_filters", "django_intercom", "django_prometheus", "djstripe", # Our apps # Uses dotted paths to AppConfig subclasses as # recommended in https://docs.djangoproject.com/en/2.2/ref/applications/#configuring-applications "users.apps.UsersConfig", "accounts.apps.AccountsConfig", "projects.apps.ProjectsConfig", "stencila_open.apps.StencilaOpenConfig", "jobs.apps.JobsConfig", ] MIDDLEWARE = [ "django_prometheus.middleware.PrometheusBeforeMiddleware", "lib.middleware.ie_detect_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", "django_prometheus.middleware.PrometheusAfterMiddleware", ] ROOT_URLCONF = "urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(BASE_DIR, "templates"), # Needed to ensure that allauth templates are overidden by ours os.path.join(BASE_DIR, "users", "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", "lib.template_context_processors.versions", "lib.template_context_processors.settings", "lib.template_context_processors.features", ], }, }, ] WSGI_APPLICATION = "wsgi.application" SITE_ID = 1 # Required by allauth # Database defaults to `dev.sqlite3` but can be set using `DATABASE_URL` env var # Note that the three leading slashes are *intentional* # See https://github.com/kennethreitz/dj-database-url#url-schema DATABASES = values.DatabaseURLValue("sqlite:///{}".format( os.path.join(BASE_DIR, "dev.sqlite3"))) DEFAULT_FROM_EMAIL = values.Value("*****@*****.**") # Authentication AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) ACCOUNT_EMAIL_REQUIRED = ( True # tell allauth to require an email address when signing up ) 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_URL = "/me/signin" LOGIN_REDIRECT_URL = "/" # 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 TESTING = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ # Use unpkg.com CDN to serve static assets (overridden in development) STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = values.Value( "https://unpkg.com/@stencila/hub@{}/director/static/".format( __version__)) STATICFILES_DIRS = [os.path.join(BASE_DIR, "assets")] # Media files (uploaded by users) # https://docs.djangoproject.com/en/2.0/topics/files/ MEDIA_ROOT = os.path.join(BASE_DIR, "storage") MEDIA_URL = "/media/" DATA_UPLOAD_MAX_MEMORY_SIZE = values.IntegerValue(5 * 1024 * 1024) # Logging LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "console": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(message)s" }, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "console" } }, "loggers": { "": { "level": "WARNING", "handlers": ["console"] } }, } ########################################################################### # Settings for third-party application in INSTALLED_APPS ########################################################################### CRISPY_ALLOWED_TEMPLATE_PACKS = ["bulma"] CRISPY_TEMPLATE_PACK = "bulma" CRISPY_CLASS_CONVERTERS = { "checkboxinput": "checkbox", "numberinput": "input", } AVATAR_GRAVATAR_DEFAULT = "identicon" SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE": [ "profile", "email", "https://www.googleapis.com/auth/documents", "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive", ], "AUTH_PARAMS": { "access_type": "offline" }, } } SOCIALACCOUNT_ADAPTER = "lib.social_account_adapter.SocialAccountAdapter" REST_FRAMEWORK = { # Use camel casing for everything (inputs and outputs) "DEFAULT_RENDERER_CLASSES": ("djangorestframework_camel_case.render.CamelCaseJSONRenderer", ), "DEFAULT_PARSER_CLASSES": ("djangorestframework_camel_case.parser.CamelCaseJSONParser", ), "DEFAULT_PERMISSION_CLASSES": ( # Default is for API endpoints to require the user to be authenticated "rest_framework.permissions.IsAuthenticated", ), "DEFAULT_AUTHENTICATION_CLASSES": [ # Default is for token and Django session authentication "general.api.authentication.BasicAuthentication", "knox.auth.TokenAuthentication", "rest_framework.authentication.SessionAuthentication", ], "EXCEPTION_HANDLER": "general.api.handlers.custom_exception_handler", "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 50, # Use JSON by default when using the test client # https://www.django-rest-framework.org/api-guide/testing/#setting-the-default-format "TEST_REQUEST_DEFAULT_FORMAT": "json", } # django-rest-knox settings for API tokens # See http://james1345.github.io/django-rest-knox/settings/ REST_KNOX = { # The Prefix to use in the Authorization header "AUTH_HEADER_PREFIX": "Token", # Automatically refresh the token when it is used "AUTO_REFRESH": True, # Period until token expires. None will create tokens that never expire. "TOKEN_TTL": datetime.timedelta(days=7), } SWAGGER_SETTINGS = { "SECURITY_DEFINITIONS": { "API": { "type": "apiKey", "name": "Authorization", "in": "header" } } } # django-rest-framework-jwt settings for JWT execution session tokens # See https://jpadilla.github.io/django-rest-framework-jwt/#additional-settings JWT_AUTH = { # The Prefix to use in the Authorization header "JWT_AUTH_HEADER_PREFIX": "JWT", # Period until token expires. Generally recommended to be <15 mins "JWT_EXPIRATION_DELTA": datetime.timedelta(minutes=10), # Allow token to be refreshed within a given period from initial issuance "JWT_ALLOW_REFRESH": True, "JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=1), } ########################################################################### # Settings for integration with external third-party services # i.e. Stripe, Sentry etc # # Many of these are empty, intentionally, and may cause an error, if you # go to a particular page that requires them. ########################################################################### # Use GoogleCloudStorage for uploads DEFAULT_FILE_STORAGE = "lib.storage.CustomPublicGoogleCloudStorage" GS_PROJECT_ID = values.Value() GS_BUCKET_NAME = values.Value() # Use SendGrid for emails EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" SENDGRID_API_KEY = values.Value() # Use Intercom for in app messages # For other potential settings see # https://django-intercom.readthedocs.io/en/latest/settings.html INTERCOM_APPID = values.Value() # Token to use the Intercom API. See # https://developers.intercom.com/building-apps/docs/authentication-types#section-access-tokens INTERCOM_ACCESS_TOKEN = values.Value() # Use PostHog for product analytics POSTHOG_KEY = values.Value() # Use Sentry for error reporting SENTRY_DSN = values.Value() # Use Strip for payments # In production, use live mode (overridden in development to use test keys) STRIPE_LIVE_MODE = True STRIPE_LIVE_PUBLIC_KEY = values.Value("") STRIPE_LIVE_SECRET_KEY = values.Value("sk_live_test") DJSTRIPE_WEBHOOK_VALIDATION = "retrieve_event" ########################################################################### # Settings for integration with other Hub services i.e. `broker`, `storage` etc ########################################################################### # An environment name e.g. prod, staging, test used for # exception reporting / filtering DEPLOYMENT_ENVIRONMENT = values.Value(environ_prefix=None) # URL to the `broker` service BROKER_URL = values.SecretValue(environ_prefix=None) # Path to the `storage` service mounted as a # local directory. Defaults to the `data` sub-directory # of the `storage` service in this repo STORAGE_DIR = values.Value(os.path.join(BASE_DIR, "..", "storage", "data")) ########################################################################### # Settings used internally in the `director`'s own code # # Some of these may be renamed / removed in the future ########################################################################### # Allow for username / password API authentication # This is usually disallowed in production (in favour of tokens) # but is permitted during development development for convenience. API_BASIC_AUTH = values.BooleanValue(False) EXECUTION_SERVER_HOST = values.Value() EXECUTION_SERVER_PROXY_PATH = values.Value() EXECUTION_CLIENT = values.Value("NIXSTER") GS_PUBLIC_READABLE_PATHS = ["avatars/*"] # these paths will be made publicly readable in the Google Storage bucket after being written to # Path to Encoda executable STENCILA_ENCODA_PATH = values.Value( os.path.join(BASE_DIR, "node_modules", "@stencila", "encoda", "dist", "cli.js")) STENCILA_CLIENT_USER_AGENT = values.Value("Stencila Hub HTTP Client") EXECUTA_HOSTS = values.SingleNestedTupleValue("") SPARKLA_PROJECT_ROOT = values.Value("") # Rudimentary feature toggle FEATURES = {"PROJECT_SESSION_SETTINGS": False} # Ensure JWT secret is set JWT_SECRET = values.SecretValue() @classmethod def post_setup(cls): # Default for environment name is the name of the settings class if not cls.DEPLOYMENT_ENVIRONMENT: cls.DEPLOYMENT_ENVIRONMENT = cls.__name__.lower() # Add Basic auth if allowed if cls.API_BASIC_AUTH: cls.REST_FRAMEWORK[ "DEFAULT_AUTHENTICATION_CLASSES"].insert( # type: ignore 0, "rest_framework.authentication.BasicAuthentication", ) # Setup sentry if a DSN is provided if cls.SENTRY_DSN: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn=cls.SENTRY_DSN, release="hub@{}".format(__version__), integrations=[DjangoIntegration()], send_default_pii=True, environment=cls.DEPLOYMENT_ENVIRONMENT, )
class Base(Configuration): ''' All configurations should sublcass this base class. This contains all that is required, aside from custom endpoints that will vary per deployment and/or environment. Defaults have been set to err on the side of caution, so DEBUG, ADMIN, etc will have to be explictly turned on where necessary. ''' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # THIS IS JUST A DEFAULT THAT WAS GENERATED FOR LOCAL DEVELOPMENT # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = values.Value('abceasyas123') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = values.BooleanValue(False) ADMIN_ENABLED = values.BooleanValue(False) SESSION_EXPIRE_AT_BROWSER_CLOSE = values.BooleanValue(True) AUTH_USER_MODEL = values.Value('users.User') MEMBERSHIP_ENCODE_KEY = values.Value('') MEMBERSHIP_RENEWAL_URL_BASE = values.URLValue('') SHARED_SESSION_SITES = values.ListValue([]) SESSION_COOKIE_DOMAIN = values.Value() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = values.ListValue([]) SITE_ID = values.IntegerValue(1) ADMINS = [('Sir Terence', '*****@*****.**')] SERVER_EMAIL = '*****@*****.**' # SESSION_COOKIE_AGE = 60*60*24 X_FRAME_OPTIONS = 'ALLOW' INSTALLED_APPS = values.ListValue([ # Django packages 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', # External packages 'captcha', 'debug_toolbar', 'django_jinja', 'raven.contrib.django.raven_compat', 'rest_framework_swagger', 'rest_framework.authtoken', 'rest_framework', 'rosetta', 'shared_session', 'storages', 'webpack_loader', 'cacheops', 'robots', 'import_export', # Application packages 'clublink.base', 'clublink.certificates', 'clublink.clubs', 'clublink.cms', 'clublink.corp', 'clublink.landings', 'clublink.users', 'clublink.emails', ]) MIDDLEWARE = values.ListValue([ 'debug_toolbar.middleware.DebugToolbarMiddleware', # Custom middleware 'clublink.base.middleware.HostnameRoutingMiddleware', 'clublink.base.middleware.ShortCircuitMiddleware', # Django 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', # Sites middleware 'django.contrib.sites.middleware.CurrentSiteMiddleware', # Custom middleware 'clublink.base.middleware.SpoofedUserMiddleware', 'clublink.base.middleware.ScaffoldingMiddleware', 'clublink.base.middleware.LocaleMiddleware' ]) ROOT_URLCONF = values.Value('clublink.urls.common') TEMPLATES = values.ListValue([ { 'BACKEND': 'django_jinja.backend.Jinja2', 'DIRS': [ 'templates', ], 'APP_DIRS': True, 'OPTIONS': { 'match_regex': '.+(\.jinja|\.txt)', 'match_extension': None, 'extensions': DEFAULT_EXTENSIONS + [ 'webpack_loader.contrib.jinja2ext.WebpackExtension', 'jinja2.ext.i18n', 'cacheops.jinja2.cache', 'clublink.base.extensions.SharedSession', ], '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.tz', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # Custom context processors 'clublink.base.context_processors.globals' ], } }, { '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 = values.Value('clublink.wsgi.application') CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': values.Value('redis://127.0.0.1:6379/1', environ_name='CACHES_DEFAULT_LOCATION'), 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } # Database # https://docs.djangoproject.com/en/1.11/ref/settings/# # As per: https://github.com/kennethreitz/dj-database-url#url-schema ### <-----------------------------------------------------------------> ### ### NOTE!!!! THIS IS THE ONE VALUE THAT IS NOT PREFIXED WITH DJANGO_ ### # DATABASE_DICT = values.DictValue() # LEGACY_DATABASE_DICT = values.DictValue() ### <-----------------------------------------------------------------> ### DATABASE_ENGINE = values.Value("django.db.backends.mysql") DATABASE_NAME = values.Value() DATABASE_USER = values.Value() DATABASE_PASSWORD = values.Value() DATABASE_HOST = values.Value() DATABASE_PORT = values.Value('3306') LEGACY_DATABASE_ENGINE = values.Value("django.db.backends.mysql") LEGACY_DATABASE_NAME = values.Value() LEGACY_DATABASE_USER = values.Value() LEGACY_DATABASE_PASSWORD = values.Value() LEGACY_DATABASE_HOST = values.Value() LEGACY_DATABASE_PORT = values.Value('3306') @property def DATABASES(self): DATABASES = { 'default': { 'ENGINE': self.DATABASE_ENGINE, 'NAME': self.DATABASE_NAME, 'USER': self.DATABASE_USER, 'PASSWORD': self.DATABASE_PASSWORD, 'HOST': self.DATABASE_HOST, 'PORT': self.DATABASE_PORT } } return DATABASES # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = values.ListValue([ { '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/1.11/topics/i18n/ LANGUAGE_CODE = values.Value('en') LANGUAGES = values.SingleNestedTupleValue(( ('en', _('English')), ('fr', _('French')), )) LOCALE_PATHS = values.SingleNestedTupleValue( (os.path.join(BASE_DIR, 'locale'), )) TIME_ZONE = values.Value('America/Toronto') USE_I18N = values.BooleanValue(True) USE_L10N = values.BooleanValue(True) USE_TZ = values.BooleanValue(True) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ DEFAULT_FILE_STORAGE = values.Value( 'django.contrib.staticfiles.storage.StaticFilesStorage') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'assets'), ) # STATIC # STATIC_URL = values.Value('/static/') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_LOCATION = values.Value('static') STATICFILES_STORAGE = values.Value( 'django.contrib.staticfiles.storage.StaticFilesStorage') # ASSETS # ASSETS_URL = values.Value('/asset_files/') ASSETS_ROOT = os.path.join(BASE_DIR, 'asset_files') ASSETS_LOCATION = values.Value('assets') ASSETS_FILE_STORAGE = values.Value( 'django.contrib.staticfiles.storage.StaticFilesStorage') # MEDIA # MEDIA_URL = values.Value('/media/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_LOCATION = values.Value('media') # WEBPACK # WEBPACK_LOADER = values.DictValue({ 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json') }, }) SWAGGER_SETTINGS = values.DictValue({ 'DOC_EXPANSION': 'list', 'JSON_EDITOR': True, }) CSRF_COOKIE_HTTPONLY = values.BooleanValue(True) SECURE_REDIRECT_EXEMPT = values.ListValue([r'^__health__/$']) GIFT_CERTIFICATE_SITE_URL = values.URLValue() CORP_SITE_URL = values.URLValue() CLUB_SITE_URL = values.Value() ADMIN_SITE_URL = values.URLValue() ADMIN_HOSTNAME = values.RegexValue(r'^admin\.') CORP_HOSTNAME = values.RegexValue(r'^(www\.)?') API_HOSTNAME = values.RegexValue(r'^api\.') GIFT_CERTIFICATE_HOSTNAME = values.RegexValue(r'^giftcertificates\.') GIFT_CARDS_HOSTNAME = values.RegexValue(r'^giftcards\.') def HOSTNAME_URLCONFS(self): return ( (self.ADMIN_HOSTNAME, 'clublink.urls.admin'), (self.CORP_HOSTNAME, 'clublink.urls.corp'), (self.API_HOSTNAME, 'clublink.urls.api'), (self.GIFT_CERTIFICATE_HOSTNAME, 'clublink.urls.gc'), (self.GIFT_CARDS_HOSTNAME, 'clublink.urls.gift_cards'), ) def HOSTNAME_LANGUAGES(self): return ( (self.ADMIN_HOSTNAME, ('en', )), (self.GIFT_CERTIFICATE_HOSTNAME, ('en', )), ) VPN_PROTECTED_VIEWS_ENABLED = values.BooleanValue(True) VPN_IP_ADDRESS = values.Value('10.8.0.1') 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) DEFAULT_FROM_EMAIL_ADDRESS = values.EmailValue('*****@*****.**') MEMBER_SERVICES_EMAIL_ADDRESS = values.EmailValue( '*****@*****.**') GIFT_CERTIFICATE_EMAIL_ADDRESS = values.EmailValue( '*****@*****.**') CORPORATE_EVENTS_EMAIL_ADDRESS = values.EmailValue( '*****@*****.**') MEMBERSHIP_SALES_EMAIL_ADDRESS = values.EmailValue( '*****@*****.**') EVENTS_EMAIL_ADDRESSES = values.ListValue([ '*****@*****.**', '*****@*****.**', '*****@*****.**', ]) IBS_API_WSDL = values.Value() IBS_API_USER = values.Value() IBS_API_PASSWORD = values.Value() IBS_WEBRES_API_ROOT = values.Value() IBS_WEBRES_API_USER = values.Value() IBS_WEBRES_API_PASSWORD = values.Value() GOOGLE_MAPS_API_KEY = values.Value() GOOGLE_ANALYTICS_TRACKING_ID = values.Value() DEFAULT_CERTIFICATE_EMPLOYEE_NUMBER = values.Value() DEFAULT_CERTIFICATE_MEMBERSHIP_NUMBER = values.Value('') CERTIFICATES_BATCH_LIMIT = values.IntegerValue(150) DATA_UPLOAD_MAX_NUMBER_FIELDS = values.IntegerValue(1000) GIFT_CERTIFICATE_IP_WHITELIST_ENABLED = values.BooleanValue(False) GIFT_CERTIFICATE_IP_WHITELIST = values.ListValue() AES_SHARED_KEY = values.Value() DYNAMICS_HOST = values.Value() DYNAMICS_USER = values.Value() DYNAMICS_PASSWORD = values.Value() DYNAMICS_DATABASE = values.Value() NOCAPTCHA = values.BooleanValue(True) RECAPTCHA_PUBLIC_KEY = values.Value() RECAPTCHA_PRIVATE_KEY = values.Value() PASSWORD_RESET_DEBUG = values.BooleanValue(True) PASSWORD_RESET_DEBUG_EMAIL_ADDRESSES = values.ListValue() ASSETS_FILE_STORAGE = values.Value( 'django.core.files.storage.FileSystemStorage') SEARCH_ENGINE_INDEXING_DISABLED = values.BooleanValue(False) SESSION_EXPIRE_AT_BROWSER_CLOSE = values.BooleanValue(True) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 50, 'EXCEPTION_HANDLER': 'clublink.base.api.handlers.logging_exception_handler', } CELERY_BROKER_URL = values.Value() CELERY_RESULT_BACKEND = values.Value()
class Common(object): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = values.SecretValue() DEBUG = values.BooleanValue(True) ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'markdownify', 'django_extensions', 'ckeditor', 'project', ] MARKDOWNIFY_BLEACH = False MARKDOWNIFY_MARKDOWN_EXTENSIONS = ['tables'] 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 = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': False, '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', ], 'loaders': ( 'admin_tools.template_loaders.Loader', 'hamlpy.template.loaders.HamlPyFilesystemLoader', 'hamlpy.template.loaders.HamlPyAppDirectoriesLoader', ), }, }, ] CKEDITOR_CONFIGS = { 'admin': { 'toolbar': 'custom', 'toolbar_custom': [ {'name': 'document', 'items': ['Source']}, {'name': 'clipboard', 'items': [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ]}, {'name': 'editing', 'items': [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt', ]}, {'name': 'styles', 'items': ['Styles', 'Format']}, '/', {'name': 'basicstyles', 'items': [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat', ]}, {'name': 'paragraph', 'items': [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', ]}, {'name': 'links', 'items': ['Link', 'Unlink']}, {'name': 'insert', 'items': ['Table', 'HorizontalRule']}, ], }, } WSGI_APPLICATION = 'project.wsgi.application' 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_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend' SENDGRID_API_KEY = values.Value(None, environ_prefix=None) SERVER_EMAIL = values.Value(None) # DJANGO_ADMINS=Bob,[email protected];Dave,[email protected] ADMINS = values.SingleNestedTupleValue([]) ADMIN_TOOLS_MENU = 'project.admin_menu.CustomMenu' ADMIN_TOOLS_INDEX_DASHBOARD = 'project.admin_dashboard.CustomIndexDashboard' ADMIN_TOOLS_APP_INDEX_DASHBOARD = 'project.admin_dashboard.CustomAppIndexDashboard'
class Common(Configuration): REPO_ROOT_DIR: str = environ.Path(__file__) - 2 APPS_ROOT_DIR: str = REPO_ROOT_DIR.path('aperte') env = environ.Env() # See https://docs.djangoproject.com/en/2.0/ref/settings/ for a description # of each Django setting. # CORE SETTINGS # -------------------------------------------------------------------------- DEBUG = values.BooleanValue(False) TIME_ZONE = values.Value('UTC') USE_TZ = True if USE_TZ: from django.conf.locale.en import formats formats.DATETIME_FORMAT = values.Value( 'm/d/Y h:i:s T', environ_name='DJANGO_DATETIME_FORMAT') LANGUAGE_CODE = values.Value('en-us') LANGUAGES = (('en', _('English')), ) LOCALE_PATHS = (str(APPS_ROOT_DIR.path('locale')), ) USE_I18N = values.BooleanValue(True) USE_L10N = values.BooleanValue(True) FIXTURE_DIRS = (str(APPS_ROOT_DIR.path('fixtures')), ) WSGI_APPLICATION = 'wsgi.application' # Note: This variable is an empty list by default for security reasons. The # allowed hosts for Django to serve must be specified explicitly in # all environments. ALLOWED_HOSTS = values.ListValue([], environ_required=True) # INSTALLED APPS SETTINGS # -------------------------------------------------------------------------- DJANGO_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django_sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', ] LOCAL_APPS = [ 'aperte.base', 'aperte.users', ] THIRD_PARTY_APPS = [ # TODO: Re-enable this. # 'allauth', # 'allauth.account', # 'allauth.socialaccount', # 'allauth.socialaccount.providers.github', # 'allauth.socialaccount.providers.google', # 'allauth.socialaccount.providers.linkedin', # 'allauth.socialaccount.providers.linkedin_oauth2', 'versatileimagefield', # TODO: Re-enable this. # 'corsheaders', 'raven.contrib.django.raven_compat', 'mail_templated', ] INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS + THIRD_PARTY_APPS # URL SETTINGS # -------------------------------------------------------------------------- ROOT_URLCONF = 'aperte.urls' # ADMIN SETTINGS # -------------------------------------------------------------------------- ADMIN_URL = values.Value('admin') ADMINS = [ ("""Adam Cook""", '*****@*****.**'), ] ADMINS = values.SingleNestedTupleValue( (('SME Virtual Network Admin', '*****@*****.**'))) MANAGERS = ADMINS # AUTHENTICATION AND LOGIN SETTINGS # -------------------------------------------------------------------------- AUTH_USER_MODEL = 'users.User' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', # TODO: Re-enable this. #'allauth.account.auth_backends.AuthenticationBackend', ] PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 6, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LOGIN_REDIRECT_URL = 'users:redirect' LOGIN_URL = 'login' # EMAIL SETTINGS # -------------------------------------------------------------------------- DEFAULT_FROM_EMAIL = values.Value( 'SME Virtual Network <*****@*****.**>') EMAIL_SUBJECT_PREFIX = values.Value('[SME Virtual Network]') EMAIL_USE_TLS = values.BooleanValue(True) SERVER_EMAIL = values.Value(DEFAULT_FROM_EMAIL) # DATABASE SETTINGS # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': values.Value('', environ_name='DATABASE_NAME_DEFAULT', environ_required=True), 'USER': values.Value('', environ_name='DATABASE_USER_DEFAULT', environ_required=True), 'PASSWORD': values.SecretValue(environ_name='DATABASE_PASSWORD_DEFAULT'), 'HOST': values.Value('', environ_name='DATABASE_HOST_DEFAULT', environ_required=True), 'PORT': values.Value('5432', environ_name='DATABASE_PORT_DEFAULT'), 'ATOMIC_REQUESTS': True, 'CONN_MAX_AGE': 10 } } # TEMPLATE SETTINGS # -------------------------------------------------------------------------- TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ str(APPS_ROOT_DIR.path('templates')), ], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'aperte.base.context_processors.site_settings', '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', ], }, }, ] CSRF_FAILURE_VIEW = 'aperte.base.views.render_csrf_failure' # STATIC FILE SETTINGS # -------------------------------------------------------------------------- # STATIC_ROOT - The absolute path to the directory where `collectstatic` # will collect static files for deployment. This is only used during # production (not development). STATIC_ROOT = str(REPO_ROOT_DIR.path('static')) # STATICFILES_DIRS - This setting defines the additional locations the # 'staticfiles' app will traverse if the 'FileSystemFinder' finder is # enabled. STATICFILES_DIRS = (str(APPS_ROOT_DIR.path('dist')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) if env.bool('DJANGO_DISABLE_WHITENOISE', default=False): # Whitenoise is disabled. # This branch is for a local development where `collectstatic` will not # be called any time the styles or scripts are changed. This makes # development faster as the browser can refresh with the latest builds # of the styles and/or scripts without having to call `collectstatic` # first. STATIC_URL = '/static/' else: # Whitenoise is enabled. # This branch is for a local development environment which enables # Whitenoise to test a staging or production environment before pushing # the code to the cloud. INSTALLED_APPS = INSTALLED_APPS + [ 'whitenoise.runserver_nostatic', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_HOST = values.URLValue('', environ_name='STATIC_HOST', environ_required=True) STATIC_URL = str(STATIC_HOST) + '/static/' # django-sites SETTINGS # -------------------------------------------------------------------------- # Note: Default setting is 'https' for security reasons. For development, # the setting will likely have to be 'http'. SITE_SCHEME = values.Value('https') SITE_DOMAIN = values.Value('', environ_name='SITE_DOMAIN', environ_required=True) SITE_NAME = values.Value('SME Virtual Network') SITES = { 'current': { 'domain': SITE_DOMAIN, 'scheme': SITE_SCHEME, 'name': SITE_NAME }, } SITE_ID = 'current' # MEDIA SETTINGS # -------------------------------------------------------------------------- MEDIA_ROOT = str(REPO_ROOT_DIR.path('.media')) MEDIA_URL = values.Value('{}://{}/media/'.format(SITE_SCHEME, SITE_DOMAIN)) # SECURITY SETTINGS # -------------------------------------------------------------------------- SECRET_KEY = values.SecretValue() CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_HTTPONLY = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' # django-log-request-id SETTINGS # -------------------------------------------------------------------------- REQUEST_ID_RESPONSE_HEADER = 'REQUEST_ID' # LOGGING SETTINGS # -------------------------------------------------------------------------- LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, 'request_id': { '()': 'log_request_id.filters.RequestIDFilter' } }, 'formatters': { 'complete': { 'format': '%(asctime)s:[%(levelname)s]:logger=%(name)s:request_id=%(request_id)s message="%(message)s"' }, 'simple': { 'format': '%(levelname)s:%(asctime)s: %(message)s' }, 'null': { 'format': '%(message)s', }, }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'complete', 'filters': ['request_id'], }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'sentry': { 'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'formatter': 'complete', 'filters': ['request_id'], }, }, 'loggers': { 'django': { 'handlers': ['null'], 'propagate': False, 'level': 'INFO', }, 'django.request': { 'handlers': ['mail_admins', 'console'], 'level': 'ERROR', 'propagate': False, }, 'django.server': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'hello_world': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, '': { 'handlers': ['console', 'sentry'], 'level': 'ERROR', 'propagate': True, }, } } # MIDDLEWARE SETTINGS # -------------------------------------------------------------------------- MIDDLEWARE = [ # TODO: Re-enable this. # 'corsheaders.middleware.CorsMiddleware', 'log_request_id.middleware.RequestIDMiddleware', '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', ] # CACHE SETTINGS # -------------------------------------------------------------------------- # See https://cloud.google.com/appengine/docs/flexible/java/upgrading#memcache_service # See https://cloud.google.com/appengine/docs/flexible/python/using-redislabs-memcache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': values.Value('', environ_name='CACHE_URL_DEFAULT', environ_required=True), 'OPTIONS': { 'BINARY': True, 'USERNAME': values.Value('', environ_name='CACHE_USERNAME_DEFAULT', environ_required=True), 'PASSWORD': values.SecretValue(environ_name='CACHE_PASSWORD_DEFAULT'), } } } # django-allauth SETTINGS # -------------------------------------------------------------------------- ACCOUNT_ALLOW_REGISTRATION = True ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_ADAPTER = 'aperte.users.adapters.AccountAdapter' SOCIALACCOUNT_ADAPTER = 'aperte.users.adapters.SocialAccountAdapter' # raven SETTINGS # -------------------------------------------------------------------------- RELEASE_VERSION = get_release() SENTRY_CLIENT = 'raven.contrib.django.raven_compat.DjangoClient' RAVEN_CONFIG = { 'dsn': values.Value('', environ_name='SENTRY_DSN'), 'environment': values.Value('production', environ_name='SENTRY_ENVIRONMENT'), 'release': RELEASE_VERSION, } SITE_INFO = { 'RELEASE_VERSION': RELEASE_VERSION, 'IS_RAVEN_INSTALLED': RAVEN_CONFIG['dsn'] is not '' }
class Base(LoggingMixin, Configuration): # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__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 = False ALLOWED_HOSTS = ['*'] ADMINS = values.SingleNestedTupleValue(( ('José Antonio Perdiguero López', '*****@*****.**'), )) # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Project apps 'barrenero_api', 'core', # System utilities 'django_extensions', 'health_check', # REST 'rest_framework', 'rest_framework.authtoken', ) MIDDLEWARE = ( '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', 'whitenoise.middleware.WhiteNoiseMiddleware', ) ROOT_URLCONF = 'barrenero_api.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 = 'barrenero_api.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'config/barrenero_api.db' }, } # Cache DEFAULT_CACHE_TIMEOUT = 60 * 15 CACHES = { 'default': {} } # 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 = os.path.abspath(os.path.join(BASE_DIR, 'assets')) # Copy files to ./barrenero_api/assets STATICFILES_DIRS = [ # os.path.abspath(os.path.join(BASE_DIR, 'client', 'dist')) ] # Media files (Upload by user) MEDIA_ROOT = os.path.abspath(os.path.join(BASE_DIR, 'media')) # Copy media files to ./barrenero_api/media MEDIA_URL = '/media/' # Static finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Regex expresions to exclude from logging at middleware REQUEST_LOGGING_EXCLUDE = { '': ( ), 'admin': ( r'.*', ), 'health_check': ( r'.*', ) } DEFAULT_RESPONSE_HEADERS = { 'Link': ( '<https://docs.sequoia.piksel.com/concepts/api/spec.html>;rel="profile"', ), 'Cache-Control': ( 'no-cache', ), } HEALTH_CHECK_PROVIDERS = { 'health': ( ('ping', 'health_check.providers.health.ping', None, None), ('databases', 'health_check.providers.django.health.databases', None, None), ), 'stats': ( ('databases', 'health_check.providers.django.stats.databases', None, None), ) } AUTH_USER_MODEL = 'core.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } # Local config API_SUPERUSER = values.SecretValue() # Third party APIs NANOPOOL = { 'url': 'https://api.nanopool.org/v1/eth/', 'worker': values.Value(environ_name='WORKER_NAME'), 'token': None } ETHERSCAN = { 'url': 'https://api.etherscan.io/api', 'token': values.SecretValue(environ_name='ETHERSCAN_TOKEN'), } ETHPLORER = { 'url': 'https://api.ethplorer.io/', 'token': values.SecretValue(environ_name='ETHPLORER_TOKEN'), } # Number of seconds since last entry to consider ether mining inactive ETHER_MAX_IDLE = 300 # Mining container names MINERS = { 'barrenero-miner-ether': 'Ether', 'barrenero-miner-storj': 'Storj', } # Storj container name to call commands with docker STORJ_CONTAINER_NAME = 'barrenero-miner-storj' # Storj API STORJ_API = { 'url': 'https://api.storj.io/', }
class Base(LoggingMixin, Configuration): # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__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 = False ALLOWED_HOSTS = ['*'] ADMINS = values.SingleNestedTupleValue( (('{{ cookiecutter.full_name }}', '{{ cookiecutter.email }}'), )) # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Project apps '{{ cookiecutter.app_slug }}', 'core', # System utilities 'django_extensions', 'health_check', ) MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ) ROOT_URLCONF = '{{ cookiecutter.app_slug }}.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 = '{{ cookiecutter.app_slug }}.wsgi.application' # Database DATABASES = { 'default': {}, } # Cache DEFAULT_CACHE_TIMEOUT = 60 * 15 CACHES = {'default': {}} # 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 = os.path.abspath( os.path.join( BASE_DIR, '{{ cookiecutter.app_slug }}', 'assets')) # Copy files to ./{{ cookiecutter.app_slug }}/assets STATICFILES_DIRS = [ os.path.abspath(os.path.join(BASE_DIR, 'client', 'dist')) ] # Media files (Upload by user) MEDIA_ROOT = os.path.abspath( os.path.join(BASE_DIR, '{{ cookiecutter.app_slug }}', 'media') ) # Copy media files to ./{{ cookiecutter.app_slug }}/media MEDIA_URL = '/media/' # Static finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Regex expresions to exclude from logging at middleware REQUEST_LOGGING_EXCLUDE = { '': (), 'admin': (r'.*', ), 'health_check': (r'.*', ) } DEFAULT_RESPONSE_HEADERS = { 'Link': ('<https://docs.sequoia.piksel.com/concepts/api/spec.html>;rel="profile"', ), 'Cache-Control': ('no-cache', ), }
class Base(Configuration): u"""Configuração comum para todos os ambientes.""" DEBUG = values.BooleanValue(False) ADMINS = values.SingleNestedTupleValue( (('Sergio Garcia', '*****@*****.**'), )) MANAGERS = values.SingleNestedTupleValue( (('Sergio Garcia', '*****@*****.**'), )) DATABASES = values.DatabaseURLValue( 'postgres://postgres@localhost/postgres') CACHES = values.CacheURLValue('locmem://') EMAIL = values.EmailURLValue('console://') EMAIL_SUBJECT_PREFIX = values.Value('[%s] ' % SITE_NAME) TIME_ZONE = values.Value('America/Sao_Paulo') LANGUAGE_CODE = values.Value('pt-br') USE_I18N = values.BooleanValue(True) USE_L10N = values.BooleanValue(True) USE_TZ = values.BooleanValue(True) MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) MEDIA_URL = values.Value('/media/') STATIC_ROOT = values.PathValue(normpath(join(SITE_ROOT, 'static'))) STATIC_URL = values.Value('/static/') STATICFILES_DIRS = (normpath(join(SITE_ROOT, 'bower_components')), ) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] SECRET_KEY = values.SecretValue() ALLOWED_HOSTS = [] FIXTURE_DIRS = (normpath(join(SITE_ROOT, 'fixtures')), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [normpath(join(SITE_ROOT, 'templates'))], 'APP_DIRS': True, 'OPTIONS': { '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.contrib.messages.context_processors.messages', 'django.core.context_processors.request', ], 'debug': DEBUG }, }, ] MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'gestaolivre.apps.utils.middleware.GlobalRequestMiddleware', ] ROOT_URLCONF = '%s.urls' % SITE_NAME DJANGO_APPS = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'django.contrib.humanize', 'django.contrib.admin', 'mptt', 'django_mptt_admin', 'widget_tweaks', 'brazil_fields') LOCAL_APPS = ( 'gestaolivre.apps.cadastro', 'gestaolivre.apps.utils', ) INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS LOGIN_REDIRECT_URL = '/' 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', }, ] WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME TEST_RUNNER = 'django.test.runner.DiscoverRunner' MIGRATION_MODULES = {} INSTALLED_APPS += ( 'rest_framework', 'rest_framework_jwt', 'corsheaders', ) REST_FRAMEWORK = values.DictValue({ 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), }) CORS_ORIGIN_ALLOW_ALL = values.Value(True) CORS_ALLOW_CREDENTIALS = values.Value(True) INSTALLED_APPS += ('compressor', ) STATICFILES_FINDERS += ('compressor.finders.CompressorFinder', ) COMPRESS_PRECOMPILERS = ( ('text/coffeescript', 'coffee --compile --stdio'), ('text/less', 'lessc --source-map-map-inline {infile} {outfile}'), ('text/x-sass', 'sass {infile} {outfile}'), ('text/x-scss', 'sass --scss {infile} {outfile}'), ) JWT_AUTH = values.DictValue({ 'JWT_EXPIRATION_DELTA': datetime.timedelta(minutes=5), 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_ALLOW_REFRESH': True, 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_RESPONSE_PAYLOAD_HANDLER': jwt_response_payload_handler }) @classmethod def pre_setup(cls): u"""Executado antes da Configuração.""" super(Base, cls).pre_setup() @classmethod def setup(cls): u"""Executado depois da Configuração.""" super(Base, cls).setup() logging.info('Configurações comuns carregadas: %s', cls) @classmethod def post_setup(cls): u"""Executado depois da Configuração.""" super(Base, cls).post_setup() logging.debug("done setting up! \o/")
class Common(object): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = values.SecretValue() DEBUG = values.BooleanValue(True) ALLOWED_HOSTS = ['*'] 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', 'project', ] 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 = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': False, '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', ], 'loaders': ( 'hamlpy.template.loaders.HamlPyFilesystemLoader', 'hamlpy.template.loaders.HamlPyAppDirectoriesLoader', ), }, }, ] WSGI_APPLICATION = 'project.wsgi.application' DATABASES = values.DatabaseURLValue('sqlite:///{}'.format( os.path.join(BASE_DIR, 'database.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_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend' SENDGRID_API_KEY = values.Value(None, environ_prefix=None) SERVER_EMAIL = values.Value(None) # DJANGO_ADMINS=Bob,[email protected];Dave,[email protected] ADMINS = values.SingleNestedTupleValue([])