cmsmanage/cmsmanage/settings.py
Adam Goldsmith 8d3f548e8b
All checks were successful
Ruff / ruff (push) Successful in 39s
Test / test (push) Successful in 3m48s
Add django-postgres-metrics
2024-08-30 11:49:21 -04:00

382 lines
12 KiB
Python

import os
import sys
from pathlib import Path
from django.core import validators
from configurations import Configuration, values
BASE_DIR = Path(__file__).resolve().parent.parent
class Base(Configuration):
@classmethod
def pre_setup(cls):
super().pre_setup()
# load systemd credentials, as per https://systemd.io/CREDENTIALS/
credentials_directory = os.getenv("CREDENTIALS_DIRECTORY")
if credentials_directory is not None:
for credential in Path(credentials_directory).iterdir():
if credential.name.endswith("_path"):
os.environ.setdefault(
credential.name.removesuffix("_path"), str(credential.resolve())
)
if credential.name.isupper():
os.environ.setdefault(credential.name, credential.read_text())
@classmethod
def setup(cls):
super().setup()
# TODO: this is a nasty hack, since the connection
# pool doesn't seem to work well with django-q2
if "qcluster" not in sys.argv:
cls.DATABASES["default"]["OPTIONS"] = {"pool": True}
INSTALLED_APPS = [
"dal",
"dal_select2",
"postgres_metrics.apps.PostgresMetrics",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_admin_logs",
"django_object_actions",
"widget_tweaks",
# "markdownx",
# "recurrence",
"rest_framework",
"rest_framework.authtoken",
"django_vite",
"django_q",
"django_nh3",
"django_tables2",
"django_filters",
"django_db_views",
"django_sendfile",
"django_bootstrap5",
"simple_history",
# "tasks.apps.TasksConfig",
"rentals.apps.RentalsConfig",
"membershipworks.apps.MembershipworksConfig",
"paperwork.apps.PaperworkConfig",
"doorcontrol.apps.DoorControlConfig",
"dashboard.apps.DashboardConfig",
"reservations.apps.ReservationsConfig",
]
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 = "cmsmanage.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [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",
],
},
},
]
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
},
"database": {
"BACKEND": "django.core.cache.backends.db.DatabaseCache",
"LOCATION": "django_cache",
},
}
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
WSGI_APPLICATION = "cmsmanage.wsgi.application"
# Default URL to redirect to after authentication
LOGIN_REDIRECT_URL = "/"
LOGIN_URL = "/auth/login/"
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "America/New_York"
USE_I18N = False
USE_L10N = True
USE_TZ = True
USE_DEPRECATED_PYTZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = "/static/"
STATICFILES_DIRS = [
BASE_DIR / "static",
BASE_DIR / "vite-dist",
]
LOGGING = values.DictValue(
{
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"my_console": {
"class": "logging.StreamHandler",
},
},
"loggers": {
"": {
"handlers": ["my_console"],
"level": "WARNING",
},
},
}
)
MEDIA_ROOT = "media"
MEDIA_URL = "media/"
SENDFILE_ROOT = str(BASE_DIR / "media" / "protected")
SERVER_EMAIL = "cmsmanage <cmsmanage@claremontmakerspace.org>"
EMAIL_SUBJECT_PREFIX = "[cmsmanage] "
DEFAULT_FROM_EMAIL = SERVER_EMAIL
# Django Rest Framework
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions
"DEFAULT_PERMISSION_CLASSES": [
"cmsmanage.drf_permissions.DjangoModelPermissionsWithView"
],
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.TokenAuthentication",
],
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning",
}
# Django Q
Q_CLUSTER = {
"name": "cmsmanage",
"orm": "default",
"retry": 60 * 6,
"timeout": 60 * 5,
"catch_up": False,
"error_reporter": {"admin_email": {}},
"ack_failures": True,
"max_attempts": 1,
"cache": "database",
"ALT_CLUSTERS": {
"internal": {
"retry": 60 * 60,
"timeout": 60 * 59,
},
},
}
# Django-Tables2
DJANGO_TABLES2_TEMPLATE = "django_tables2/bootstrap5-responsive.html"
DJANGO_TABLES2_TABLE_ATTRS = {"class": "table mx-auto w-auto"}
# Django Vite
@property
def DJANGO_VITE(self):
return {
"default": {
"dev_mode": values.BooleanValue(False, environ_name="VITE_DEV_MODE"),
"dev_server_port": values.IntegerValue(
5173, environ_name="VITE_DEV_SERVER_PORT"
),
"manifest_path": (
BASE_DIR / "vite-dist" / "manifest.json" if self.DEBUG else None
),
}
}
SECRET_KEY = values.SecretValue(environ_required=True)
# CMSManage specific stuff
WIKI_URL = values.URLValue("https://wiki.claremontmakerspace.org")
# ID of flag for Members folder in MembershipWorks
MW_MEMBERS_FOLDER_ID = "5771675edcdf126302a2f6b9"
class NonCIBase(Base):
"""required for all but CI"""
CSRF_TRUSTED_ORIGINS = values.ListValue([])
DATABASES = values.DatabaseURLValue(environ_required=True)
EMAIL = values.EmailURLValue(environ_required=True)
# TODO: should validate emails
ADMINS = values.SingleNestedTupleValue(environ_required=True)
MEMBERSHIPWORKS_USERNAME = values.EmailValue(
environ_required=True, environ_prefix=None
)
MEMBERSHIPWORKS_PASSWORD = values.SecretValue(
environ_required=True, environ_prefix=None
)
GOOGLE_SERVICE_ACCOUNT_FILE = values.PathValue(environ_prefix=None)
HID_DOOR_USERNAME = values.Value(environ_required=True, environ_prefix=None)
HID_DOOR_PASSWORD = values.SecretValue(environ_prefix=None)
# TODO: should validate emails (but EmailValidator doesn't handle name parts)
INVOICE_HANDLERS = values.ListValue(
environ_required=True, environ_prefix="CMSMANAGE"
)
# arguments for https://udm-rest-client.readthedocs.io/en/latest/udm_rest_client.html#udm_rest_client.udm.UDM
UCS = values.DictValue(environ_required=True, environ_prefix="CMSMANAGE")
class LDAPURLValue(values.ValidationMixin, values.Value):
message = "Cannot interpret LDAP URL value {0!r}"
validator = validators.URLValidator(schemes=["ldap", "ldaps"])
class Prod(NonCIBase):
import ldap
from django_auth_ldap.config import LDAPGroupQuery, LDAPSearch, PosixGroupType
DEBUG = False
# LDAP Authentication
# https://django-auth-ldap.readthedocs.io/en/latest/
AUTHENTICATION_BACKENDS = [
"django_auth_ldap.backend.LDAPBackend",
"django.contrib.auth.backends.ModelBackend",
]
AUTH_LDAP_USER_SEARCH = LDAPSearch(
"cn=users,dc=sawtooth,dc=claremontmakerspace,dc=org",
ldap.SCOPE_SUBTREE,
"(uid=%(user)s)",
)
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail",
}
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_staff": (
LDAPGroupQuery(
"cn=MW_CMS Staff,cn=groups,dc=sawtooth,dc=claremontmakerspace,dc=org"
)
| LDAPGroupQuery(
"cn=MW_Database Admin,cn=groups,dc=sawtooth,dc=claremontmakerspace,dc=org"
)
| LDAPGroupQuery(
"cn=MW_Database Access,cn=groups,dc=sawtooth,dc=claremontmakerspace,dc=org"
)
)
}
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
"cn=groups,dc=sawtooth,dc=claremontmakerspace,dc=org",
ldap.SCOPE_SUBTREE,
"(objectClass=posixGroup)",
)
AUTH_LDAP_GROUP_TYPE = PosixGroupType()
AUTH_LDAP_MIRROR_GROUPS = True
SENDFILE_BACKEND = "django_sendfile.backends.nginx"
SENDFILE_URL = "/media/protected"
AUTH_LDAP_SERVER_URI = LDAPURLValue(None, environ_required=True)
AUTH_LDAP_BIND_DN = values.Value(environ_required=True)
AUTH_LDAP_BIND_PASSWORD = values.SecretValue()
ALLOWED_HOSTS = values.ListValue([], environ_required=True)
STATIC_ROOT = values.PathValue(environ_required=True)
def configure_hypothesis_profiles():
from hypothesis import HealthCheck, Verbosity, settings
settings.register_profile("ci", suppress_health_check=(HealthCheck.too_slow,))
settings.register_profile("dev", max_examples=20)
settings.register_profile("debug", max_examples=10, verbosity=Verbosity.verbose)
class Dev(NonCIBase):
@classmethod
def post_setup(cls):
import os
from hypothesis import settings
super().post_setup()
configure_hypothesis_profiles()
settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", "dev"))
DOTENV = BASE_DIR / "settings.dev.env"
DEBUG = values.BooleanValue(True)
INTERNAL_IPS = ["127.0.0.1"]
INSTALLED_APPS = NonCIBase.INSTALLED_APPS + ["django_extensions"]
# bit of a hack to disable debug toolbar when running tests
if DEBUG and "test" not in sys.argv:
INSTALLED_APPS += ["debug_toolbar"]
MIDDLEWARE = NonCIBase.MIDDLEWARE + [
"debug_toolbar.middleware.DebugToolbarMiddleware",
]
EMAIL = values.EmailURLValue("smtp://localhost:1025") # for local `mailpit`
SENDFILE_BACKEND = "django_sendfile.backends.development"
class CI(Base):
@classmethod
def post_setup(cls):
from hypothesis import settings
super().post_setup()
configure_hypothesis_profiles()
settings.load_profile("ci")
@property
def DJANGO_VITE(self):
d = super().DJANGO_VITE
d["default"]["manifest_path"] = BASE_DIR / "vite-dist" / "manifest.json"
return d
SECRET_KEY = "aed7jee2kai1we9eithae0gaegh9ohthoh4phahk5bau4Ahxaijo3aicheex3qua"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"HOST": "postgres",
"NAME": "cms",
"USER": "postgres",
"PASSWORD": "whatever",
}
}