Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(workspaces): scope the WordPress sites hub to the active workspace (#33)

Juan Denis8ea5f50408b6
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py
index 38b3d9cb..bf0c1f8f 100644
--- a/backend/app/api/wordpress.py
+++ b/backend/app/api/wordpress.py
@@ -21,8 +21,15 @@ def _resolve_app(site_or_app_id):
@wordpress_bp.route('/sites', methods=['GET'])
@jwt_required()
def list_sites():
- """List all WordPress sites (production sites with environment counts)."""
- result = WordPressService.get_sites()
+ """List all WordPress sites (production sites with environment counts).
+
+ Workspace-aware (#33): filters to the active workspace when one is supplied
+ (X-Workspace-Id / ?workspace_id), via the site's parent application."""
+ from app.services.workspace_service import WorkspaceService
+ user = User.query.get(get_jwt_identity())
+ ws_id = WorkspaceService.resolve_workspace_id(
+ user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
+ result = WordPressService.get_sites(workspace_id=ws_id)
return jsonify(result), 200
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index 2e6e5b52..7b76c635 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -1296,11 +1296,21 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
return site_data
@classmethod
- def get_sites(cls) -> Dict:
- """Get all production WordPress sites with environment counts."""
- from app.models import WordPressSite
+ def get_sites(cls, workspace_id=None) -> Dict:
+ """Get all production WordPress sites with environment counts.
+
+ Workspace scoping (#33): when workspace_id is given, only sites whose
+ Application belongs to that workspace are returned (join-based, since WP
+ sites carry no workspace_id of their own — they inherit their app's). The
+ hub is global today, so with no workspace context this is unchanged.
+ """
+ from app.models import WordPressSite, Application
- sites = WordPressSite.query.filter_by(is_production=True).all()
+ query = WordPressSite.query.filter_by(is_production=True)
+ if workspace_id is not None:
+ query = query.join(Application, WordPressSite.application_id == Application.id) \
+ .filter(Application.workspace_id == workspace_id)
+ sites = query.all()
result = []
for site in sites:
diff --git a/backend/tests/test_workspace_scope.py b/backend/tests/test_workspace_scope.py
index d9de27b6..8a1e340d 100644
--- a/backend/tests/test_workspace_scope.py
+++ b/backend/tests/test_workspace_scope.py
@@ -319,3 +319,33 @@ def test_servers_list_global_without_context(app, client):
r = client.get('/api/v1/servers', headers=_token(dev.id))
assert r.status_code == 200
assert any(s['name'] == 'srv-a' for s in r.get_json())
+
+
+def test_wordpress_sites_scoping_api(app, client):
+ from app import db
+ from app.services.workspace_service import WorkspaceService
+ from app.models import Application, WordPressSite
+
+ admin = _mk_user(db, 'wp_admin', 'admin')
+ ws_a = WorkspaceService.create_workspace({'name': 'WP-A'}, admin.id)
+ ws_b = WorkspaceService.create_workspace({'name': 'WP-B'}, admin.id)
+
+ def mk_site(name, ws_id):
+ a = Application(name=name, app_type='wordpress', user_id=admin.id, workspace_id=ws_id)
+ db.session.add(a)
+ db.session.commit()
+ db.session.add(WordPressSite(application_id=a.id, is_production=True))
+ db.session.commit()
+
+ mk_site('site-a', ws_a.id)
+ mk_site('site-b', ws_b.id)
+
+ # No context: the WP hub is global -> both sites.
+ r = client.get('/api/v1/wordpress/sites', headers=_token(admin.id))
+ assert r.status_code == 200
+ assert {s['name'] for s in r.get_json()['sites']} == {'site-a', 'site-b'}
+
+ # Scoped to workspace A (via the site's parent application) -> only site-a.
+ r = client.get('/api/v1/wordpress/sites', headers={**_token(admin.id), 'X-Workspace-Id': str(ws_a.id)})
+ assert r.status_code == 200
+ assert {s['name'] for s in r.get_json()['sites']} == {'site-a'}
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index d369dffb..4a1eeac3 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -302,6 +302,7 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c
- **Landed (frontend workspace selector):** the keystone that makes the foundation user-visible — the research flagged "no current-workspace context in the frontend" as *the* gap #33 must close. A self-contained `WorkspaceSwitcher` in the sidebar reads/writes an `active_workspace_id` in `localStorage`, which the central API client (`services/api/client.js`) now sends ambiently as the **`X-Workspace-Id` header** on every request (endpoints that don't honor it ignore it; cleared on logout). Switching reloads so all lists re-fetch under the new scope; the switcher self-hides for single-workspace installs and drops a stale selection on load. To make an ambient header safe, backend `resolve_workspace_id` was first made **lenient** (a deleted/forbidden workspace degrades to no-scope instead of 403/404, so a stale header can never break the apps/servers lists — still safe since no-scope only ever shows the user's *own* resources). Verified: frontend lint-clean + production build; the header→scoping path is covered end-to-end by the backend API tests. *(Follow-on: surfacing `workspace_id` in more list endpoints, a workspace management UX beyond the existing admin list, and per-workspace logo override.)*
- **Landed (workspace-scoped brand color):** the visible payoff — selecting a client workspace now recolors the whole panel to that client's brand. A workspace's `primary_color` (already on the model; now editable via a color picker added to the Workspaces create modal) is mirrored by the `WorkspaceSwitcher` into a `workspace_accent` localStorage key, and `ThemeContext` applies it via the existing `applyAccentToDOM` with **precedence over the user's personal accent** (`workspace_accent || accentColor`) — recoloring the logo gradient, buttons, and highlights. Deterministic (no effect-ordering races) because switching reloads and the value is read once on mount; cleared on logout and on a stale selection; reverts to the user accent on "All workspaces". Default color is the app accent, so a workspace is unbranded unless a custom color is chosen. Verified: frontend lint-clean (no new warnings) + production build. *(Deferred: per-workspace logo swap in the sidebar brand — the accent recolor is the high-impact piece and the default logo already recolors with the accent.)*
- **Landed (resource reassignment):** completes the organizing loop — existing resources were stuck wherever the backfill put them (Default); now they can be moved into client workspaces. New endpoints `PUT /apps/<id>/workspace` (owner-or-admin on the app) and `PUT /servers/<id>/workspace` (developer+), both requiring the **target** be a workspace the caller can access (member or admin); a null target moves a resource back to Default. UI: an **Apps** management modal on each Workspaces card (mirrors the Members modal) listing the workspace's apps with move-in/move-out — it fetches with `allWorkspaces` (an empty `X-Workspace-Id` header) so it can see apps in other workspaces to move them in, sidestepping the ambient scope. **Fixed a real bug** caught by tests: the ownership check compared `app.user_id` to the *stringified* `get_jwt_identity()` (int≠str → spurious 403); now uses `user.id`. Verified: backend `py_compile`, **2 new endpoint tests** (ownership + target-membership + null→Default + role gates), full suite **122 passed**, frontend lint-clean + production build. *(Servers reassignment is API-only for now; the management modal is apps-only.)*
+- **Landed (WordPress hub workspace scoping):** the active-workspace switcher now also filters the **WordPress sites hub**, not just apps/servers (it was the inconsistent gap). WP sites carry no `workspace_id` of their own, so `WordPressService.get_sites(workspace_id=…)` scopes **join-based** through the site's parent `Application.workspace_id`; `list_sites` resolves the active workspace and passes it. The hub is global today, so with no workspace context behavior is unchanged (additive, narrow-only). **No frontend change** — the WP hub already fetches through the header-injecting `api.request`, so it auto-scopes on the ambient `X-Workspace-Id`. Verified: backend `py_compile`, a new API test (global vs workspace-scoped), full suite **123 passed**. *(Follow-on for broad adoption: databases/domains are murkier — server-level vs app-child — and need their own analysis before scoping.)*
### #34 — Horizontal scaling `[XL]` ❌ — ⏸️ Deferred (XL + blocked on the same per-site reverse-proxy/upstream layer as #21)
- **Today:** `nginx_advanced_service` has load-balancing primitives (round-robin/least-conn/IP-hash) but WP containers are stateful (local uploads, no shared object cache).