forked from val-lop20/Pagina-de-Asistencia-MAC
270 lines
8.1 KiB
Python
270 lines
8.1 KiB
Python
"""
|
|
Django settings for mac_attendance project.
|
|
|
|
Generated by 'django-admin startproject' using Django 5.2.6.
|
|
|
|
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
|
|
from decouple import config
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
|
|
SECRET_KEY = config('SECRET_KEY')
|
|
|
|
DEBUG = config('DEBUG', default=False, cast=bool)
|
|
|
|
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='localhost,127.0.0.1').split(',')
|
|
|
|
INSTALLED_APPS = [
|
|
'django.contrib.admin',
|
|
'django.contrib.auth',
|
|
'django.contrib.contenttypes',
|
|
'django.contrib.sessions',
|
|
'django.contrib.messages',
|
|
'django.contrib.staticfiles',
|
|
'rest_framework',
|
|
'rest_framework_simplejwt',
|
|
'corsheaders',
|
|
'import_export',
|
|
'authentication',
|
|
'events',
|
|
'attendance',
|
|
]
|
|
|
|
MIDDLEWARE = [
|
|
'corsheaders.middleware.CorsMiddleware',
|
|
'django.middleware.security.SecurityMiddleware',
|
|
'django.contrib.sessions.middleware.SessionMiddleware',
|
|
'django.middleware.common.CommonMiddleware',
|
|
'mac_attendance.middleware.DisableCSRFOnAPIMiddleware', # Exentar API de CSRF (usamos JWT)
|
|
'django.middleware.csrf.CsrfViewMiddleware',
|
|
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
|
'django.contrib.messages.middleware.MessageMiddleware',
|
|
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
|
'mac_attendance.middleware.AuditMiddleware', # Auditoría de seguridad
|
|
]
|
|
|
|
# Rate Limiting Configuration
|
|
RATELIMIT_ENABLE = config('RATELIMIT_ENABLE', default=True, cast=bool)
|
|
RATELIMIT_USE_CACHE = 'default' # Usar cache por defecto (memory en dev)
|
|
|
|
ROOT_URLCONF = 'mac_attendance.urls'
|
|
|
|
TEMPLATES = [
|
|
{
|
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
'DIRS': [BASE_DIR / 'templates'],
|
|
'APP_DIRS': True,
|
|
'OPTIONS': {
|
|
'context_processors': [
|
|
'django.template.context_processors.debug',
|
|
'django.template.context_processors.request',
|
|
'django.contrib.auth.context_processors.auth',
|
|
'django.contrib.messages.context_processors.messages',
|
|
],
|
|
},
|
|
},
|
|
]
|
|
|
|
WSGI_APPLICATION = 'mac_attendance.wsgi.application'
|
|
|
|
# Database Configuration - PostgreSQL
|
|
DATABASES = {
|
|
'default': {
|
|
'ENGINE': 'django.db.backends.postgresql',
|
|
'NAME': config('DB_NAME', default='mac_attendance'),
|
|
'USER': config('DB_USER', default='mac_user'),
|
|
'PASSWORD': config('DB_PASSWORD', default='mac_password_2024_secure'),
|
|
'HOST': config('DB_HOST', default='db'),
|
|
'PORT': config('DB_PORT', default='5432'),
|
|
'CONN_MAX_AGE': 600, # Conexiones persistentes para mejor rendimiento
|
|
'OPTIONS': {
|
|
'connect_timeout': 10,
|
|
}
|
|
}
|
|
}
|
|
|
|
# Cache Configuration (para rate limiting)
|
|
CACHES = {
|
|
'default': {
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
|
'LOCATION': 'ratelimit-cache',
|
|
}
|
|
}
|
|
|
|
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',
|
|
},
|
|
]
|
|
|
|
LANGUAGE_CODE = 'es-mx'
|
|
TIME_ZONE = 'America/Mexico_City'
|
|
USE_I18N = True
|
|
USE_TZ = True
|
|
|
|
STATIC_URL = '/static/'
|
|
STATIC_ROOT = BASE_DIR / 'staticfiles'
|
|
|
|
MEDIA_URL = '/media/'
|
|
MEDIA_ROOT = BASE_DIR / 'media'
|
|
|
|
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
|
|
|
# Security Settings for Production
|
|
if not DEBUG:
|
|
# HTTPS/SSL Settings
|
|
SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT', default=True, cast=bool)
|
|
SESSION_COOKIE_SECURE = config('SESSION_COOKIE_SECURE', default=True, cast=bool)
|
|
CSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE', default=True, cast=bool)
|
|
|
|
# HSTS (HTTP Strict Transport Security)
|
|
SECURE_HSTS_SECONDS = config('SECURE_HSTS_SECONDS', default=31536000, cast=int) # 1 año
|
|
SECURE_HSTS_INCLUDE_SUBDOMAINS = config('SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True, cast=bool)
|
|
SECURE_HSTS_PRELOAD = config('SECURE_HSTS_PRELOAD', default=True, cast=bool)
|
|
|
|
# Security Headers
|
|
SECURE_CONTENT_TYPE_NOSNIFF = True
|
|
SECURE_BROWSER_XSS_FILTER = True
|
|
X_FRAME_OPTIONS = 'DENY'
|
|
|
|
# Proxy Settings (para uso detrás de nginx/apache)
|
|
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
|
|
|
|
# CORS settings
|
|
CORS_ALLOWED_ORIGINS = config(
|
|
'CORS_ALLOWED_ORIGINS',
|
|
default='http://localhost,http://127.0.0.1,http://localhost:5173,http://127.0.0.1:5173'
|
|
).split(',')
|
|
|
|
CORS_ALLOW_CREDENTIALS = True
|
|
|
|
# CSRF Settings - Exentar rutas de API ya que usamos JWT
|
|
CSRF_TRUSTED_ORIGINS = config(
|
|
'CSRF_TRUSTED_ORIGINS',
|
|
default='http://localhost,http://127.0.0.1'
|
|
).split(',')
|
|
|
|
# Exentar todas las rutas de API del CSRF check (usamos JWT para seguridad)
|
|
CSRF_EXEMPT_URLS = [r'^api/.*$']
|
|
|
|
# Django REST Framework
|
|
REST_FRAMEWORK = {
|
|
'DEFAULT_AUTHENTICATION_CLASSES': [
|
|
'rest_framework_simplejwt.authentication.JWTAuthentication',
|
|
'rest_framework.authentication.SessionAuthentication', # Mantener para Django admin
|
|
],
|
|
'DEFAULT_PERMISSION_CLASSES': [
|
|
'rest_framework.permissions.IsAuthenticated',
|
|
],
|
|
'EXCEPTION_HANDLER': 'mac_attendance.exceptions.custom_exception_handler',
|
|
}
|
|
|
|
# JWT Settings
|
|
from datetime import timedelta
|
|
|
|
SIMPLE_JWT = {
|
|
'ACCESS_TOKEN_LIFETIME': timedelta(hours=1),
|
|
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
|
|
'ROTATE_REFRESH_TOKENS': True,
|
|
'BLACKLIST_AFTER_ROTATION': False,
|
|
'UPDATE_LAST_LOGIN': True,
|
|
|
|
'ALGORITHM': 'HS256',
|
|
'SIGNING_KEY': SECRET_KEY,
|
|
'VERIFYING_KEY': None,
|
|
|
|
'AUTH_HEADER_TYPES': ('Bearer',),
|
|
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
|
|
'USER_ID_FIELD': 'id',
|
|
'USER_ID_CLAIM': 'user_id',
|
|
|
|
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
|
|
'TOKEN_TYPE_CLAIM': 'token_type',
|
|
}
|
|
|
|
# Logging Configuration
|
|
LOGGING = {
|
|
'version': 1,
|
|
'disable_existing_loggers': False,
|
|
'formatters': {
|
|
'verbose': {
|
|
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
|
|
'style': '{',
|
|
},
|
|
'simple': {
|
|
'format': '{levelname} {asctime} {message}',
|
|
'style': '{',
|
|
},
|
|
'audit': {
|
|
'format': '[AUDIT] {asctime} {levelname} {message}',
|
|
'style': '{',
|
|
},
|
|
},
|
|
'handlers': {
|
|
'console': {
|
|
'class': 'logging.StreamHandler',
|
|
'formatter': 'simple',
|
|
},
|
|
'file': {
|
|
'class': 'logging.FileHandler',
|
|
'filename': BASE_DIR / 'logs' / 'django.log',
|
|
'formatter': 'verbose',
|
|
},
|
|
'security_file': {
|
|
'class': 'logging.FileHandler',
|
|
'filename': BASE_DIR / 'logs' / 'security.log',
|
|
'formatter': 'audit',
|
|
},
|
|
'audit_file': {
|
|
'class': 'logging.FileHandler',
|
|
'filename': BASE_DIR / 'logs' / 'audit.log',
|
|
'formatter': 'audit',
|
|
},
|
|
},
|
|
'loggers': {
|
|
'django': {
|
|
'handlers': ['console', 'file'] if not DEBUG else ['console'],
|
|
'level': 'INFO' if not DEBUG else 'DEBUG',
|
|
},
|
|
'django.security': {
|
|
'handlers': ['console', 'security_file'] if not DEBUG else ['console'],
|
|
'level': 'WARNING',
|
|
'propagate': False,
|
|
},
|
|
'authentication.audit': {
|
|
'handlers': ['console', 'audit_file'] if not DEBUG else ['console'],
|
|
'level': 'INFO',
|
|
'propagate': False,
|
|
},
|
|
# Logger para debugging de rate limiting
|
|
'django_ratelimit': {
|
|
'handlers': ['console', 'security_file'] if not DEBUG else ['console'],
|
|
'level': 'WARNING',
|
|
'propagate': False,
|
|
},
|
|
},
|
|
}
|
|
|
|
# Crear directorio de logs si no existe
|
|
import os
|
|
LOGS_DIR = BASE_DIR / 'logs'
|
|
if not os.path.exists(LOGS_DIR):
|
|
os.makedirs(LOGS_DIR)
|
|
|