| 1 | import { v4 as uuid } from 'uuid';
|
|---|
| 2 | import db from '../config/database.js';
|
|---|
| 3 |
|
|---|
| 4 | // A Klonkt instance should ALWAYS have a primary site — it carries the identity
|
|---|
| 5 | // (title, theme, profile) and is the anchor point in solo/hub/circle mode.
|
|---|
| 6 | // The register flow already creates one, but an admin created via a script
|
|---|
| 7 | // (or an empty sites table for any reason) left the instance without a site:
|
|---|
| 8 | // no settings, dashboard would crash.
|
|---|
| 9 | //
|
|---|
| 10 | // This helper runs at boot (and is idempotent): as soon as there is an admin
|
|---|
| 11 | // but no site yet, it creates a default site owned by the first god/admin.
|
|---|
| 12 | // Tenancy-agnostic — applies to solo, hub, and circle.
|
|---|
| 13 |
|
|---|
| 14 | function defaultTitle() {
|
|---|
| 15 | try {
|
|---|
| 16 | const base = process.env.PUBLIC_BASE_URL;
|
|---|
| 17 | if (base) {
|
|---|
| 18 | const host = new URL(base).hostname.replace(/^www\./, '');
|
|---|
| 19 | const label = host.split('.')[0];
|
|---|
| 20 | if (label) return label.charAt(0).toUpperCase() + label.slice(1);
|
|---|
| 21 | }
|
|---|
| 22 | } catch { /* fall back to generic */ }
|
|---|
| 23 | return 'Mijn site';
|
|---|
| 24 | }
|
|---|
| 25 |
|
|---|
| 26 | export function ensurePrimarySite() {
|
|---|
| 27 | const count = db.prepare('SELECT COUNT(*) AS c FROM sites').get().c;
|
|---|
| 28 | if (count > 0) return null; // a site already exists — nothing to do
|
|---|
| 29 |
|
|---|
| 30 | const owner = db.prepare(
|
|---|
| 31 | "SELECT id FROM users WHERE role IN ('god','admin') ORDER BY created_at LIMIT 1"
|
|---|
| 32 | ).get();
|
|---|
| 33 | if (!owner) return null; // no admin yet -> no owner, nothing to create
|
|---|
| 34 |
|
|---|
| 35 | const siteId = uuid();
|
|---|
| 36 | const slug = 'main'; // not reserved; in solo mode the primary site is always pinned anyway
|
|---|
| 37 | db.prepare(`
|
|---|
| 38 | INSERT INTO sites (
|
|---|
| 39 | id, slug, title, description, tagline, owner_id,
|
|---|
| 40 | language, palette, accent, profile_photo,
|
|---|
| 41 | is_public, robots_index, require_login_to_comment, enable_audio_player,
|
|---|
| 42 | feed_view_default, is_primary
|
|---|
| 43 | ) VALUES (?, ?, ?, '', '', ?, 'en', 'klonkt', '#e8b04b', NULL, 1, 1, 1, 1, 'grid', 1)
|
|---|
| 44 | `).run(siteId, slug, defaultTitle(), owner.id);
|
|---|
| 45 |
|
|---|
| 46 | // site_members-entry zodat de owner door canAdminSite-checks komt.
|
|---|
| 47 | db.prepare(
|
|---|
| 48 | "INSERT INTO site_members (site_id, user_id, role) VALUES (?, ?, 'admin')"
|
|---|
| 49 | ).run(siteId, owner.id);
|
|---|
| 50 |
|
|---|
| 51 | console.log(`[ensurePrimarySite] standaard-site '${slug}' aangemaakt (owner ${owner.id})`);
|
|---|
| 52 | return { siteId, slug };
|
|---|
| 53 | }
|
|---|