diff --git a/server-db.ts b/server-db.ts index 697fa7d..ec3660c 100644 --- a/server-db.ts +++ b/server-db.ts @@ -70,6 +70,12 @@ db.exec(` createdBy TEXT, createdAt TEXT NOT NULL ); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT DEFAULT (datetime('now')) + ); `); // Lightweight migrations for columns added after the initial release. @@ -83,4 +89,32 @@ function ensureColumn(table: string, column: string, ddl: string) { ensureColumn('devices', 'checkMkUrl', "checkMkUrl TEXT NOT NULL DEFAULT ''"); +// Seed default settings (INSERT OR IGNORE = only if key absent) +const _insertDefault = db.prepare('INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)'); +const _defaultSettings: [string, string][] = [ + ['azure_enabled', 'false'], + ['azure_client_id', ''], + ['azure_tenant_id', ''], + ['azure_client_secret', ''], + ['azure_redirect_uri', ''], + ['checkmk_api_url', ''], + ['checkmk_api_secret', ''], + ['checkmk_sync_interval_ms', '60000'], +]; +for (const [k, v] of _defaultSettings) _insertDefault.run(k, v); + +export function getSetting(key: string): string { + const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as { value: string } | undefined; + return row?.value ?? ''; +} + +export function setSetting(key: string, value: string): void { + db.prepare("INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES (?, ?, datetime('now'))").run(key, value); +} + +export function getAllSettings(): Record { + const rows = db.prepare('SELECT key, value FROM settings').all() as { key: string; value: string }[]; + return Object.fromEntries(rows.map(r => [r.key, r.value])); +} + export default db; diff --git a/server.ts b/server.ts index db174fe..be9078f 100644 --- a/server.ts +++ b/server.ts @@ -4,7 +4,8 @@ import path from 'path'; import { createServer as createViteServer } from 'vite'; import bcrypt from 'bcryptjs'; import jwt from 'jsonwebtoken'; -import db from './server-db'; +import { ConfidentialClientApplication } from '@azure/msal-node'; +import db, { getSetting, setSetting, getAllSettings } from './server-db'; import { Device, LabTemplate, Booking, LogEntry, User, QuickLink } from './src/types'; const uid = (prefix: string) => `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; @@ -41,6 +42,35 @@ function requireAuth(req: Request, res: Response, next: NextFunction) { } } +function requireAdmin(req: Request, res: Response, next: NextFunction) { + const row = db.prepare('SELECT role FROM users WHERE id = ?').get(req.user!.userId) as { role: string } | undefined; + if (!row || row.role.toLowerCase() !== 'admin') { + res.status(403).json({ error: 'Admin access required.' }); + return; + } + next(); +} + +function getMsalClient(): ConfidentialClientApplication | null { + const clientId = getSetting('azure_client_id'); + const tenantId = getSetting('azure_tenant_id'); + const secret = getSetting('azure_client_secret'); + if (getSetting('azure_enabled') !== 'true' || !clientId || !tenantId || !secret) return null; + return new ConfidentialClientApplication({ + auth: { clientId, authority: `https://login.microsoftonline.com/${tenantId}`, clientSecret: secret }, + }); +} + +const SECRET_KEYS = ['azure_client_secret', 'checkmk_api_secret']; + +function maskSettings(raw: Record): Record { + const out = { ...raw }; + for (const k of SECRET_KEYS) { + if (out[k]) out[k] = '__SET__'; + } + return out; +} + async function startServer() { const app = express(); const PORT = Number(process.env.PORT) || 3000; @@ -113,6 +143,104 @@ async function startServer() { } }); + // Public: frontend checks this before rendering the Azure login button + app.get('/api/auth/config', (_req, res) => { + const enabled = getSetting('azure_enabled') === 'true'; + const clientId = getSetting('azure_client_id'); + const tenantId = getSetting('azure_tenant_id'); + const secret = getSetting('azure_client_secret'); + res.json({ azureEnabled: enabled && Boolean(clientId) && Boolean(tenantId) && Boolean(secret) }); + }); + + // Start Azure OAuth flow + app.get('/api/auth/azure', async (_req, res) => { + const msalClient = getMsalClient(); + if (!msalClient) { + return res.redirect('/?auth_error=Azure+Login+nicht+konfiguriert'); + } + const appUrl = process.env.APP_URL || `http://localhost:${PORT}`; + const redirectUri = getSetting('azure_redirect_uri') || `${appUrl}/api/auth/azure/callback`; + try { + const authCodeUrl = await msalClient.getAuthCodeUrl({ + scopes: ['openid', 'profile', 'email'], + redirectUri, + }); + res.redirect(authCodeUrl); + } catch (err: any) { + console.error('[Azure Auth] getAuthCodeUrl error:', err); + res.redirect('/?auth_error=Microsoft+Login+konnte+nicht+gestartet+werden'); + } + }); + + // Azure OAuth callback + app.get('/api/auth/azure/callback', async (req, res) => { + const { code, error, error_description } = req.query; + if (error) { + const msg = encodeURIComponent(String(error_description || error)); + return res.redirect(`/?auth_error=${msg}`); + } + if (!code) { + return res.redirect('/?auth_error=Kein+Autorisierungscode+erhalten'); + } + const msalClient = getMsalClient(); + if (!msalClient) { + return res.redirect('/?auth_error=Azure+Login+nicht+konfiguriert'); + } + const appUrl = process.env.APP_URL || `http://localhost:${PORT}`; + const redirectUri = getSetting('azure_redirect_uri') || `${appUrl}/api/auth/azure/callback`; + try { + const result = await msalClient.acquireTokenByCode({ + code: String(code), + scopes: ['openid', 'profile', 'email'], + redirectUri, + }); + const email = (result.account?.username ?? '').toLowerCase(); + const name = result.account?.name || email; + if (!email) { + return res.redirect('/?auth_error=Keine+E-Mail+von+Microsoft+erhalten'); + } + let user = db.prepare('SELECT id, name, role, email FROM users WHERE email = ?').get(email) as User | undefined; + if (!user) { + const id = uid("u"); + db.prepare('INSERT INTO users (id, name, role, email, password_hash) VALUES (?, ?, ?, ?, ?)') + .run(id, name, 'User', email, ''); + user = db.prepare('SELECT id, name, role, email FROM users WHERE id = ?').get(id) as User; + } + const token = jwt.sign({ userId: user.id, email: user.email }, JWT_SECRET, { expiresIn: JWT_EXPIRY }); + res.redirect(`/?token=${encodeURIComponent(token)}`); + } catch (err: any) { + console.error('[Azure Auth] acquireTokenByCode error:', err); + res.redirect('/?auth_error=Authentifizierung+fehlgeschlagen'); + } + }); + + // ------------------------------------------------------------- + // RESTFUL API: Settings (admin only) + // ------------------------------------------------------------- + app.get('/api/settings', requireAuth, requireAdmin, (_req, res) => { + try { + res.json(maskSettings(getAllSettings())); + } catch (err: any) { + res.status(500).json({ error: err.message }); + } + }); + + app.put('/api/settings', requireAuth, requireAdmin, (req, res) => { + try { + const allowed = ['azure_enabled', 'azure_client_id', 'azure_tenant_id', 'azure_client_secret', + 'azure_redirect_uri', 'checkmk_api_url', 'checkmk_api_secret', 'checkmk_sync_interval_ms']; + const updates = req.body as Record; + for (const key of allowed) { + if (key in updates && updates[key] !== '__SET__') { + setSetting(key, String(updates[key])); + } + } + res.json(maskSettings(getAllSettings())); + } catch (err: any) { + res.status(500).json({ error: err.message }); + } + }); + // ------------------------------------------------------------- // RESTFUL API: Users // ------------------------------------------------------------- @@ -511,11 +639,13 @@ async function startServer() { // Until CHECKMK_API_URL/SECRET are configured, devices stay 'unknown' (and // therefore not bookable) - which is the intended safe default. // ------------------------------------------------------------- - const CHECKMK_SYNC_INTERVAL_MS = Number(process.env.CHECKMK_SYNC_INTERVAL_MS) || 60_000; - const CHECKMK_API_URL = process.env.CHECKMK_API_URL; // e.g. https://checkmk.internal//check_mk/api/1.0 - const CHECKMK_API_SECRET = process.env.CHECKMK_API_SECRET; // automation user secret + // Sync interval: DB setting takes precedence over env var + const CHECKMK_SYNC_INTERVAL_MS = Number(getSetting('checkmk_sync_interval_ms') || process.env.CHECKMK_SYNC_INTERVAL_MS) || 60_000; async function syncCheckMkStatuses() { + // DB settings take precedence; fall back to env vars for backwards compatibility + const CHECKMK_API_URL = getSetting('checkmk_api_url') || process.env.CHECKMK_API_URL; + const CHECKMK_API_SECRET = getSetting('checkmk_api_secret') || process.env.CHECKMK_API_SECRET; if (!CHECKMK_API_URL || !CHECKMK_API_SECRET) return; // not configured - leave statuses as 'unknown' const rows = db.prepare("SELECT id, hostname, checkMkUrl FROM devices WHERE checkMkUrl != ''") .all() as { id: string; hostname: string; checkMkUrl: string }[]; diff --git a/src/App.tsx b/src/App.tsx index 0f6fee2..5e22c77 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -12,10 +12,11 @@ import UserDirectory from './components/UserDirectory'; import BookingDetailsModal from './components/BookingDetailsModal'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; +import Settings from './components/Settings'; import { LayoutDashboard, Calendar, Server, Layers, History, Link as LinkIcon, Users, - PanelLeftClose, PanelLeftOpen, + PanelLeftClose, PanelLeftOpen, Settings2, } from 'lucide-react'; type AuthView = 'login' | 'register'; @@ -47,6 +48,7 @@ export default function App() { localStorage.setItem('ghostgrid_nav_collapsed', navCollapsed ? '1' : '0'); }, [navCollapsed]); + const [oauthError, setOauthError] = useState(''); const [notifications, setNotifications] = useState([]); const [remindedBookings, setRemindedBookings] = useState>(new Set()); @@ -59,14 +61,46 @@ export default function App() { localStorage.setItem('ghostgrid_theme', theme); }, [theme]); - // Verify stored token on startup + // Verify stored token on startup + handle OAuth callback (?token= / ?auth_error=) useEffect(() => { async function verifyToken() { - const token = getToken(); + // Handle OAuth redirect params first + const params = new URLSearchParams(window.location.search); + const urlToken = params.get('token'); + const urlError = params.get('auth_error'); + if (urlToken || urlError) { + window.history.replaceState({}, '', '/'); + } + if (urlError) { + setOauthError(decodeURIComponent(urlError)); + setAuthChecked(true); + return; + } + + const token = urlToken || getToken(); if (!token) { setAuthChecked(true); return; } + if (urlToken) { + // Token came from OAuth callback – verify and persist + try { + const res = await fetch('/api/auth/me', { headers: { Authorization: `Bearer ${urlToken}` } }); + if (res.ok) { + const user = await res.json(); + const { saveSession } = await import('./lib/auth'); + saveSession(urlToken, user); + setCurrentUser(user); + } else { + setOauthError('Anmeldung fehlgeschlagen. Bitte erneut versuchen.'); + } + } catch { + setOauthError('Server nicht erreichbar.'); + } finally { + setAuthChecked(true); + } + return; + } try { const res = await authFetch('/api/auth/me'); if (res.ok) { @@ -337,6 +371,8 @@ export default function App() { setActiveTab('devices'); }; + const isAdmin = currentUser?.role?.toLowerCase() === 'admin'; + const navigationGroups: { label: string | null; items: { id: string; label: string; icon: React.ReactNode }[] }[] = [ { label: null, @@ -365,6 +401,12 @@ export default function App() { { id: 'logs', label: 'Logbook', icon: }, ], }, + ...(isAdmin ? [{ + label: 'System', + items: [ + { id: 'settings', label: 'Einstellungen', icon: }, + ], + }] : []), ]; // Startup check not done yet @@ -386,7 +428,7 @@ export default function App() { if (authView === 'register') { return setAuthView('login')} />; } - return setAuthView('register')} />; + return setAuthView('register')} authError={oauthError} />; } // Loading data after login @@ -561,6 +603,9 @@ export default function App() { onAddLog={handleAddLogManually} /> )} + {activeTab === 'settings' && ( + + )} diff --git a/src/components/LoginPage.tsx b/src/components/LoginPage.tsx index 9a81263..357b60f 100644 --- a/src/components/LoginPage.tsx +++ b/src/components/LoginPage.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; import { GhostGridLogo } from './Header'; import { authFetch, saveSession } from '../lib/auth'; import { User } from '../types'; @@ -7,14 +7,23 @@ import { LogIn, Eye, EyeOff, AlertCircle } from 'lucide-react'; interface LoginPageProps { onLogin: (user: User) => void; onNavigateToRegister: () => void; + authError?: string; } -export default function LoginPage({ onLogin, onNavigateToRegister }: LoginPageProps) { +export default function LoginPage({ onLogin, onNavigateToRegister, authError }: LoginPageProps) { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); - const [error, setError] = useState(''); + const [error, setError] = useState(authError || ''); const [loading, setLoading] = useState(false); + const [azureEnabled, setAzureEnabled] = useState(false); + + useEffect(() => { + fetch('/api/auth/config') + .then(r => r.json()) + .then(d => setAzureEnabled(Boolean(d.azureEnabled))) + .catch(() => {}); + }, []); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); @@ -137,6 +146,30 @@ export default function LoginPage({ onLogin, onNavigateToRegister }: LoginPagePr + {azureEnabled && ( + <> +
+
+ oder +
+
+ + + )} +

