""" Django settings for config project. Generated by 'django-admin startproject' using Django 6.1. For more information on this file, see https://docs.djangoproject.com/en/6.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/6.1/ref/settings/ """ import json import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Load environment variables from .env file if it exists env_path = BASE_DIR / '.env' if env_path.exists(): with open(env_path) as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: k, v = line.split('=', 1) os.environ.setdefault(k.strip(), v.strip()) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-w97g8j2h1=r%4$i1qc4xu%#c3)iw^4@#0-^sr3h&*okow^ax!@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'api', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] # CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:5173', # Vite local dev 'http://127.0.0.1:5173', # Vite local dev 'https://d1zlxfmkt834bg.cloudfront.net', # CloudFront betasupplier site ] CORS_ALLOW_CREDENTIALS = True 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' # --------------------------------------------------------------------------- # Database Configuration # --------------------------------------------------------------------------- import os db_credentials = { 'ENGINE': 'django.db.backends.postgresql', 'USER': os.environ.get('DB_USER', 'vignesh'), 'PASSWORD': os.environ.get('DB_PASSWORD', 'vtechnosoft@123A'), 'HOST': os.environ.get('DB_HOST', '16.113.106.152'), 'PORT': os.environ.get('DB_PORT', '5432'), } env_name = os.environ.get('ENVIRONMENT', 'prod') db_suffix = f'_{env_name}' DATABASES = { 'default': { 'NAME': f'sellerprofile{db_suffix}', **db_credentials }, 'customerprofile': { 'NAME': f'customerprofile{db_suffix}', **db_credentials }, 'productprofile': { 'NAME': f'productprofile{db_suffix}', **db_credentials } } DATABASE_ROUTERS = ['config.db_router.DatabaseRouter'] # Default primary key field type # https://docs.djangoproject.com/en/6.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Password validation # https://docs.djangoproject.com/en/6.1/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/6.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/6.1/howto/static-files/ STATIC_URL = 'static/' # Email # https://docs.djangoproject.com/en/6.1/topics/email/#topic-email-configuration MAILERS = { 'default': { 'BACKEND': 'django.core.mail.backends.console.EmailBackend', }, } from datetime import timedelta REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.DummyAuthentication' if DEBUG else 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20, } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': timedelta(days=7), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', } # --------------------------------------------------------------------------- # Logging # Writes to /app/logs/ (volume-mounted on host) and to stdout. # Log files are also picked up by the CloudWatch Agent on the EC2 host. # --------------------------------------------------------------------------- LOGS_DIR = BASE_DIR / 'logs' os.makedirs(LOGS_DIR, exist_ok=True) LOGGING = { 'version': 1, 'disable_existing_loggers': False, # ----- Formatters ----- 'formatters': { 'verbose': { 'format': '[{asctime}] {levelname} {name} {process:d} {thread:d} | {message}', 'style': '{', 'datefmt': '%Y-%m-%d %H:%M:%S', }, 'simple': { 'format': '[{asctime}] {levelname} | {message}', 'style': '{', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, # ----- Filters ----- 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, # ----- Handlers ----- 'handlers': { # Writes every log line to stdout (visible via `docker logs`) 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', }, # Rotating file for all application logs (INFO+) 'app_file': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': str(LOGS_DIR / 'app.log'), 'maxBytes': 10 * 1024 * 1024, # 10 MB 'backupCount': 7, 'formatter': 'verbose', 'encoding': 'utf-8', }, # Dedicated rotating file for ERROR+ only 'error_file': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': str(LOGS_DIR / 'error.log'), 'maxBytes': 10 * 1024 * 1024, # 10 MB 'backupCount': 7, 'formatter': 'verbose', 'level': 'ERROR', 'encoding': 'utf-8', }, # Django request/response log 'request_file': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': str(LOGS_DIR / 'requests.log'), 'maxBytes': 10 * 1024 * 1024, # 10 MB 'backupCount': 7, 'formatter': 'simple', 'encoding': 'utf-8', }, }, # ----- Loggers ----- 'loggers': { # Root logger – catches everything not matched below '': { 'handlers': ['console', 'app_file', 'error_file'], 'level': 'INFO', 'propagate': False, }, # Your application code 'api': { 'handlers': ['console', 'app_file', 'error_file'], 'level': 'DEBUG', 'propagate': False, }, # Django HTTP request log (4xx / 5xx) 'django.request': { 'handlers': ['console', 'request_file', 'error_file'], 'level': 'INFO', 'propagate': False, }, # Suppress noisy security middleware warnings in prod 'django.security': { 'handlers': ['error_file'], 'level': 'ERROR', 'propagate': False, }, }, } # Media files (uploads) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # CloudFront Domain Configuration import boto3 AWS_CLOUDFRONT_DOMAIN = os.environ.get('AWS_CLOUDFRONT_DOMAIN', '') USE_S3 = os.environ.get('USE_S3', 'False').lower() == 'true' AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', 'betasupplierdocumentstorage')