feat: Entra ID login + settings page for integrations
- Add SQLite settings table with getSetting/setSetting/getAllSettings helpers - Implement Azure OAuth2 authorization code flow via @azure/msal-node - Add public GET /api/auth/config endpoint for frontend activation check - Add admin-only GET/PUT /api/settings API with masked secret fields - CheckMK sync reads credentials from DB settings (env vars as fallback) - New Settings.tsx: Entra ID and CheckMK configuration cards - LoginPage: "Sign in with Microsoft" button, shown only when Azure is active - App.tsx: OAuth callback handling (?token=/?auth_error=), Settings tab for admins
This commit is contained in:
34
server-db.ts
34
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<string, string> {
|
||||
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;
|
||||
|
||||
138
server.ts
138
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<string, string>): Record<string, string> {
|
||||
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<string, string>;
|
||||
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/<site>/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 }[];
|
||||
|
||||
53
src/App.tsx
53
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<string[]>([]);
|
||||
const [remindedBookings, setRemindedBookings] = useState<Set<string>>(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: <History className="w-4 h-4 shrink-0" /> },
|
||||
],
|
||||
},
|
||||
...(isAdmin ? [{
|
||||
label: 'System',
|
||||
items: [
|
||||
{ id: 'settings', label: 'Einstellungen', icon: <Settings2 className="w-4 h-4 shrink-0" /> },
|
||||
],
|
||||
}] : []),
|
||||
];
|
||||
|
||||
// Startup check not done yet
|
||||
@ -386,7 +428,7 @@ export default function App() {
|
||||
if (authView === 'register') {
|
||||
return <RegisterPage onLogin={handleLogin} onNavigateToLogin={() => setAuthView('login')} />;
|
||||
}
|
||||
return <LoginPage onLogin={handleLogin} onNavigateToRegister={() => setAuthView('register')} />;
|
||||
return <LoginPage onLogin={handleLogin} onNavigateToRegister={() => setAuthView('register')} authError={oauthError} />;
|
||||
}
|
||||
|
||||
// Loading data after login
|
||||
@ -561,6 +603,9 @@ export default function App() {
|
||||
onAddLog={handleAddLogManually}
|
||||
/>
|
||||
)}
|
||||
{activeTab === 'settings' && (
|
||||
<Settings currentUser={currentUser} />
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
|
||||
@ -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
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{azureEnabled && (
|
||||
<>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-1 h-px bg-slate-800" />
|
||||
<span className="text-[10px] font-mono text-slate-500 uppercase tracking-widest">oder</span>
|
||||
<div className="flex-1 h-px bg-slate-800" />
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { window.location.href = '/api/auth/azure'; }}
|
||||
className="w-full flex items-center justify-center gap-3 bg-slate-800 hover:bg-slate-700 border border-slate-700 hover:border-slate-600 text-white font-semibold text-sm py-2.5 rounded-lg transition-all"
|
||||
>
|
||||
{/* Microsoft M logo */}
|
||||
<svg width="18" height="18" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
||||
<rect x="1" y="1" width="9" height="9" fill="#F25022" />
|
||||
<rect x="11" y="1" width="9" height="9" fill="#7FBA00" />
|
||||
<rect x="1" y="11" width="9" height="9" fill="#00A4EF" />
|
||||
<rect x="11" y="11" width="9" height="9" fill="#FFB900" />
|
||||
</svg>
|
||||
Mit Microsoft anmelden
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="text-center text-xs text-slate-400">
|
||||
No account yet?{' '}
|
||||
<button
|
||||
|
||||
316
src/components/Settings.tsx
Normal file
316
src/components/Settings.tsx
Normal file
@ -0,0 +1,316 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { authFetch } from '../lib/auth';
|
||||
import { User } from '../types';
|
||||
import {
|
||||
Shield, Activity, Save, CheckCircle, AlertCircle, Eye, EyeOff, Settings2, Lock,
|
||||
} from 'lucide-react';
|
||||
|
||||
const SECRET_SENTINEL = '__SET__';
|
||||
|
||||
interface RawSettings {
|
||||
azure_enabled: string;
|
||||
azure_client_id: string;
|
||||
azure_tenant_id: string;
|
||||
azure_client_secret: string;
|
||||
azure_redirect_uri: string;
|
||||
checkmk_api_url: string;
|
||||
checkmk_api_secret: string;
|
||||
checkmk_sync_interval_ms: string;
|
||||
}
|
||||
|
||||
interface SettingsProps {
|
||||
currentUser: User;
|
||||
}
|
||||
|
||||
function FieldLabel({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1.5">{children}</label>
|
||||
);
|
||||
}
|
||||
|
||||
function TextInput({
|
||||
value, onChange, placeholder, disabled, monospace,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
monospace?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
className={`w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all disabled:opacity-50 disabled:cursor-not-allowed ${monospace ? 'font-mono' : ''}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SecretInput({
|
||||
value, onChange, alreadySet, show, onToggleShow, placeholder,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
alreadySet: boolean;
|
||||
show: boolean;
|
||||
onToggleShow: () => void;
|
||||
placeholder?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="relative">
|
||||
<input
|
||||
type={show ? 'text' : 'password'}
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
placeholder={alreadySet ? 'Bereits konfiguriert – leer lassen zum Behalten' : (placeholder ?? 'Neuen Wert eingeben')}
|
||||
className="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2.5 pr-10 text-sm text-white placeholder-slate-500 font-mono focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleShow}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-200 transition-colors"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{show ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<string, string> = {
|
||||
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 (
|
||||
<div className="flex flex-col items-center justify-center h-64 space-y-3">
|
||||
<Lock className="w-10 h-10 text-slate-600" />
|
||||
<p className="text-slate-400 text-sm">Einstellungen sind nur für Administratoren zugänglich.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<span className="w-5 h-5 border-2 border-slate-600 border-t-cyan-400 rounded-full animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-3xl">
|
||||
|
||||
{/* Page header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-slate-900 border border-slate-800 rounded-xl">
|
||||
<Settings2 className="w-5 h-5 text-cyan-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg font-bold text-white">Einstellungen</h1>
|
||||
<p className="text-xs text-slate-400">Integrationen und Dienst-Konfigurationen</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Feedback */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 bg-red-950/60 border border-red-800/60 rounded-lg px-3 py-2.5 text-xs text-red-300">
|
||||
<AlertCircle className="w-4 h-4 shrink-0 text-red-400" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{successMsg && (
|
||||
<div className="flex items-center gap-2 bg-emerald-950/60 border border-emerald-800/60 rounded-lg px-3 py-2.5 text-xs text-emerald-300">
|
||||
<CheckCircle className="w-4 h-4 shrink-0 text-emerald-400" />
|
||||
{successMsg}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Microsoft Entra ID */}
|
||||
<div className="bg-[#0F172A] border border-[#1E293B] rounded-2xl p-6 space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-1.5 bg-blue-950/50 border border-blue-900/50 rounded-lg">
|
||||
<Shield className="w-4 h-4 text-blue-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-white">Microsoft Entra ID</h3>
|
||||
<p className="text-xs text-slate-500">OAuth 2.0 Login für Organisationsaccounts</p>
|
||||
</div>
|
||||
</div>
|
||||
{/* Toggle */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAzureEnabled(v => !v)}
|
||||
className={`relative w-11 h-6 rounded-full transition-colors ${azureEnabled ? 'bg-blue-600' : 'bg-slate-700'}`}
|
||||
title={azureEnabled ? 'Deaktivieren' : 'Aktivieren'}
|
||||
>
|
||||
<span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform ${azureEnabled ? 'translate-x-5' : 'translate-x-0'}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={`grid grid-cols-1 sm:grid-cols-2 gap-4 ${!azureEnabled ? 'opacity-50 pointer-events-none' : ''}`}>
|
||||
<div>
|
||||
<FieldLabel>Tenant ID</FieldLabel>
|
||||
<TextInput value={azureTenantId} onChange={setAzureTenantId} placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" monospace />
|
||||
</div>
|
||||
<div>
|
||||
<FieldLabel>Client ID (Application ID)</FieldLabel>
|
||||
<TextInput value={azureClientId} onChange={setAzureClientId} placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" monospace />
|
||||
</div>
|
||||
<div>
|
||||
<FieldLabel>Client Secret</FieldLabel>
|
||||
<SecretInput
|
||||
value={azureClientSecret}
|
||||
onChange={setAzureClientSecret}
|
||||
alreadySet={azureSecretSet}
|
||||
show={showAzureSecret}
|
||||
onToggleShow={() => setShowAzureSecret(v => !v)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<FieldLabel>Redirect URI <span className="text-slate-500 font-normal">(leer = automatisch)</span></FieldLabel>
|
||||
<TextInput value={azureRedirectUri} onChange={setAzureRedirectUri} placeholder="https://ghostgrid.internal/api/auth/azure/callback" monospace />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CheckMK */}
|
||||
<div className="bg-[#0F172A] border border-[#1E293B] rounded-2xl p-6 space-y-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-1.5 bg-emerald-950/50 border border-emerald-900/50 rounded-lg">
|
||||
<Activity className="w-4 h-4 text-emerald-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-white">CheckMK</h3>
|
||||
<p className="text-xs text-slate-500">Geräte-Status-Synchronisation über die CheckMK REST API</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="sm:col-span-2">
|
||||
<FieldLabel>API URL</FieldLabel>
|
||||
<TextInput
|
||||
value={checkmkApiUrl}
|
||||
onChange={setCheckmkApiUrl}
|
||||
placeholder="https://checkmk.internal/<site>/check_mk/api/1.0"
|
||||
monospace
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<FieldLabel>Automation Secret</FieldLabel>
|
||||
<SecretInput
|
||||
value={checkmkApiSecret}
|
||||
onChange={setCheckmkApiSecret}
|
||||
alreadySet={checkmkSecretSet}
|
||||
show={showCheckmkSecret}
|
||||
onToggleShow={() => setShowCheckmkSecret(v => !v)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<FieldLabel>Sync-Intervall (ms)</FieldLabel>
|
||||
<TextInput value={checkmkSyncInterval} onChange={setCheckmkSyncInterval} placeholder="60000" monospace />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Save */}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="flex items-center gap-2 bg-cyan-600 hover:bg-cyan-500 disabled:bg-slate-700 disabled:text-slate-500 text-white font-semibold text-sm px-5 py-2.5 rounded-lg transition-all shadow-lg shadow-cyan-900/30"
|
||||
>
|
||||
{saving ? (
|
||||
<span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
||||
) : (
|
||||
<Save className="w-4 h-4" />
|
||||
)}
|
||||
{saving ? 'Speichert…' : 'Einstellungen speichern'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user