diff --git a/.env.example b/.env.example index b494d7f..8d78f4e 100644 --- a/.env.example +++ b/.env.example @@ -2,8 +2,9 @@ USE_REMOTE_MYSQL=0 ENABLE_DB_SEEDING=1 DOCKER_ENV=development -UPLOAD_FOLDER=app/static/uploads -SECRET_KEY=supersecretplantappkey +FLASK_ENV=development +UPLOAD_FOLDER=static/uploads +SECRET_KEY=37f765030a6986ce47922ea1248d1e8dc24c1bc0638e4cd0d09382d1634a8e2a # MySQL configuration MYSQL_HOST=db @@ -13,9 +14,10 @@ MYSQL_USER=plant_user MYSQL_PASSWORD=plant_pass MYSQL_ROOT_PASSWORD=supersecret - +# Neo4j Settings NEO4J_URI=bolt://neo4j:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=your_secure_password +# Media Settings STANDARD_IMG_SIZE=300x200 diff --git a/.gitignore b/.gitignore index 424e42e..e6c0b6a 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,6 @@ __pycache__/ instance/ mysql_data/ .env -#.env.* # VS Code .vscode/ diff --git a/Dockerfile b/Dockerfile index e070a62..ae6c8c4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,16 +1,32 @@ FROM python:3.11-slim +# Install build deps and netcat for the DB-wait +RUN apt-get update && apt-get install -y \ + gcc \ + default-libmysqlclient-dev \ + pkg-config \ + netcat-openbsd \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# Upgrade pip and install Python requirements WORKDIR /app +COPY requirements.txt . +RUN pip install --upgrade pip \ + && pip install -r requirements.txt + +# Copy the app code COPY . . -# Required for mysqlclient + netcat wait -RUN apt-get update && apt-get install -y gcc default-libmysqlclient-dev pkg-config netcat-openbsd curl && rm -rf /var/lib/apt/lists/* +# Create a non-root user and give it ownership of /app +RUN useradd -ms /bin/bash appuser \ + && chown -R appuser:appuser /app -RUN pip install --upgrade pip -RUN pip install -r requirements.txt +# Switch to appuser for all subsequent commands +USER appuser -# Add entrypoint script -COPY entrypoint.sh /entrypoint.sh +# Make the entrypoint script executable +COPY --chown=appuser:appuser entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] diff --git a/app/__init__.py b/app/__init__.py index 4ced773..7cc9d6b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,120 +1,145 @@ -# app/__init__.py +# File: app/__init__.py import os import json -import glob import importlib -import importlib.util import time -from flask import Flask,request +from flask import Flask, request from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_wtf.csrf import CSRFProtect -from dotenv import load_dotenv from datetime import datetime +from dotenv import load_dotenv, find_dotenv +# ─── Load .env ──────────────────────────────────────────────────────────────── +dotenv_path = find_dotenv() +if dotenv_path: + load_dotenv(dotenv_path, override=True) -# Load environment variables from .env or system -load_dotenv() - -# ─── Initialize core extensions ───────────────────────────────────────────────── +# ─── Core extensions ─────────────────────────────────────────────────────────── db = SQLAlchemy() migrate = Migrate() login_manager = LoginManager() csrf = CSRFProtect() -from plugins.media.routes import generate_image_url # Import it here - +# ─── Template helper (still in core) ────────────────────────────────────────── +from plugins.media.routes import generate_image_url # noqa: E402 def create_app(): - app = Flask(__name__) + # ─── Configure Flask ──────────────────────────────────────────────────────── + project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + app = Flask( + __name__, + static_folder=os.path.join(project_root, 'static'), + static_url_path='/static' + ) app.config.from_object('app.config.Config') - # ─── Initialize extensions with the app ─────────────────────────────────────── + # ─── Init extensions ─────────────────────────────────────────────────────── csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) login_manager.init_app(app) login_manager.login_view = 'auth.login' - # ─── Register user_loader for Flask-Login ─────────────────────────────────── - from plugins.auth.models import User - - @login_manager.user_loader - def load_user(user_id): - try: - return User.query.get(int(user_id)) - except Exception: - return None - - # ─── Register error handlers ───────────────────────────────────────────────── - from .errors import bp as errors_bp + # ─── Core routes & errors ─────────────────────────────────────────────────── + from .errors import bp as errors_bp # noqa: E402 app.register_blueprint(errors_bp) + from .routes import init_app as register_core_routes # noqa: E402 + register_core_routes(app) + app.logger.info("✔️ Registered core routes") - # ─── 1) Auto‐import plugin models by their package names ───────────────────── - # This ensures that every plugins//models.py is imported exactly once - plugin_model_paths = glob.glob( - os.path.join(os.path.dirname(__file__), '..', 'plugins', '*', 'models.py') - ) - for path in plugin_model_paths: - # path looks like ".../plugins/plant/models.py" - rel = path.split(os.sep)[-2] # e.g. "plant" - pkg = f"plugins.{rel}.models" # e.g. "plugins.plant.models" + # ─── JSON‐driven plugin loader ────────────────────────────────────────────── + plugins_dir = os.path.join(project_root, 'plugins') + for name in sorted(os.listdir(plugins_dir)): + plugin_path = os.path.join(plugins_dir, name) + manifest = os.path.join(plugin_path, 'plugin.json') + if not os.path.isfile(manifest): + continue + + errors = [] try: - importlib.import_module(pkg) - print(f"✅ (Startup) Loaded: {pkg}") + meta = json.load(open(manifest)) except Exception as e: - print(f"❌ (Startup) Failed to load {pkg}: {e}") - - # ─── 2) Auto‐discover & register plugin routes, CLI, entry‐points ──────────── - plugin_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'plugins')) - for plugin in os.listdir(plugin_path): - if plugin.endswith('.noload'): - print(f"[⏭] Skipping plugin '{plugin}' (marked as .noload)") + print(f"Plugin '{name}' 🛑 manifest load failed: {e}") continue - plugin_dir = os.path.join(plugin_path, plugin) - if not os.path.isdir(plugin_dir): - continue - - # (a) Register routes.py - route_file = os.path.join(plugin_dir, 'routes.py') - if os.path.isfile(route_file): + # 1) Import models + for model_path in meta.get('models', []): try: - spec = importlib.util.spec_from_file_location(f"plugins.{plugin}.routes", route_file) - mod = importlib.util.module_from_spec(spec) - spec.loader.exec_module(mod) - if hasattr(mod, 'bp'): - app.register_blueprint(mod.bp, strict_slashes=False) - print(f"✔️ Registered routes for plugin '{plugin}'") + importlib.import_module(model_path) except Exception as e: - print(f"❌ Failed to load routes from plugin '{plugin}': {e}") + errors.append(f"model import ({model_path}): {e}") - # (b) Register CLI and entry‐point - init_file = os.path.join(plugin_dir, '__init__.py') - plugin_json = os.path.join(plugin_dir, 'plugin.json') - if os.path.isfile(init_file): + # 1.b) user_loader hook + ul = meta.get('user_loader') + if ul: try: - cli_module = importlib.import_module(f"plugins.{plugin}") - if hasattr(cli_module, 'register_cli'): - cli_module.register_cli(app) - print(f"✔️ Registered CLI for plugin '{plugin}'") - if os.path.isfile(plugin_json): - with open(plugin_json, 'r') as f: - meta = json.load(f) - entry = meta.get('entry_point') - if entry and hasattr(cli_module, entry): - getattr(cli_module, entry)(app) - print(f"✔️ Ran entry point '{entry}' for plugin '{plugin}'") + mod = importlib.import_module(ul['module']) + fn = getattr(mod, ul['callable']) + fn(app) except Exception as e: - print(f"❌ Failed to load CLI for plugin '{plugin}': {e}") + errors.append(f"user_loader ({ul['module']}:{ul['callable']}): {e}") - # ─── Inject current year into templates ──────────────────────────────────────── + # 2) Register routes + routes_cfg = meta.get('routes') + if routes_cfg: + try: + mod = importlib.import_module(routes_cfg['module']) + bp_obj = getattr(mod, routes_cfg['blueprint']) + prefix = routes_cfg.get('url_prefix') + app.register_blueprint(bp_obj, url_prefix=prefix, strict_slashes=False) + except Exception as e: + errors.append(f"routes ({routes_cfg['module']}): {e}") + + # 3) Register CLI commands + cli_cfg = meta.get('cli') + if cli_cfg: + try: + mod = importlib.import_module(cli_cfg['module']) + fn = getattr(mod, cli_cfg['callable']) + app.cli.add_command(fn) + except Exception as e: + errors.append(f"cli ({cli_cfg['module']}:{cli_cfg['callable']}): {e}") + + # 4) Template globals + for tg in meta.get('template_globals', []): + try: + mod_name, fn_name = tg['callable'].rsplit('.', 1) + mod = importlib.import_module(mod_name) + fn = getattr(mod, fn_name) + app.jinja_env.globals[tg['name']] = fn + except Exception as e: + errors.append(f"template_global ({tg}): {e}") + + # 5) Subplugins (models + routes) + for sp in meta.get('subplugins', []): + for mp in sp.get('models', []): + try: + importlib.import_module(mp) + except Exception as e: + errors.append(f"subplugin model ({mp}): {e}") + sp_rt = sp.get('routes') + if sp_rt: + try: + mod = importlib.import_module(sp_rt['module']) + bp_obj = getattr(mod, sp_rt['blueprint']) + prefix = sp_rt.get('url_prefix') + app.register_blueprint(bp_obj, url_prefix=prefix, strict_slashes=False) + except Exception as e: + errors.append(f"subplugin routes ({sp_rt['module']}): {e}") + + # Final status + if errors: + print(f"Plugin '{name}' 🛑 failed to load: {'; '.join(errors)}") + else: + print(f"Plugin '{name}' ✔️ Loaded Successfully.") + + # ─── Context processors, analytics, teardown ─────────────────────────────── @app.context_processor def inject_current_year(): - from datetime import datetime return {'current_year': datetime.now().year} @app.context_processor @@ -127,17 +152,16 @@ def create_app(): @app.after_request def log_analytics(response): - # import here to avoid circular at module‐load time - from plugins.admin.models import AnalyticsEvent + from plugins.admin.models import AnalyticsEvent # noqa: E402 try: duration = time.time() - getattr(request, '_start_time', time.time()) ev = AnalyticsEvent( - method=request.method, - path=request.path, - status_code=response.status_code, - response_time=duration, - user_agent=request.headers.get('User-Agent'), - referer=request.headers.get('Referer'), + method = request.method, + path = request.path, + status_code = response.status_code, + response_time = duration, + user_agent = request.headers.get('User-Agent'), + referer = request.headers.get('Referer'), accept_language=request.headers.get('Accept-Language'), ) db.session.add(ev) @@ -146,6 +170,11 @@ def create_app(): db.session.rollback() return response + @app.teardown_appcontext + def shutdown_session(exception=None): + db.session.remove() + + # ─── Keep the template helper exposed ────────────────────────────────────── app.jinja_env.globals['generate_image_url'] = generate_image_url return app diff --git a/app/config.py b/app/config.py index 40f6e1c..5d8f0d6 100644 --- a/app/config.py +++ b/app/config.py @@ -1,45 +1,93 @@ import os +from dotenv import load_dotenv, find_dotenv -# CONFIG_DIR is your app package; go up one to the project root +# ─── Load .env from project root or any parent ──────────────────────────────── +dotenv_path = find_dotenv() +if dotenv_path: + load_dotenv(dotenv_path, override=True) + +# ─── Paths ──────────────────────────────────────────────────────────────────── CONFIG_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_ROOT = os.path.dirname(CONFIG_DIR) class Config: - SECRET_KEY = os.environ['SECRET_KEY'] - MAX_CONTENT_LENGTH = int( - os.environ.get('MAX_CONTENT_LENGTH', 20 * 1024 * 1024 * 1024) - ) - ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} + # ─── Environment ───────────────────────────────────────────────────────────── + ENV = ( + os.getenv('FLASK_ENV') + or os.getenv('DOCKER_ENV') + or 'production' + ).lower() - UPLOAD_FOLDER = os.path.join(PROJECT_ROOT, "static", "uploads") + # ─── Secret Key ────────────────────────────────────────────────────────────── + if ENV == 'production': + SECRET_KEY = os.getenv('SECRET_KEY') + if not SECRET_KEY: + raise RuntimeError( + "SECRET_KEY environment variable not set! " + "Generate one with `openssl rand -hex 32` and export it." + ) + else: + # dev/test: fall back to env or a random one + SECRET_KEY = os.getenv('SECRET_KEY') or os.urandom(24).hex() - # MySQL connection parameters - MYSQL_USER = os.environ['MYSQL_USER'] - MYSQL_PASSWORD = os.environ['MYSQL_PASSWORD'] - MYSQL_HOST = os.environ['MYSQL_HOST'] - MYSQL_PORT = int(os.environ.get('MYSQL_PORT', 3306)) - MYSQL_DATABASE = os.environ['MYSQL_DATABASE'] + # ─── Uploads ──────────────────────────────────────────────────────────────── + # Default to PROJECT_ROOT/static/uploads; if UPLOAD_FOLDER env is set, resolve relative to PROJECT_ROOT + _env_upload = os.getenv('UPLOAD_FOLDER', '') + if _env_upload: + # if absolute, use directly; otherwise join to project root + UPLOAD_FOLDER = _env_upload if os.path.isabs(_env_upload) else os.path.join(PROJECT_ROOT, _env_upload) + else: + UPLOAD_FOLDER = os.path.join(PROJECT_ROOT, "static", "uploads") - # Build the SQLAlchemy database URI - SQLALCHEMY_DATABASE_URI = ( + MAX_CONTENT_LENGTH = int(os.getenv('MAX_CONTENT_LENGTH', 20 * 1024**3)) + ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} + + # ─── Celery ──────────────────────────────────────────────────────────────── + CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL') + if not CELERY_BROKER_URL: + raise RuntimeError("CELERY_BROKER_URL environment variable not set!") + CELERY_RESULT_BACKEND = os.getenv('CELERY_RESULT_BACKEND', CELERY_BROKER_URL) + + # ─── MySQL ────────────────────────────────────────────────────────────────── + MYSQL_USER = os.getenv('MYSQL_USER') + MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD') + if not MYSQL_PASSWORD: + raise RuntimeError("MYSQL_PASSWORD environment variable not set!") + MYSQL_HOST = os.getenv('MYSQL_HOST', 'db') + MYSQL_PORT = int(os.getenv('MYSQL_PORT', 3306)) + MYSQL_DATABASE = os.getenv('MYSQL_DATABASE') + if not MYSQL_DATABASE: + raise RuntimeError("MYSQL_DATABASE environment variable not set!") + + SQLALCHEMY_DATABASE_URI = ( f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}" f"@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}" ) SQLALCHEMY_TRACK_MODIFICATIONS = False - # Optional toggles - ENABLE_DB_SEEDING = os.environ.get('ENABLE_DB_SEEDING', '0') == '1' - DOCKER_ENV = os.environ.get('FLASK_ENV', 'production') + # ─── Cookies / Session ────────────────────────────────────────────────────── + SESSION_COOKIE_SECURE = True + SESSION_COOKIE_HTTPONLY = True + SESSION_COOKIE_SAMESITE = 'Lax' + REMEMBER_COOKIE_SECURE = True + REMEMBER_COOKIE_HTTPONLY = True + REMEMBER_COOKIE_SAMESITE = 'Lax' + PREFERRED_URL_SCHEME = 'https' - # Neo4j configuration + # ─── Toggles ──────────────────────────────────────────────────────────────── + ENABLE_DB_SEEDING = os.getenv('ENABLE_DB_SEEDING', '0') == '1' + DOCKER_ENV = os.getenv('DOCKER_ENV', 'production') + + # ─── Neo4j ────────────────────────────────────────────────────────────────── NEO4J_URI = os.getenv('NEO4J_URI', 'bolt://neo4j:7687') NEO4J_USER = os.getenv('NEO4J_USER', 'neo4j') - NEO4J_PASSWORD = os.getenv('NEO4J_PASSWORD', 'your_secure_password') + NEO4J_PASSWORD = os.getenv('NEO4J_PASSWORD') + if not NEO4J_PASSWORD: + raise RuntimeError("NEO4J_PASSWORD environment variable not set!") - # Standard image size (for placeholders, etc.) + # ─── Misc ────────────────────────────────────────────────────────────────── STANDARD_IMG_SIZE = tuple( map(int, os.getenv('STANDARD_IMG_SIZE', '300x200').split('x')) ) - PLANT_CARDS_BASE_URL = "https://plant.cards" - ALLOW_REGISTRATION = False + ALLOW_REGISTRATION = False diff --git a/app/routes.py b/app/routes.py new file mode 100644 index 0000000..81b72b5 --- /dev/null +++ b/app/routes.py @@ -0,0 +1,15 @@ +from flask import render_template + +def init_app(app): + """ + Register core application routes directly on the Flask app: + - GET / → home page + - GET /health → health check + """ + @app.route('/') + def home(): + return render_template('core/home.html') + + @app.route('/health') + def health(): + return 'OK', 200 diff --git a/app/templates/400.html b/app/templates/400.html index b24eec9..f1c8255 100644 --- a/app/templates/400.html +++ b/app/templates/400.html @@ -7,6 +7,6 @@

400 – Bad Request

{{ error.description or "Sorry, we couldn’t understand that request." }}

- Return home + Return home diff --git a/plugins/core_ui/templates/core_ui/_media_macros.html b/app/templates/core/_media_macros.html similarity index 96% rename from plugins/core_ui/templates/core_ui/_media_macros.html rename to app/templates/core/_media_macros.html index 48ed992..23cff37 100644 --- a/plugins/core_ui/templates/core_ui/_media_macros.html +++ b/app/templates/core/_media_macros.html @@ -1,4 +1,3 @@ -{# plugins/core_ui/templates/core_ui/_media_macros.html #} {% macro render_media_list(media_list, thumb_width=150, current_user=None) -%} {% if media_list %}
diff --git a/plugins/core_ui/templates/core_ui/base.html b/app/templates/core/base.html similarity index 97% rename from plugins/core_ui/templates/core_ui/base.html rename to app/templates/core/base.html index 7785299..7f3d24a 100644 --- a/plugins/core_ui/templates/core_ui/base.html +++ b/app/templates/core/base.html @@ -22,7 +22,7 @@