316 lines
11 KiB
Python
316 lines
11 KiB
Python
import os
|
|
import sys
|
|
from datetime import timedelta
|
|
from pathlib import Path
|
|
|
|
import dj_database_url
|
|
from django.core.exceptions import ImproperlyConfigured
|
|
from dotenv import load_dotenv
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
|
|
load_dotenv(BASE_DIR / ".env")
|
|
|
|
JWT_PRIVATE_KEY_PATH = BASE_DIR / "keys" / "rsa_private.pem"
|
|
JWT_PUBLIC_KEY_PATH = BASE_DIR / "keys" / "rsa_public.pem"
|
|
JWT_PRIVATE_KEY = ""
|
|
JWT_PUBLIC_KEY = ""
|
|
if JWT_PRIVATE_KEY_PATH.exists():
|
|
JWT_PRIVATE_KEY = JWT_PRIVATE_KEY_PATH.read_text()
|
|
if JWT_PUBLIC_KEY_PATH.exists():
|
|
JWT_PUBLIC_KEY = JWT_PUBLIC_KEY_PATH.read_text()
|
|
|
|
|
|
def env(name, default=None):
|
|
return os.getenv(name, default)
|
|
|
|
|
|
def env_bool(name, default=False):
|
|
return os.getenv(name, str(default)).lower() in ("1", "true", "yes", "on")
|
|
|
|
|
|
def env_list(name, default=""):
|
|
return [item.strip() for item in env(name, default).split(",") if item.strip()]
|
|
|
|
|
|
DJANGO_ENV = env("DJANGO_ENV", "development")
|
|
DEBUG = env_bool("DJANGO_DEBUG", DJANGO_ENV == "development")
|
|
|
|
SECRET_KEY = env("DJANGO_SECRET_KEY", "dev-only-insecure-secret-key")
|
|
if DJANGO_ENV == "production" and SECRET_KEY == "dev-only-insecure-secret-key":
|
|
raise ImproperlyConfigured("DJANGO_SECRET_KEY must be set in production.")
|
|
|
|
JWT_SIGNING_KEY = env("JWT_SIGNING_KEY", "dev-only-insecure-secret-key-32b-min")
|
|
if (
|
|
DJANGO_ENV == "production"
|
|
and JWT_SIGNING_KEY == "dev-only-insecure-secret-key-32b-min"
|
|
):
|
|
raise ImproperlyConfigured("JWT_SIGNING_KEY must be set in production.")
|
|
|
|
ALLOWED_HOSTS = env_list(
|
|
"DJANGO_ALLOWED_HOSTS",
|
|
"localhost,127.0.0.1,0.0.0.0,backend",
|
|
)
|
|
INTERNAL_IPS = ["127.0.0.1", "0.0.0.0"]
|
|
|
|
INSTALLED_APPS = [
|
|
"django.contrib.admin",
|
|
"django.contrib.auth",
|
|
"django.contrib.contenttypes",
|
|
"django.contrib.sessions",
|
|
"django.contrib.messages",
|
|
"django.contrib.staticfiles",
|
|
"rest_framework",
|
|
"drf_spectacular",
|
|
"django_filters",
|
|
"corsheaders",
|
|
"apps.common",
|
|
"apps.identity",
|
|
"apps.oauth",
|
|
"apps.organization",
|
|
"apps.membership",
|
|
"apps.session",
|
|
"apps.security",
|
|
"apps.application",
|
|
"apps.authentication",
|
|
"apps.product",
|
|
"apps.profile",
|
|
"apps.access",
|
|
"apps.token_blacklist",
|
|
"apps.verification",
|
|
"apps.sso",
|
|
"apps.passport",
|
|
"apps.mailbox",
|
|
"apps.messaging",
|
|
"apps.sms",
|
|
]
|
|
|
|
MIDDLEWARE = [
|
|
"corsheaders.middleware.CorsMiddleware",
|
|
"django.middleware.security.SecurityMiddleware",
|
|
"whitenoise.middleware.WhiteNoiseMiddleware",
|
|
"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",
|
|
]
|
|
|
|
ROOT_URLCONF = "config.urls"
|
|
|
|
TEMPLATES = [
|
|
{
|
|
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
|
"DIRS": [],
|
|
"APP_DIRS": True,
|
|
"OPTIONS": {
|
|
"context_processors": [
|
|
"django.template.context_processors.request",
|
|
"django.contrib.auth.context_processors.auth",
|
|
"django.contrib.messages.context_processors.messages",
|
|
],
|
|
},
|
|
},
|
|
]
|
|
|
|
WSGI_APPLICATION = "config.wsgi.application"
|
|
ASGI_APPLICATION = "config.asgi.application"
|
|
|
|
DATABASES = {
|
|
"default": dj_database_url.config(
|
|
default=env(
|
|
"DATABASE_URL",
|
|
"postgres://identity:identity@localhost:5432/identity",
|
|
),
|
|
conn_max_age=600,
|
|
)
|
|
}
|
|
|
|
AUTH_USER_MODEL = "identity.User"
|
|
|
|
AUTH_PASSWORD_VALIDATORS = [
|
|
{
|
|
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
|
|
},
|
|
{
|
|
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
|
|
"OPTIONS": {"min_length": 10},
|
|
},
|
|
{
|
|
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
|
|
},
|
|
{
|
|
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
|
|
},
|
|
]
|
|
|
|
LANGUAGE_CODE = "en"
|
|
TIME_ZONE = "UTC"
|
|
USE_I18N = True
|
|
USE_TZ = True
|
|
LOCALE_PATHS = [BASE_DIR / "locale"]
|
|
|
|
STATIC_URL = "static/"
|
|
STATIC_ROOT = BASE_DIR / "staticfiles"
|
|
|
|
# Uploads. Without these a FileField's `upload_to` resolves against the
|
|
# process's working directory, so mailbox attachments would land wherever the
|
|
# server happened to be started instead of in one predictable place.
|
|
# `or` rather than a default: an empty value in .env must not win.
|
|
MEDIA_URL = "media/"
|
|
MEDIA_ROOT = env("MEDIA_ROOT") or str(BASE_DIR / "media")
|
|
|
|
STORAGES = {
|
|
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
|
|
"staticfiles": {
|
|
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"
|
|
},
|
|
}
|
|
|
|
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
|
|
|
REDIS_URL = env("REDIS_URL")
|
|
if REDIS_URL:
|
|
CACHES = {
|
|
"default": {
|
|
"BACKEND": "django_redis.cache.RedisCache",
|
|
"LOCATION": REDIS_URL,
|
|
"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"},
|
|
}
|
|
}
|
|
else:
|
|
CACHES = {
|
|
"default": {
|
|
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
|
|
"LOCATION": "identity-platform",
|
|
}
|
|
}
|
|
|
|
CORS_ALLOWED_ORIGINS = env_list(
|
|
"CORS_ALLOWED_ORIGINS",
|
|
"http://localhost:8000,http://127.0.0.1:8000",
|
|
)
|
|
CORS_ALLOW_CREDENTIALS = True
|
|
CSRF_TRUSTED_ORIGINS = env_list("CSRF_TRUSTED_ORIGINS", "http://localhost:8000")
|
|
|
|
# Central SSO session cookie domain. For Google-style cross-subdomain SSO the
|
|
# IdP session cookie must be readable by every hamsoo subdomain, so in
|
|
# production this is set to ".hamsoo.me". In development (localhost) it must be
|
|
# left empty so the cookie is host-only.
|
|
SSO_COOKIE_DOMAIN = env("SSO_COOKIE_DOMAIN", "")
|
|
if SSO_COOKIE_DOMAIN:
|
|
SESSION_COOKIE_DOMAIN = SSO_COOKIE_DOMAIN
|
|
CSRF_COOKIE_DOMAIN = SSO_COOKIE_DOMAIN
|
|
SESSION_COOKIE_NAME = env("SESSION_COOKIE_NAME", "hamsoo_sso_session")
|
|
CSRF_COOKIE_NAME = env("CSRF_COOKIE_NAME", "hamsoo_sso_csrftoken")
|
|
SESSION_COOKIE_SECURE = True
|
|
CSRF_COOKIE_SECURE = True
|
|
SESSION_COOKIE_SAMESITE = "Lax"
|
|
CSRF_COOKIE_SAMESITE = "Lax"
|
|
|
|
# Hosts allowed as post-login/post-logout redirect targets, beyond the IdP itself.
|
|
# ALLOWED_HOSTS cannot serve this purpose: it only validates the inbound Host
|
|
# header, so a product subdomain has to be trusted explicitly or every sign-in
|
|
# lands on the fallback and looks like a broken login button.
|
|
SSO_TRUSTED_REDIRECT_HOSTS = env_list(
|
|
"SSO_TRUSTED_REDIRECT_HOSTS",
|
|
"localhost,127.0.0.1",
|
|
)
|
|
|
|
# ── Outbound email ───────────────────────────────────────────────────────────
|
|
# From here on the platform owns identity, so "who are you" and "reset your
|
|
# password" both leave through this address and users must recognise it.
|
|
DEFAULT_FROM_EMAIL = env("EMAIL_FROM_ADDRESS", "no-reply@localhost")
|
|
EMAIL_RESET_PATH = env("EMAIL_RESET_PATH", "account/reset-password")
|
|
|
|
# ── Outbound SMS ─────────────────────────────────────────────────────────────
|
|
# `console` logs the message instead of sending it, so sign-in is developable
|
|
# without provider credentials. Production refuses to boot on an unset provider.
|
|
SMS_PROVIDER = env("SMS_PROVIDER", "console")
|
|
SMS_TIMEOUT = float(env("SMS_TIMEOUT", "10"))
|
|
KAVENEGAR_API_KEY = env("KAVENEGAR_API_KEY", "")
|
|
KAVENEGAR_SENDER = env("KAVENEGAR_SENDER", "")
|
|
|
|
if DJANGO_ENV == "production" and SMS_PROVIDER == "console":
|
|
raise ImproperlyConfigured(
|
|
"SMS_PROVIDER must name a real provider in production; "
|
|
"'console' would print every sign-in code to the logs instead of "
|
|
"delivering it."
|
|
)
|
|
|
|
# ── Personal mailbox ─────────────────────────────────────────────────────────
|
|
MAIL_DOMAIN = env("MAIL_DOMAIN", "jobid.ir")
|
|
MAIL_INBOUND_SECRET = env("MAIL_INBOUND_SECRET", "")
|
|
MAIL_DAILY_SEND_LIMIT = int(env("MAIL_DAILY_SEND_LIMIT", "200"))
|
|
MAIL_MAX_ATTACH_MB = int(env("MAIL_MAX_ATTACH_MB", "10"))
|
|
|
|
REST_FRAMEWORK = {
|
|
"DEFAULT_AUTHENTICATION_CLASSES": [
|
|
"apps.authentication.auth.JwtBlacklistAuthentication",
|
|
"rest_framework.authentication.SessionAuthentication",
|
|
],
|
|
"DEFAULT_PERMISSION_CLASSES": [
|
|
"rest_framework.permissions.IsAuthenticated",
|
|
],
|
|
"DEFAULT_FILTER_BACKENDS": [
|
|
"django_filters.rest_framework.DjangoFilterBackend",
|
|
"rest_framework.filters.SearchFilter",
|
|
"rest_framework.filters.OrderingFilter",
|
|
],
|
|
"DEFAULT_PAGINATION_CLASS": "apps.common.pagination.DefaultPagination",
|
|
"PAGE_SIZE": 20,
|
|
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
|
|
"EXCEPTION_HANDLER": "apps.common.exceptions.api_exception_handler",
|
|
}
|
|
|
|
# OIDC issuer used in the `iss` claim of id_tokens. In production this must
|
|
# match the public base URL products use to reach the platform (and the value
|
|
# advertised in /.well-known/openid-configuration).
|
|
OIDC_ISSUER = env("OIDC_ISSUER", "http://localhost:8000")
|
|
|
|
SIMPLE_JWT = {
|
|
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
|
|
"REFRESH_TOKEN_LIFETIME": timedelta(days=30),
|
|
"AUTH_HEADER_TYPES": ("Bearer",),
|
|
"USER_ID_CLAIM": "user_id",
|
|
"UPDATE_LAST_LOGIN": False,
|
|
"ALGORITHM": "RS256",
|
|
"SIGNING_KEY": JWT_PRIVATE_KEY or JWT_SIGNING_KEY,
|
|
"VERIFYING_KEY": JWT_PUBLIC_KEY,
|
|
"TOKEN_TYPE_CLAIM": "typ",
|
|
}
|
|
|
|
SPECTACULAR_SETTINGS = {
|
|
"TITLE": "Identity Platform API",
|
|
"DESCRIPTION": (
|
|
"Central identity, authentication and authorization infrastructure "
|
|
"for the ecosystem. One Identity. Every Product."
|
|
),
|
|
"VERSION": "1.0.0",
|
|
"SERVE_INCLUDE_SCHEMA": False,
|
|
"SERVE_PERMISSIONS": ["rest_framework.permissions.AllowAny"],
|
|
"COMPONENT_SPLIT_REQUEST": True,
|
|
}
|
|
|
|
# PBKDF2 is deliberately expensive — well over a second per hash. The test suite
|
|
# mints accounts purely as setup, with no real credential being protected, so
|
|
# paying that cost on every one turns a suite that should run in seconds into
|
|
# one that takes ten minutes.
|
|
#
|
|
# MD5 is prepended, not substituted: the list still contains every default
|
|
# hasher, so a hash copied verbatim out of a legacy dump — which is the whole
|
|
# point of the migration path — is still identified and verified correctly. Only
|
|
# new hashes made while testing are cheapened, and nothing that reaches
|
|
# production sees this, because it is gated on Django's own test runner.
|
|
if "test" in sys.argv:
|
|
PASSWORD_HASHERS = [
|
|
"django.contrib.auth.hashers.MD5PasswordHasher",
|
|
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
|
|
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
|
|
"django.contrib.auth.hashers.Argon2PasswordHasher",
|
|
"django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
|
|
"django.contrib.auth.hashers.ScryptPasswordHasher",
|
|
]
|