source: Klonkt/src/config/database.js@ 6117035

main
Last change on this file since 6117035 was 640b39c, checked in by roboburr <roboburr@â€Ļ>, 3 months ago

auth: read-only view accounts (view everything, modify nothing)

New users.readonly column + readonly in the session. Global guard in server.js
blocks every state-modifying method (POST/PUT/PATCH/DELETE) for read-only
accounts -> no comments, saves, settings, nothing. GET remains free, so they
can view everything (including admin panels). Sticky "read-only demo" banner in
the shell when such an account is logged in.

Co-Authored-By: Claude <noreply@â€Ļ>

  • Property mode set to 100644
File size: 5.3 KB
Line 
1import Database from 'better-sqlite3';
2import path from 'path';
3import { fileURLToPath } from 'url';
4import fs from 'fs';
5
6const __dirname = path.dirname(fileURLToPath(import.meta.url));
7const dbPath = process.env.DATABASE_PATH || path.join(__dirname, '../../storage/database.sqlite');
8
9// Ensure storage directory exists
10const storageDir = path.dirname(dbPath);
11if (!fs.existsSync(storageDir)) {
12 fs.mkdirSync(storageDir, { recursive: true });
13}
14
15// Initialize database
16const db = new Database(dbPath);
17db.pragma('journal_mode = WAL');
18db.pragma('foreign_keys = ON');
19
20export function initializeDatabase() {
21 const tableExists = db.prepare(`
22 SELECT name FROM sqlite_master WHERE type='table' AND name='users'
23 `).get();
24
25 if (!tableExists) {
26 console.log('🔧 Initializing database schema...');
27 const schemaPath = path.join(__dirname, '..', 'db', 'migrations', '001-init.sql');
28 const schema = fs.readFileSync(schemaPath, 'utf-8');
29 db.exec(schema);
30 console.log('✅ Database initialized with v9-soul schema');
31 }
32
33 // Additive column migrations — safe to run every boot.
34 // SQLite throws if the column already exists; we swallow that.
35 ensureColumn('sites', 'enable_audio_player', 'INTEGER DEFAULT 1');
36 ensureColumn('sites', 'profile_photo', 'TEXT');
37 ensureColumn('audio_tracks', 'cover_url', 'TEXT');
38 ensureColumn('audio_tracks', 'album', 'TEXT');
39 ensureColumn('users', 'reset_token', 'TEXT');
40 ensureColumn('users', 'reset_token_expires', 'DATETIME');
41 // Google OAuth: koppel een Google-account aan een user (login via Google).
42 ensureColumn('users', 'google_sub', 'TEXT');
43 // Read-only/kijk-account: kan alles bekijken maar geen wijzigingen doen.
44 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
45 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
46 ensureColumn('sites', 'comments_moderation_mode', "TEXT DEFAULT 'trust'");
47 // Per-site Prutter toggle: when off, DM endpoints/UI are hidden for that site.
48 ensureColumn('sites', 'enable_prutter', 'INTEGER DEFAULT 1');
49
50 // v9 audit additions —————————————————————————————————————————
51 // SEO/social columns the v9 template uses (most live in 001-init.sql already
52 // for fresh DBs but ensureColumn is idempotent for existing DBs).
53 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
54 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
55 ensureColumn('sites', 'publisher_name', 'TEXT');
56 ensureColumn('sites', 'publisher_url', 'TEXT');
57 ensureColumn('sites', 'publisher_logo', 'TEXT');
58 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
59 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
60 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
61 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
62 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'timeline'"); // timeline | grid
63 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
64 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
65 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
66
67 // Per-post noindex + type
68 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
69 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
70
71 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
72 // idempotent so it's safe to run on every boot regardless of DB age.
73 db.exec(`
74 CREATE TABLE IF NOT EXISTS playlists (
75 id TEXT PRIMARY KEY,
76 site_id TEXT NOT NULL,
77 title TEXT NOT NULL,
78 artist TEXT,
79 year INTEGER,
80 cover_url TEXT,
81 kind TEXT DEFAULT 'album',
82 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
83 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
84 FOREIGN KEY (site_id) REFERENCES sites(id)
85 );
86 CREATE TABLE IF NOT EXISTS playlist_tracks (
87 playlist_id TEXT NOT NULL,
88 track_id TEXT NOT NULL,
89 position INTEGER NOT NULL DEFAULT 0,
90 PRIMARY KEY (playlist_id, track_id),
91 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
92 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
93 );
94 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
95 ON playlist_tracks(playlist_id, position);
96 `);
97
98 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
99 // (solo = ÊÊn site, hub = bedrijfssite + /user/). Default = solo.
100 db.exec(`
101 CREATE TABLE IF NOT EXISTS app_settings (
102 key TEXT PRIMARY KEY,
103 value TEXT,
104 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
105 );
106 `);
107 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
108}
109
110function ensureColumn(table, column, definition) {
111 try {
112 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
113 console.log(`🔧 Added column ${table}.${column}`);
114 } catch (e) {
115 // "duplicate column name" → already there. Anything else, surface it.
116 if (!/duplicate column/i.test(e.message)) {
117 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
118 }
119 }
120}
121
122export default db;
Note: See TracBrowser for help on using the repository browser.