gh_UserManager/apps/api/config/settings.py
bermooda-company 54d5891edf user
2026-08-23 23:59:14 +03:30

248 lines
7.5 KiB
Python

import os
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,frontend",
)
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",
]
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"
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:3000,http://127.0.0.1:3000",
)
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = env_list("CSRF_TRUSTED_ORIGINS", "http://localhost:3000")
# 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"
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,
}