No account yet?{' '} +

+ ); +} + +export default function Settings({ currentUser }: SettingsProps) { + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(''); + const [successMsg, setSuccessMsg] = useState(''); + + // Entra ID + const [azureEnabled, setAzureEnabled] = useState(false); + const [azureClientId, setAzureClientId] = useState(''); + const [azureTenantId, setAzureTenantId] = useState(''); + const [azureClientSecret, setAzureClientSecret] = useState(''); + const [azureSecretSet, setAzureSecretSet] = useState(false); + const [azureRedirectUri, setAzureRedirectUri] = useState(''); + const [showAzureSecret, setShowAzureSecret] = useState(false); + + // CheckMK + const [checkmkApiUrl, setCheckmkApiUrl] = useState(''); + const [checkmkApiSecret, setCheckmkApiSecret] = useState(''); + const [checkmkSecretSet, setCheckmkSecretSet] = useState(false); + const [checkmkSyncInterval, setCheckmkSyncInterval] = useState('60000'); + const [showCheckmkSecret, setShowCheckmkSecret] = useState(false); + + useEffect(() => { loadSettings(); }, []); + + async function loadSettings() { + setLoading(true); + setError(''); + try { + const res = await authFetch('/api/settings'); + if (!res.ok) { setError('Einstellungen konnten nicht geladen werden.'); return; } + const data: RawSettings = await res.json(); + setAzureEnabled(data.azure_enabled === 'true'); + setAzureClientId(data.azure_client_id || ''); + setAzureTenantId(data.azure_tenant_id || ''); + setAzureSecretSet(data.azure_client_secret === SECRET_SENTINEL); + setAzureClientSecret(''); + setAzureRedirectUri(data.azure_redirect_uri || ''); + setCheckmkApiUrl(data.checkmk_api_url || ''); + setCheckmkSecretSet(data.checkmk_api_secret === SECRET_SENTINEL); + setCheckmkApiSecret(''); + setCheckmkSyncInterval(data.checkmk_sync_interval_ms || '60000'); + } catch { + setError('Netzwerkfehler beim Laden der Einstellungen.'); + } finally { + setLoading(false); + } + } + + async function handleSave() { + setSaving(true); + setError(''); + setSuccessMsg(''); + const payload: Record = { + azure_enabled: azureEnabled ? 'true' : 'false', + azure_client_id: azureClientId, + azure_tenant_id: azureTenantId, + azure_redirect_uri: azureRedirectUri, + checkmk_api_url: checkmkApiUrl, + checkmk_sync_interval_ms: checkmkSyncInterval, + }; + if (azureClientSecret) payload.azure_client_secret = azureClientSecret; + if (checkmkApiSecret) payload.checkmk_api_secret = checkmkApiSecret; + try { + const res = await authFetch('/api/settings', { method: 'PUT', body: JSON.stringify(payload) }); + if (!res.ok) { + const d = await res.json(); + setError(d.error || 'Speichern fehlgeschlagen.'); + return; + } + const data: RawSettings = await res.json(); + setAzureSecretSet(data.azure_client_secret === SECRET_SENTINEL); + setCheckmkSecretSet(data.checkmk_api_secret === SECRET_SENTINEL); + setAzureClientSecret(''); + setCheckmkApiSecret(''); + setSuccessMsg('Einstellungen gespeichert.'); + setTimeout(() => setSuccessMsg(''), 4000); + } catch { + setError('Netzwerkfehler beim Speichern.'); + } finally { + setSaving(false); + } + } + + if (currentUser.role.toLowerCase() !== 'admin') { + return ( +
+ +

Einstellungen sind nur für Administratoren zugänglich.

+
+ ); + } + + if (loading) { + return ( +
+ +
+ ); + } + + return ( +
+ + {/* Page header */} +
+
+ +
+
+

Einstellungen

+

Integrationen und Dienst-Konfigurationen

+
+
+ + {/* Feedback */} + {error && ( +
+ + {error} +
+ )} + {successMsg && ( +
+ + {successMsg} +
+ )} + + {/* Microsoft Entra ID */} +
+
+
+
+ +
+
+

Microsoft Entra ID

+

OAuth 2.0 Login für Organisationsaccounts

+
+
+ {/* Toggle */} + +
+ +
+
+ Tenant ID + +
+
+ Client ID (Application ID) + +
+
+ Client Secret + setShowAzureSecret(v => !v)} + /> +
+
+ Redirect URI (leer = automatisch) + +
+
+
+ + {/* CheckMK */} +
+
+
+ +
+
+

CheckMK

+

Geräte-Status-Synchronisation über die CheckMK REST API

+
+
+ +
+
+ API URL + +
+
+ Automation Secret + setShowCheckmkSecret(v => !v)} + /> +
+
+ Sync-Intervall (ms) + +
+
+
+ + {/* Save */} +
+ +
+
+ ); +}