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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(wordpress): passwordless WP-admin login, multisite detection, site tags
Juan Denis62adcdf28d0d
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex 583945d6..c4e5d92e 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -54,6 +54,36 @@ def get_site(site_id):return jsonify(result), 200+@wordpress_bp.route('/sites/<int:site_id>/tags', methods=['PATCH'])+@jwt_required()+def set_site_tags(site_id):+ """Replace the tag list for a WordPress site."""+ data = request.get_json() or {}+ tags = data.get('tags')+ if tags is None or not isinstance(tags, list):+ return jsonify({'error': 'tags must be a list'}), 400++ site = WordPressSite.query.get(site_id)+ if not site:+ return jsonify({'error': 'Site not found'}), 404++ # Normalize: strings only, trimmed, non-empty, de-duplicated (order-preserving)+ seen = set()+ cleaned = []+ for t in tags:+ if not isinstance(t, str):+ continue+ v = t.strip()+ if v and v.lower() not in seen:+ seen.add(v.lower())+ cleaned.append(v)++ import json as _json+ site.tags = _json.dumps(cleaned)+ db.session.commit()+ return jsonify({'success': True, 'tags': cleaned}), 200++@wordpress_bp.route('/sites/<int:site_id>', methods=['DELETE'])@jwt_required()def delete_site(site_id):@@ -624,6 +654,58 @@ def create_wp_user(app_id):return jsonify(result), 201 if result['success'] else 400+@wordpress_bp.route('/sites/<int:site_id>/login', methods=['POST'])+@jwt_required()+@admin_required+def wp_auto_login(site_id):+ """Mint a one-time passwordless wp-admin login URL for the calling operator."""+ from app.services.audit_service import AuditService+ current_user_id = get_jwt_identity()+ operator = User.query.get(current_user_id)+ if not operator:+ return jsonify({'error': 'User not found'}), 404++ wp_site = WordPressSite.query.get(site_id)+ app = wp_site.application if wp_site else _resolve_app(site_id)+ if not app or not app.root_path:+ return jsonify({'error': 'Application not found'}), 404+ if app.app_type != 'wordpress':+ return jsonify({'error': 'Application is not a WordPress site'}), 400++ # Resolve a managed admin tied to the operator's panel email. Prefer the+ # site's recorded admin_user; otherwise derive a deterministic username+ # from the operator and create it via the WP-CLI bridge if absent.+ wp_user = (wp_site.admin_user if wp_site and wp_site.admin_user else None)+ if not wp_user:+ wp_user = (operator.username or operator.email.split('@')[0])+ exists = WordPressService.wp_cli(app.root_path, ['user', 'get', wp_user, '--field=ID'])+ if not exists.get('success'):+ created = WordPressService.create_user(+ app.root_path, wp_user, operator.email, role='administrator'+ )+ if not created.get('success'):+ return jsonify({'error': created.get('error') or 'Failed to provision admin'}), 400+ if wp_site:+ wp_site.admin_user = wp_user+ if not wp_site.admin_email:+ wp_site.admin_email = operator.email+ db.session.commit()++ result = WordPressService.create_login_url(app.root_path, wp_user)+ if not result.get('success'):+ return jsonify({'error': result.get('error') or 'Failed to create login URL'}), 400++ AuditService.log(+ action='wordpress.admin_login',+ user_id=current_user_id,+ target_type='app',+ target_id=app.id,+ details={'wp_user': wp_user, 'site_id': site_id, 'app_name': app.name},+ )++ return jsonify({'success': True, 'url': result['url']}), 200++@wordpress_bp.route('/sites/<int:app_id>/users/<user>/reset-password', methods=['POST'])@jwt_required()@admin_requireddiff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.pyindex ada77465..6f827abf 100644--- a/backend/app/models/wordpress_site.py+++ b/backend/app/models/wordpress_site.py@@ -62,6 +62,9 @@ class WordPressSite(db.Model):# Resource limits (stored as JSON for flexibility)resource_limits = db.Column(db.Text) # JSON: {memory, cpus, db_memory, db_cpus}+ # Tags / labels for agency organization (stored as JSON array of strings)+ tags = db.Column(db.Text) # JSON: ["client-acme", "retainer", "php8"]+# Basic Authbasic_auth_enabled = db.Column(db.Boolean, default=False)basic_auth_user = db.Column(db.String(100))@@ -134,6 +137,7 @@ class WordPressSite(db.Model):'compose_project_name': self.compose_project_name,'container_prefix': self.container_prefix,'resource_limits': json.loads(self.resource_limits) if self.resource_limits else None,+ 'tags': json.loads(self.tags) if self.tags else [],'basic_auth_enabled': self.basic_auth_enabled,'basic_auth_user': self.basic_auth_user,'health_status': self.health_status,diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.pyindex d310820c..df57d180 100644--- a/backend/app/services/wordpress_service.py+++ b/backend/app/services/wordpress_service.py@@ -212,6 +212,16 @@ define('WP_AUTO_UPDATE_CORE', 'minor');except Exception as e:return {'success': False, 'error': str(e)}+ @classmethod+ def is_multisite(cls, path: str) -> bool:+ """Return True if the WordPress install at ``path`` is a multisite network.++ Uses ``wp core is-multisite`` (exit 0 = multisite, non-zero = single).+ Routes through the Docker-aware wp_cli bridge automatically.+ """+ result = cls.wp_cli(path, ['core', 'is-multisite'])+ return bool(result.get('success'))+@classmethoddef get_wordpress_info(cls, path: str) -> Optional[Dict]:"""Get WordPress installation info."""@@ -250,6 +260,9 @@ define('WP_AUTO_UPDATE_CORE', 'minor');if email_result['success']:info['admin_email'] = email_result['output'].strip()+ # Detect multisite (wp core is-multisite: exit 0 = multisite)+ info['multisite'] = cls.is_multisite(path)+return info@classmethod@@ -720,6 +733,40 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]return {'success': True, 'message': 'Password reset', 'password': password}return result+ @classmethod+ def _get_login_url_slug(cls, path: str) -> str:+ """Return the site's real login URL (avoids hardcoding /wp-admin)."""+ res = cls.wp_cli(path, ['eval', 'echo wp_login_url();'])+ if res.get('success') and res.get('output', '').strip():+ return res['output'].strip()+ return ''++ @classmethod+ def _ensure_login_package(cls, path: str) -> Dict:+ """Make the wp-cli-login command + its launcher available, idempotently."""+ have = cls.wp_cli(path, ['login', '--help'])+ if not have.get('success'):+ inst = cls.wp_cli(path, ['package', 'install', 'aaemnnosttv/wp-cli-login-command'])+ if not inst.get('success'):+ return {'success': False, 'error': 'Failed to install wp-cli-login package: ' + (inst.get('error') or '')}+ # Ensure the companion launcher mu-plugin is present (idempotent).+ cls.wp_cli(path, ['login', 'install', '--yes'])+ return {'success': True}++ @classmethod+ def create_login_url(cls, path: str, user: str) -> Dict:+ """Mint a one-time passwordless wp-admin login URL for ``user``."""+ pkg = cls._ensure_login_package(path)+ if not pkg.get('success'):+ return pkg+ res = cls.wp_cli(path, ['login', 'create', user, '--url-only'])+ if res.get('success'):+ url = (res.get('output') or '').strip()+ if not url:+ return {'success': False, 'error': 'Login URL was empty'}+ return {'success': True, 'url': url, 'login_slug': cls._get_login_url_slug(path)}+ return res+@staticmethoddef _generate_password(length: int = 16) -> str:"""Generate a secure random password."""@@ -1014,6 +1061,16 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]site_data = site.to_dict(include_environments=True)cls._enrich_site_data(site, site_data)+ # Refresh the multisite flag from reality (single-site detail only;+ # never added to the hot list endpoint get_sites). One cheap wp_cli probe.+ if site.application and site.application.root_path:+ detected = cls.is_multisite(site.application.root_path)+ if detected != site.multisite:+ site.multisite = detected+ from app import db+ db.session.commit()+ site_data['multisite'] = detected+# Also enrich environment dataif 'environments' in site_data:for env_data in site_data['environments']:@@ -1092,6 +1149,10 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]'finalized. Complete setup via the WordPress wizard.')+ # Detect multisite from the freshly installed site (cheap one-shot;+ # only meaningful if the automated install finalized).+ multisite = cls.is_multisite(app.root_path) if admin_password else False+# Create WordPressSite recordwp_site = WordPressSite(application_id=app.id,@@ -1100,7 +1161,8 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]is_production=True,environment_type='production',wp_version='6.4',- compose_project_name=safe_name+ compose_project_name=safe_name,+ multisite=multisite)db.session.add(wp_site)db.session.commit()diff --git a/backend/migrations/versions/009_wordpress_site_tags.py b/backend/migrations/versions/009_wordpress_site_tags.pynew file mode 100644index 00000000..a2a054af--- /dev/null+++ b/backend/migrations/versions/009_wordpress_site_tags.py@@ -0,0 +1,42 @@+"""Add tags column to wordpress_sites for agency organization.++Stored as JSON-encoded TEXT (a JSON array of strings), matching the+existing sync_config / resource_limits / git_paths columns.++Idempotent: MigrationService._fix_missing_columns may have already added+this column on boot before Alembic runs, so guard on the live schema.++Revision ID: 009_wordpress_site_tags+Revises: 008_fix_server_metrics_id_type+Create Date: 2026-05-31+"""+from alembic import op+import sqlalchemy as sa++revision = '009_wordpress_site_tags'+down_revision = '008_fix_server_metrics_id_type'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ if 'wordpress_sites' not in inspector.get_table_names():+ # Fresh install: create_all() produces the column from the model.+ return+ existing_cols = {c['name'] for c in inspector.get_columns('wordpress_sites')}+ if 'tags' not in existing_cols:+ with op.batch_alter_table('wordpress_sites') as batch_op:+ batch_op.add_column(sa.Column('tags', sa.Text(), nullable=True))+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ if 'wordpress_sites' not in inspector.get_table_names():+ return+ existing_cols = {c['name'] for c in inspector.get_columns('wordpress_sites')}+ if 'tags' in existing_cols:+ with op.batch_alter_table('wordpress_sites') as batch_op:+ batch_op.drop_column('tags')diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex 1900443a..ddf1c6e2 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -163,7 +163,7 @@ These are the features that make a user say "this is a managed platform, not a f- **Reuse:** everything from Phase 0 + #8.- **Done when:** One wizard produces a hardened, TLS'd, admin-ready site on a real domain.-### #16 — Passwordless WP-admin login (the signature feature) `[M]` ❌+### #16 — Passwordless WP-admin login (the signature feature) `[M]` ❌ — ✅ Done (WP-CLI magic link; needs container egress to install the wp-cli-login package once)- **Today:** "Open WP Admin" is a dumb `window.open` to `{site.url}/wp-admin`. Grep confirms **zero** login/magic/token/SSO code in the WP API. `create_user` (`:646`) and `reset_password` (`:666`) exist, so managed-admin provisioning is half-done.- **Do (no heavy plugin — WP-CLI bridge):**1. Mint a one-time URL via `wp package install wp-cli/login-command` then `wp login create <user> --url-only` (or a ~30-line mu-plugin validating an HMAC nonce).@@ -186,13 +186,13 @@ These are the features that make a user say "this is a managed platform, not a f- **Reuse:** `create_environment` internals, `db_sync_service`.- **Done when:** "Clone" yields an independent site with its own credentials.-### #19 — Multisite detection `[S]` 🟡+### #19 — Multisite detection `[S]` 🟡 — ✅ Done- **Today:** `WordPressSite.multisite` is a decorative boolean (`models/wordpress_site.py:25`), never populated from reality.- **Do:** Populate it via `wp core is-multisite` during create/health.- **Reuse:** `wp_cli`.- **Done when:** The flag reflects the actual install.-### #20 — Site labels / tags (agency organization) `[S]` ❌+### #20 — Site labels / tags (agency organization) `[S]` ❌ — ✅ Done- **Today:** No tags/labels/client/group field on `WordPressSite`; UI renders no chips.- **Do:** Add a `tags` (and optional `client`/`group`) field + UI chips + filtering on the sites list.- **Reuse:** `WordPressSite.to_dict`, `WordPressSiteCard.jsx`.diff --git a/frontend/src/pages/WordPress.jsx b/frontend/src/pages/WordPress.jsxindex 434728cc..3977afe6 100644--- a/frontend/src/pages/WordPress.jsx+++ b/frontend/src/pages/WordPress.jsx@@ -15,6 +15,7 @@ import { Badge } from '@/components/ui/badge';function WordPress() {const [sites, setSites] = useState([]);const [loading, setLoading] = useState(true);+ const [activeTag, setActiveTag] = useState(null); // null = show allconst [showCreateModal, setShowCreateModal] = useState(false);const [createLoading, setCreateLoading] = useState(false);const [createForm, setCreateForm] = useState({ name: '', adminEmail: '' });@@ -158,8 +159,32 @@ function WordPress() {}/>) : (+ <>+ {(() => {+ const allTags = Array.from(new Set(sites.flatMap(s => s.tags || []))).sort();+ if (allTags.length === 0) return null;+ return (+ <div className="wp-tag-filter">+ <button+ className={`wp-tag-chip wp-tag-chip--filter ${activeTag === null ? 'is-active' : ''}`}+ onClick={() => setActiveTag(null)}+ >+ All+ </button>+ {allTags.map(tag => (+ <button+ key={tag}+ className={`wp-tag-chip wp-tag-chip--filter ${activeTag === tag ? 'is-active' : ''}`}+ onClick={() => setActiveTag(tag)}+ >+ {tag}+ </button>+ ))}+ </div>+ );+ })()}<div className="wp-sites-grid">- {sites.map(site => (+ {sites.filter(site => activeTag === null || (site.tags || []).includes(activeTag)).map(site => (<divkey={site.id}className="wp-site-card"@@ -195,6 +220,13 @@ function WordPress() {<span className="meta-value">{(site.environment_count || 0) + 1}</span></div></div>+ {site.tags && site.tags.length > 0 && (+ <div className="wp-site-tags">+ {site.tags.map(tag => (+ <span key={tag} className="wp-tag-chip">{tag}</span>+ ))}+ </div>+ )}{site.url && site.status === 'running' && (<div className="wp-site-card-links"><a@@ -223,6 +255,7 @@ function WordPress() {</div>))}</div>+ </>)}{/* Create Site Modal */}diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex 958eec03..55976b35 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -80,6 +80,7 @@ const WordPressDetail = () => {const [site, setSite] = useState(null);const [loading, setLoading] = useState(true);const [activeTab, setActiveTab] = useTabParam(`/wordpress/${id}`, VALID_TABS);+ const [autoLoggingIn, setAutoLoggingIn] = useState(false);useEffect(() => {loadSite();@@ -97,6 +98,23 @@ const WordPressDetail = () => {}}+ async function handleAutoLogin() {+ setAutoLoggingIn(true);+ toast.info('Creating one-time login link...', { duration: 3000 });+ try {+ const res = await wordpressApi.autoLogin(site.id);+ if (res && res.url) {+ window.open(res.url, '_blank', 'noopener,noreferrer');+ } else {+ toast.error('No login URL returned');+ }+ } catch (err) {+ toast.error(err.message || 'Failed to create login link');+ } finally {+ setAutoLoggingIn(false);+ }+ }+if (loading) {return <DetailPageSkeleton />;}@@ -175,6 +193,15 @@ const WordPressDetail = () => {</Button></>)}+ <Button+ variant="default"+ onClick={handleAutoLogin}+ disabled={autoLoggingIn}+ title="Open wp-admin logged in, no password (one-time link)"+ >+ <Lock size={16} />+ {autoLoggingIn ? 'Signing in...' : 'Auto Login'}+ </Button></div></div>diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex 7a8451d7..c6133381 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -13,6 +13,12 @@ const wordpressApi = {getSite: (id) => api.request(`${BASE_PATH}/${id}`),+ // Replace the tag list for a site (agency organization labels)+ setTags: (id, tags) => api.request(`${BASE_PATH}/${id}/tags`, {+ method: 'PATCH',+ body: { tags }+ }),+// Deletes the site and all environments. A final files+DB backup is taken// by default (pass { createBackup: false } to skip).deleteSite: (id, { createBackup = true } = {}) => api.request(@@ -136,6 +142,11 @@ const wordpressApi = {method: 'POST'}),+ // Mint a one-time passwordless wp-admin login URL for the current operator.+ autoLogin: (siteId) => api.request(`${BASE_PATH}/${siteId}/login`, {+ method: 'POST'+ }),+// Clone Database (for advanced use)cloneDatabase: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/clone-db`, {method: 'POST',diff --git a/frontend/src/styles/pages/_wordpress.scss b/frontend/src/styles/pages/_wordpress.scssindex fa6954eb..8b84bd63 100644--- a/frontend/src/styles/pages/_wordpress.scss+++ b/frontend/src/styles/pages/_wordpress.scss@@ -151,6 +151,44 @@padding: $space-4;}+// Site tags / labels (chips + filter bar)+.wp-tag-filter {+ display: flex;+ flex-wrap: wrap;+ gap: $space-2;+ margin: 0 $space-4 $space-4;+}++.wp-site-tags {+ display: flex;+ flex-wrap: wrap;+ gap: $space-1;+ margin-top: $space-3;+}++.wp-tag-chip {+ display: inline-flex;+ align-items: center;+ padding: 2px 10px;+ font-size: $font-size-xs;+ line-height: 1.4;+ border-radius: $radius-full;+ background: $bg-tertiary;+ color: $text-secondary;+ border: 1px solid $border-subtle;++ &--filter {+ cursor: pointer;+ background: $bg-card;++ &.is-active {+ background: $color-primary;+ color: #fff;+ border-color: $color-primary;+ }+ }+}+// Site Card.wp-site-card {background: $bg-card;