intent/config/settings/base.py

206 lines
7.4 KiB
Python
Raw Normal View History

import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Holds the SQLite database. A Fly volume in production, a Docker volume in compose.
DATA_DIR = Path(os.environ.get("INTENT_DATA_DIR", BASE_DIR / "data"))
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "")
DEBUG = False
ALLOWED_HOSTS = []
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_otp",
"django_otp.plugins.otp_totp",
"allauth",
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.discord",
"allauth.socialaccount.providers.github",
# Forgejo instances are OpenID Connect apps, one SocialApp per instance, added in admin.
"allauth.socialaccount.providers.openid_connect",
"intent.core",
"intent.accounts",
"intent.orgs",
"intent.projects",
"intent.features",
"intent.files",
"intent.implementations",
"intent.issues",
"intent.comments",
]
MIDDLEWARE = [
# First, so health checks skip host validation and the HTTPS redirect.
"intent.core.middleware.HealthCheckMiddleware",
"django.middleware.security.SecurityMiddleware",
"intent.core.middleware.SecurityHeadersMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django_otp.middleware.OTPMiddleware",
"allauth.account.middleware.AccountMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "config.urls"
WSGI_APPLICATION = "config.wsgi.application"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": DATA_DIR / "db.sqlite3",
"OPTIONS": {
# Take the write lock at BEGIN so concurrent writers wait instead of failing.
"transaction_mode": "IMMEDIATE",
"timeout": 5,
# WAL is required by Litestream.
"init_command": "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;",
},
}
}
# Uploads up to 25 MB (see intent.files). Larger bodies spill to a temp file, not memory.
FILE_UPLOAD_MAX_MEMORY_SIZE = 2_621_440
# Rate limits (allauth's and ours) live here, so the cache must be shared by every worker
# and survive restarts. The database is the only shared store on a one-machine deploy.
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.db.DatabaseCache",
"LOCATION": "cache",
}
}
AUTH_USER_MODEL = "accounts.User"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
AUTHENTICATION_BACKENDS = [
# Password login, used only by sysadmins at /admin/.
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
]
# The admin asks for a code from an authenticator app as well as the password.
# Add a device with `manage.py add_admin_totp <username>`. Off only in local development.
ADMIN_REQUIRE_OTP = True
OTP_TOTP_ISSUER = "Intent admin"
LOGIN_URL = "account_login"
LOGIN_REDIRECT_URL = "home"
# Regular users never have a password: they sign in with an emailed code or a linked provider.
ACCOUNT_ADAPTER = "intent.accounts.adapter.AccountAdapter"
ACCOUNT_LOGIN_METHODS = {"email"}
ACCOUNT_SIGNUP_FIELDS = ["email*", "username*"]
ACCOUNT_USERNAME_VALIDATORS = "intent.accounts.validators.username_validators"
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
ACCOUNT_EMAIL_VERIFICATION_BY_CODE_SUPPORTS_RESEND = True
ACCOUNT_LOGIN_BY_CODE_ENABLED = True
ACCOUNT_LOGIN_BY_CODE_SUPPORTS_RESEND = True
ACCOUNT_LOGIN_BY_CODE_TIMEOUT = 600
ACCOUNT_LOGOUT_ON_GET = False
# Adding an email address adds a way to sign in, so ask for a fresh code first, and tell
# the existing addresses about it.
ACCOUNT_REAUTHENTICATION_REQUIRED = True
ACCOUNT_EMAIL_NOTIFICATIONS = True
SOCIALACCOUNT_PROVIDERS = {
"github": {"SCOPE": ["read:user", "user:email"]},
}
# Provider is TBD (see concept.md); console output until then. Any Anymail provider works
# without code changes: set EMAIL_BACKEND to its backend and pass its settings as ANYMAIL_*
# variables, e.g. EMAIL_BACKEND=anymail.backends.postmark.EmailBackend with
# ANYMAIL_POSTMARK_SERVER_TOKEN=... (see docs/operations.md).
EMAIL_BACKEND = os.environ.get("EMAIL_BACKEND", "django.core.mail.backends.console.EmailBackend")
ANYMAIL = {
key.removeprefix("ANYMAIL_"): value
for key, value in os.environ.items()
if key.startswith("ANYMAIL_")
}
DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", "Intent <intent@localhost>")
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_TZ = True
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / "static"]
# Uploaded files go to S3-compatible storage (Tigris) when a bucket is configured,
# otherwise to the local filesystem. `fly storage create` sets these variable names.
if os.environ.get("BUCKET_NAME"):
_default_storage = {
"BACKEND": "storages.backends.s3.S3Storage",
"OPTIONS": {
"bucket_name": os.environ["BUCKET_NAME"],
"endpoint_url": os.environ.get("AWS_ENDPOINT_URL_S3"),
"region_name": os.environ.get("AWS_REGION", "auto"),
# Bucket in the hostname, matching CSP_BUCKET_ORIGIN below.
"addressing_style": "virtual",
"default_acl": None,
"querystring_auth": True,
"querystring_expire": 300,
"file_overwrite": False,
},
}
else:
_default_storage = {
"BACKEND": "django.core.files.storage.FileSystemStorage",
"OPTIONS": {"location": DATA_DIR / "media"},
}
# The bucket's origin, so pages may show images and frame prototypes from signed URLs.
# Tigris signed URLs are virtual-hosted: https://<bucket>.fly.storage.tigris.dev.
CSP_BUCKET_ORIGIN = os.environ.get("CSP_BUCKET_ORIGIN", "")
if not CSP_BUCKET_ORIGIN and os.environ.get("BUCKET_NAME"):
_endpoint = os.environ.get("AWS_ENDPOINT_URL_S3", "https://fly.storage.tigris.dev")
_scheme, _, _host = _endpoint.partition("://")
CSP_BUCKET_ORIGIN = f"{_scheme}://{os.environ['BUCKET_NAME']}.{_host.rstrip('/')}"
STORAGES = {
"default": _default_storage,
"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"},
}
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {"console": {"class": "logging.StreamHandler"}},
"root": {"handlers": ["console"], "level": "INFO"},
}