seller_central_backend/config/settings.py
2026-09-05 16:04:01 +05:30

370 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
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
# 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 socket
def is_postgres_available():
try:
s = socket.create_connection(('127.0.0.1', 5432), timeout=1)
s.close()
return True
except OSError:
return False
if is_postgres_available():
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', '127.0.0.1'),
'PORT': os.environ.get('DB_PORT', '5432'),
}
DATABASES = {
'default': {
'NAME': 'sellerprofile',
**db_credentials
},
'customerprofile': {
'NAME': 'customerprofile',
**db_credentials
},
'productprofile': {
'NAME': 'productprofile',
**db_credentials
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'customerprofile': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'productprofile': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
DATABASE_ROUTERS = ['config.db_router.DatabaseRouter']
# 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
import json
from botocore.exceptions import ClientError
def load_s3_secrets():
secret_name = "arn:aws:secretsmanager:ap-south-2:764709663363:secret:betasupplierdocument-rjF6JE"
region_name = "ap-south-2"
try:
session = boto3.session.Session()
client = session.client(service_name='secretsmanager', region_name=region_name)
get_secret_value_response = client.get_secret_value(SecretId=secret_name)
secrets = json.loads(get_secret_value_response['SecretString'])
# Inject secrets into environment variables so views.py can use them
for key, value in secrets.items():
os.environ[key] = str(value)
return secrets
except Exception as e:
print(f"Warning: Failed to load S3 secrets from Secrets Manager: {e}")
return {}
s3_secrets = load_s3_secrets()
def load_surepass_secrets():
secret_name = "arn:aws:secretsmanager:ap-south-2:764709663363:secret:surpassbeta-r6EcKi"
region_name = "ap-south-2"
try:
session = boto3.session.Session()
client = session.client(service_name='secretsmanager', region_name=region_name)
get_secret_value_response = client.get_secret_value(SecretId=secret_name)
secrets = json.loads(get_secret_value_response['SecretString'])
if 'apikey' in secrets:
os.environ['SUREPASS_JWT_TOKEN'] = str(secrets['apikey'])
return secrets
except Exception as e:
print(f"Warning: Failed to load Surepass secrets from Secrets Manager: {e}")
return {}
surepass_secrets = load_surepass_secrets()
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')