231 lines
7.2 KiB
Python

"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 5.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""
from pathlib import Path
import os
# ใน core/settings.py (ด้านบนสุด)
from dotenv import load_dotenv
load_dotenv() # โหลดตัวแปรจาก .env
DB_HOST = os.getenv("DB_HOST", "cockroach-1")
# 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/5.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-a1c7+vs57v77ywrtrdrgg58utw5p1a4t2tq9!=w09y@nq-ig0q'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = [
'django_bolt',
'rest_framework',
'corsheaders',
]
LOCAL_APPS = [
'api',
'accounts',
'user_profile',
'permissions',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # สำคัญมากสำหรับ Frontend
'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: อนุญาตให้ Frontend เข้าถึง API ได้ (ใน Dev Mode)
CORS_ALLOWED_ORIGINS = [
"http://localhost:5173", # Vite/React Default Port
"http://127.0.0.1:5173",
]
CORS_ALLOW_ALL_ORIGINS = True # ควรเป็น False ใน Production
ROOT_URLCONF = 'core.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 = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django_cockroachdb',
'NAME': os.environ.get('DB_NAME', 'my_db'),
'HOST': os.environ.get('DB_HOST', 'cockroach-1'),
'PORT': os.environ.get('DB_PORT', '26257'),
'USER': os.environ.get('DB_USER', 'root'),
'PASSWORD': os.environ.get('DB_PASSWORD', ''),
# อยู่ระดับเดียวกับ 'ENGINE' และ 'OPTIONS'
'support_check_by_version': False,
'OPTIONS': {
# ใช้ 'options' เพื่อส่งค่า config ไปยัง CockroachDB/PostgreSQL
'options': '-c default_transaction_read_only=off'
},
'ATOMIC_REQUESTS': False,
},
}
# Password validation
# https://docs.djangoproject.com/en/5.2/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/5.2/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/5.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# 1. กำหนด Custom User Model
AUTH_USER_MODEL = 'accounts.CustomUser' # ต้องชี้ไปที่ Model ใน App accounts/models.py
# 2. ตั้งค่า REST Framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
# ใช้ JWT เป็นวิธีการยืนยันตัวตนหลัก
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
# 3. ตั้งค่า DJOSER (เพื่อจัดการ Auth Endpoints)
DJOSER = {
# ใช้งาน JWT โดยตรง
'USER_ID_FIELD': 'id', # ใช้ ID ของ User Model
'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', # URL สำหรับ Frontend
'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': '#/activate/{uid}/{token}', # หากต้องการยืนยันอีเมล
'SERIALIZERS': {
'user_create': 'accounts.serializers.UserCreateSerializer', # จะสร้างในขั้นตอนถัดไป
'user': 'accounts.serializers.UserSerializer', # ใช้ UserSerializer เดิม
'current_user': 'accounts.serializers.UserSerializer',
},
'TOKEN_MODEL': None, # ไม่ใช้ TokenAuth แบบเก่า
'PERMISSIONS': {
'user_create': ['rest_framework.permissions.AllowAny'],
}
}
REDIS_HOST = os.getenv("REDIS_HOST", "redis")
REDIS_PORT = os.getenv("REDIS_PORT", "6379")
# 1. ตั้งค่า Redis Cache
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
# ใช้ตัวแปร REDIS_HOST ที่ดึงมาจาก .env (localhost) หรือ Docker (redis)
"LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"IGNORE_EXCEPTIONS": True
}
}
}
# 2. บังคับให้ Django ใช้ Cache (Redis) ในการเก็บ Session
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
# 3. ใช้ Redis สำหรับเก็บ Token Cache (สำหรับ DRF/JWT ถ้าจำเป็น)
# CACHE_MIDDLEWARE_SECONDS = 60 * 5 # 5 นาที
# CACHE_MIDDLEWARE_KEY_PREFIX = 'auth_cache'
# CELERY CONFIGURATION
CELERY_BROKER_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}/0'
CELERY_RESULT_BACKEND = f'redis://{REDIS_HOST}:{REDIS_PORT}/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Bangkok'