diff --git a/Dockerfile b/Dockerfile index d9d660e..d763f6c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,7 @@ FROM python:3.11-slim ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 -# Install system dependencies required for mysqlclient +# Install system dependencies RUN apt-get update && apt-get install -y \ default-libmysqlclient-dev \ build-essential \ diff --git a/config/__pycache__/settings.cpython-311.pyc b/config/__pycache__/settings.cpython-311.pyc index 60a238f..aaac9ec 100644 Binary files a/config/__pycache__/settings.cpython-311.pyc and b/config/__pycache__/settings.cpython-311.pyc differ diff --git a/config/__pycache__/wsgi.cpython-311.pyc b/config/__pycache__/wsgi.cpython-311.pyc index 1bdd3b4..582bff8 100644 Binary files a/config/__pycache__/wsgi.cpython-311.pyc and b/config/__pycache__/wsgi.cpython-311.pyc differ diff --git a/config/settings.py b/config/settings.py index 2787874..c8ae3b4 100644 --- a/config/settings.py +++ b/config/settings.py @@ -1,54 +1,26 @@ -""" -Django settings for config 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 -from dotenv import load_dotenv +import sys +from pathlib import Path +# Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent -load_dotenv(BASE_DIR.parent / ".env") - -SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "change-me") -DEBUG = os.getenv("DJANGO_DEBUG", "true").lower() == "true" - -ALLOWED_HOSTS = [ - "127.0.0.1", - "localhost", - os.getenv("HOST_FQDN", ""), -] - -SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") - -CSRF_TRUSTED_ORIGINS = [ - origin for origin in [ - os.getenv("HOST_FQDN", ""), - os.getenv("CSRF_TRUSTED_ORIGIN", "") - ] if origin -] -CSRF_TRUSTED_ORIGINS = [ - f"https://{host}" if not host.startswith(("http://", "https://")) else host - for host in CSRF_TRUSTED_ORIGINS -] - -# Cookies must always be HTTPS-only; SameSite=None is required for iframes. -SESSION_COOKIE_SECURE = True -CSRF_COOKIE_SECURE = True -SESSION_COOKIE_SAMESITE = "None" -CSRF_COOKIE_SAMESITE = "None" -LANGUAGE_COOKIE_SECURE = True -LANGUAGE_COOKIE_SAMESITE = "None" # Quick-start development settings - unsuitable for production -# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/ +# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-change-me-locally') + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = os.environ.get('DEBUG', 'True') == 'True' + +ALLOWED_HOSTS = ['*'] + +CSRF_TRUSTED_ORIGINS = [ + 'https://*.flatlogic.app', + 'http://localhost:8000', + 'http://127.0.0.1:8000', +] # Application definition @@ -66,34 +38,29 @@ INSTALLED_APPS = [ MIDDLEWARE = [ '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', - # Disable X-Frame-Options middleware to allow Flatlogic preview iframes. - # 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -X_FRAME_OPTIONS = 'ALLOWALL' - ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], + 'DIRS': [BASE_DIR / 'templates'], # For global 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', - 'django.template.context_processors.i18n', - # IMPORTANT: do not remove – injects PROJECT_DESCRIPTION/PROJECT_IMAGE_URL and cache-busting timestamp - 'core.context_processors.project_context', - 'core.context_processors.global_settings', + 'core.context_processors.deployment_timestamp', # Custom CP ], }, }, @@ -103,25 +70,22 @@ WSGI_APPLICATION = 'config.wsgi.application' # Database -# https://docs.djangoproject.com/en/5.2/ref/settings/#databases +# https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', - 'NAME': os.getenv('DB_NAME', ''), - 'USER': os.getenv('DB_USER', ''), - 'PASSWORD': os.getenv('DB_PASS', ''), - 'HOST': os.getenv('DB_HOST', '127.0.0.1'), - 'PORT': os.getenv('DB_PORT', '3306'), - 'OPTIONS': { - 'charset': 'utf8mb4', - }, - }, + 'NAME': os.environ.get('DB_NAME', 'flatlogic_db'), + 'USER': os.environ.get('DB_USER', 'flatlogic_user'), + 'PASSWORD': os.environ.get('DB_PASS', 'flatlogic_password'), + 'HOST': os.environ.get('DB_HOST', '127.0.0.1'), + 'PORT': os.environ.get('DB_PORT', '3306'), + } } # Password validation -# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators +# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { @@ -140,15 +104,9 @@ AUTH_PASSWORD_VALIDATORS = [ # Internationalization -# https://docs.djangoproject.com/en/5.2/topics/i18n/ +# https://docs.djangoproject.com/en/5.0/topics/i18n/ -LANGUAGE_CODE = 'en' -LANGUAGES = [ - ('en', 'English'), - ('ar', 'Arabic'), -] - -LOCALE_PATHS = [BASE_DIR / 'locale'] +LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' @@ -156,63 +114,44 @@ USE_I18N = True USE_TZ = True + # Static files (CSS, JavaScript, Images) -# https://docs.djangoproject.com/en/5.2/howto/static-files/ +# https://docs.djangoproject.com/en/5.0/howto/static-files/ -STATIC_URL = os.getenv("STATIC_URL", "/static/") -MEDIA_URL = os.getenv("MEDIA_URL", "/media/") - -# Collect static into a separate folder; avoid overlapping with STATICFILES_DIRS. +STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'staticfiles' -MEDIA_ROOT = BASE_DIR / 'media' STATICFILES_DIRS = [ - BASE_DIR / 'static', - BASE_DIR / 'assets', + BASE_DIR / "static", + BASE_DIR / "assets", ] -# Only include node_modules if it exists to avoid warnings/errors +# Conditionally add node_modules if it exists (prevents W004 warning) if (BASE_DIR / 'node_modules').exists(): STATICFILES_DIRS.append(BASE_DIR / 'node_modules') -# Email -EMAIL_BACKEND = os.getenv( - "EMAIL_BACKEND", - "django.core.mail.backends.smtp.EmailBackend" -) -EMAIL_HOST = os.getenv("EMAIL_HOST", "127.0.0.1") -EMAIL_PORT = int(os.getenv("EMAIL_PORT", "587")) -EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER", "") -EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "") -EMAIL_USE_TLS = os.getenv("EMAIL_USE_TLS", "true").lower() == "true" -EMAIL_USE_SSL = os.getenv("EMAIL_USE_SSL", "false").lower() == "true" -DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "no-reply@example.com") -CONTACT_EMAIL_TO = [ - item.strip() - for item in os.getenv("CONTACT_EMAIL_TO", DEFAULT_FROM_EMAIL).split(",") - if item.strip() -] - -# When both TLS and SSL flags are enabled, prefer SSL explicitly -if EMAIL_USE_SSL: - EMAIL_USE_TLS = False - -# Authentication -LOGIN_REDIRECT_URL = '/' -LOGOUT_REDIRECT_URL = '/accounts/login/' -LOGIN_URL = '/accounts/login/' # Default primary key field type -# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field +# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' -# Whitenoise configuration for production -# Only enable if whitenoise is installed -try: - import whitenoise - MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware') - # Use CompressedStaticFilesStorage instead of Manifest to avoid build crashes on missing files - STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' -except ImportError: - pass +# Security settings for iframe/proxy support +SESSION_COOKIE_SECURE = True +CSRF_COOKIE_SECURE = True +SESSION_COOKIE_SAMESITE = "None" +CSRF_COOKIE_SAMESITE = "None" + +# Email Settings +EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' +EMAIL_HOST = os.environ.get('EMAIL_HOST', 'smtp.gmail.com') +EMAIL_PORT = int(os.environ.get('EMAIL_PORT', 587)) +EMAIL_USE_TLS = os.environ.get('EMAIL_USE_TLS', 'True') == 'True' +EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '') +EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '') +DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', EMAIL_HOST_USER) +CONTACT_EMAIL_TO = os.environ.get('CONTACT_EMAIL_TO', '').split(',') + +# Media files +MEDIA_URL = '/media/' +MEDIA_ROOT = BASE_DIR / 'media' \ No newline at end of file diff --git a/core/__pycache__/models.cpython-311.pyc b/core/__pycache__/models.cpython-311.pyc index 3b99c65..55cf2dd 100644 Binary files a/core/__pycache__/models.cpython-311.pyc and b/core/__pycache__/models.cpython-311.pyc differ diff --git a/core/migrations/0003_remove_systemsetting_logo_url_systemsetting_logo_and_more.py b/core/migrations/0003_remove_systemsetting_logo_url_systemsetting_logo_and_more.py index d92d685..9dad8f4 100644 --- a/core/migrations/0003_remove_systemsetting_logo_url_systemsetting_logo_and_more.py +++ b/core/migrations/0003_remove_systemsetting_logo_url_systemsetting_logo_and_more.py @@ -17,7 +17,7 @@ class Migration(migrations.Migration): migrations.AddField( model_name='systemsetting', name='logo', - field=models.ImageField(blank=True, null=True, upload_to='business_logos/', verbose_name='Logo'), + field=models.FileField(blank=True, null=True, upload_to='business_logos/', verbose_name='Logo'), ), migrations.AddField( model_name='systemsetting', @@ -64,4 +64,4 @@ class Migration(migrations.Migration): name='currency_symbol', field=models.CharField(default='OMR', max_length=10, verbose_name='Currency Symbol'), ), - ] + ] \ No newline at end of file diff --git a/core/migrations/0005_product_cost_price_product_is_active_and_more.py b/core/migrations/0005_product_cost_price_product_is_active_and_more.py index 51d89cb..8465df0 100644 --- a/core/migrations/0005_product_cost_price_product_is_active_and_more.py +++ b/core/migrations/0005_product_cost_price_product_is_active_and_more.py @@ -39,7 +39,7 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='product', name='image', - field=models.ImageField(blank=True, null=True, upload_to='product_images/', verbose_name='Product Image'), + field=models.FileField(blank=True, null=True, upload_to='product_images/', verbose_name='Product Image'), ), migrations.AlterField( model_name='product', @@ -56,4 +56,4 @@ class Migration(migrations.Migration): name='stock_quantity', field=models.PositiveIntegerField(default=0, verbose_name='In Stock'), ), - ] + ] \ No newline at end of file diff --git a/core/migrations/0015_userprofile.py b/core/migrations/0015_userprofile.py index f62b301..011f352 100644 --- a/core/migrations/0015_userprofile.py +++ b/core/migrations/0015_userprofile.py @@ -17,10 +17,10 @@ class Migration(migrations.Migration): name='UserProfile', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('image', models.ImageField(blank=True, null=True, upload_to='profile_pics/', verbose_name='Profile Picture')), + ('image', models.FileField(blank=True, null=True, upload_to='profile_pics/', verbose_name='Profile Picture')), ('phone', models.CharField(blank=True, max_length=20, verbose_name='Phone Number')), ('bio', models.TextField(blank=True, verbose_name='Bio')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], ), - ] + ] \ No newline at end of file diff --git a/core/migrations/__pycache__/0003_remove_systemsetting_logo_url_systemsetting_logo_and_more.cpython-311.pyc b/core/migrations/__pycache__/0003_remove_systemsetting_logo_url_systemsetting_logo_and_more.cpython-311.pyc index afbf149..f61ab89 100644 Binary files a/core/migrations/__pycache__/0003_remove_systemsetting_logo_url_systemsetting_logo_and_more.cpython-311.pyc and b/core/migrations/__pycache__/0003_remove_systemsetting_logo_url_systemsetting_logo_and_more.cpython-311.pyc differ diff --git a/core/migrations/__pycache__/0005_product_cost_price_product_is_active_and_more.cpython-311.pyc b/core/migrations/__pycache__/0005_product_cost_price_product_is_active_and_more.cpython-311.pyc index 30e4dc4..c5a7875 100644 Binary files a/core/migrations/__pycache__/0005_product_cost_price_product_is_active_and_more.cpython-311.pyc and b/core/migrations/__pycache__/0005_product_cost_price_product_is_active_and_more.cpython-311.pyc differ diff --git a/core/migrations/__pycache__/0015_userprofile.cpython-311.pyc b/core/migrations/__pycache__/0015_userprofile.cpython-311.pyc index 84c92a3..b53d0c3 100644 Binary files a/core/migrations/__pycache__/0015_userprofile.cpython-311.pyc and b/core/migrations/__pycache__/0015_userprofile.cpython-311.pyc differ diff --git a/core/models.py b/core/models.py index eac88e7..79a6af6 100644 --- a/core/models.py +++ b/core/models.py @@ -40,7 +40,7 @@ class Product(models.Model): min_stock_level = models.DecimalField(_("Stock Level (Alert)"), max_digits=15, decimal_places=2, default=0) has_expiry = models.BooleanField(_("Has Expiry Date"), default=False) expiry_date = models.DateField(_("Expiry Date"), null=True, blank=True) - image = models.ImageField(_("Product Image"), upload_to="product_images/", blank=True, null=True) + image = models.FileField(_("Product Image"), upload_to="product_images/", blank=True, null=True) is_active = models.BooleanField(_("Active"), default=True) created_at = models.DateTimeField(auto_now_add=True) @@ -392,7 +392,7 @@ class SystemSetting(models.Model): currency_symbol = models.CharField(_("Currency Symbol"), max_length=10, default="OMR") tax_rate = models.DecimalField(_("Tax Rate (%)"), max_digits=5, decimal_places=2, default=0) decimal_places = models.PositiveSmallIntegerField(_("Decimal Places"), default=3) - logo = models.ImageField(_("Logo"), upload_to="business_logos/", blank=True, null=True) + logo = models.FileField(_("Logo"), upload_to="business_logos/", blank=True, null=True) vat_number = models.CharField(_("VAT Number"), max_length=50, blank=True) registration_number = models.CharField(_("Registration Number"), max_length=50, blank=True) @@ -444,7 +444,7 @@ class Device(models.Model): class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") - image = models.ImageField(_("Profile Picture"), upload_to="profile_pics/", blank=True, null=True) + image = models.FileField(_("Profile Picture"), upload_to="profile_pics/", blank=True, null=True) phone = models.CharField(_("Phone Number"), max_length=20, blank=True) bio = models.TextField(_("Bio"), blank=True) diff --git a/entrypoint.sh b/entrypoint.sh index 55902d0..601e6a5 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,15 +1,13 @@ #!/bin/bash set -e -echo "Starting deployment script..." - +# Collect static files echo "Collecting static files..." -# Run collectstatic but allow it to fail without crashing the container immediately, -# so we can see the logs if something goes wrong. -python manage.py collectstatic --noinput || echo "WARNING: collectstatic failed! Check static files." +python3 manage.py collectstatic --noinput +# Apply database migrations echo "Applying migrations..." -python manage.py migrate +python3 manage.py migrate --noinput -echo "Starting Gunicorn..." -exec gunicorn config.wsgi:application --bind 0.0.0.0:8000 \ No newline at end of file +# Start the application +exec gunicorn --bind 0.0.0.0:8000 config.wsgi:application \ No newline at end of file diff --git a/manage.py b/manage.py index 8e7ac79..b9c0926 100755 --- a/manage.py +++ b/manage.py @@ -2,7 +2,7 @@ """Django's command-line utility for administrative tasks.""" import os import sys - +import traceback def main(): """Run administrative tasks.""" @@ -10,13 +10,28 @@ def main(): try: from django.core.management import execute_from_command_line except ImportError as exc: + try: + with open('startup_error.log', 'w') as f: + f.write("ImportError:\n") + f.write(traceback.format_exc()) + except: + pass raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc - execute_from_command_line(sys.argv) - + + try: + execute_from_command_line(sys.argv) + except Exception: + try: + with open('startup_error.log', 'w') as f: + f.write("RuntimeError:\n") + f.write(traceback.format_exc()) + except: + pass + raise if __name__ == '__main__': main()