feat(02-04): LDAP admin UI with config, mapping editor, and sync trigger

This commit is contained in:
2026-06-19 08:40:29 +02:00
parent f928cd7713
commit 6e19591168
3 changed files with 594 additions and 1 deletions
@@ -0,0 +1,564 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useAuthStore } from '@/lib/stores/auth-store';
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
interface FieldMapping {
id: string;
ldapField: string;
tesseraField: string;
isDefault: boolean;
}
interface LdapConfig {
id: string;
tenantId: string;
serverUrl: string;
baseDn: string;
bindDn: string;
bindPassword: string;
searchFilter: string;
syncIntervalMin: number;
isActive: boolean;
lastSyncAt: string | null;
fieldMappings: FieldMapping[];
}
interface SyncResult {
created: number;
updated: number;
deactivated: number;
errors: string[];
}
/**
* LDAP Configuration admin page (D-14, D-16, D-17, D-18).
* Only visible to ADMIN and SUPER_ADMIN roles.
*/
export default function AdminLdapPage() {
const t = useTranslations('admin.ldap');
const tCommon = useTranslations('common');
const currentUser = useAuthStore((s) => s.user);
const [config, setConfig] = useState<LdapConfig | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testResult, setTestResult] = useState<{
success: boolean;
error?: string;
} | null>(null);
const [syncResult, setSyncResult] = useState<SyncResult | null>(null);
const [syncing, setSyncing] = useState(false);
// Form state for connection settings
const [formData, setFormData] = useState({
serverUrl: '',
baseDn: '',
bindDn: '',
bindPassword: '',
searchFilter: '(objectClass=person)',
syncIntervalMin: 60,
isActive: true,
});
// New mapping form
const [newMapping, setNewMapping] = useState({ ldapField: '', tesseraField: '' });
const [showMappingForm, setShowMappingForm] = useState(false);
const hasAccess =
currentUser?.role === 'ADMIN' || currentUser?.role === 'SUPER_ADMIN';
const fetchConfig = useCallback(async () => {
try {
const res = await fetch(`${API_URL}/ldap/config`, {
credentials: 'include',
});
if (res.ok) {
const data = await res.json();
if (data) {
setConfig(data);
setFormData({
serverUrl: data.serverUrl || '',
baseDn: data.baseDn || '',
bindDn: data.bindDn || '',
bindPassword: '',
searchFilter: data.searchFilter || '(objectClass=person)',
syncIntervalMin: data.syncIntervalMin ?? 60,
isActive: data.isActive ?? true,
});
}
}
} catch {
// silently fail
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
if (hasAccess) {
fetchConfig();
} else {
setLoading(false);
}
}, [hasAccess, fetchConfig]);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
setTestResult(null);
try {
const method = config ? 'PATCH' : 'POST';
const body: Record<string, unknown> = { ...formData };
// Don't send empty password on update (keeps existing)
if (config && !formData.bindPassword) {
delete body.bindPassword;
}
const res = await fetch(`${API_URL}/ldap/config`, {
method,
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(body),
});
if (res.ok) {
await fetchConfig();
}
} catch {
// silently fail
} finally {
setSaving(false);
}
};
const handleTestConnection = async () => {
setTestResult(null);
try {
const res = await fetch(`${API_URL}/ldap/test-connection`, {
method: 'POST',
credentials: 'include',
});
if (res.ok) {
const data = await res.json();
setTestResult(data);
}
} catch {
setTestResult({ success: false, error: 'Network error' });
}
};
const handleSync = async () => {
setSyncing(true);
setSyncResult(null);
try {
const res = await fetch(`${API_URL}/ldap/sync`, {
method: 'POST',
credentials: 'include',
});
if (res.ok) {
const data = await res.json();
setSyncResult(data);
await fetchConfig();
}
} catch {
setSyncResult({ created: 0, updated: 0, deactivated: 0, errors: ['Network error'] });
} finally {
setSyncing(false);
}
};
const handleAddMapping = async (e: React.FormEvent) => {
e.preventDefault();
if (!newMapping.ldapField || !newMapping.tesseraField) return;
try {
const res = await fetch(`${API_URL}/ldap/config/mappings`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(newMapping),
});
if (res.ok) {
setNewMapping({ ldapField: '', tesseraField: '' });
setShowMappingForm(false);
await fetchConfig();
}
} catch {
// silently fail
}
};
const handleRemoveMapping = async (mappingId: string) => {
try {
const res = await fetch(`${API_URL}/ldap/config/mappings/${mappingId}`, {
method: 'DELETE',
credentials: 'include',
});
if (res.ok) {
await fetchConfig();
}
} catch {
// silently fail
}
};
if (!hasAccess) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<p className="text-lg text-muted-foreground">{tCommon('accessDenied')}</p>
</div>
);
}
if (loading) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<p className="text-muted-foreground">{tCommon('loading')}</p>
</div>
);
}
return (
<div className="space-y-8">
<h1 className="text-2xl font-bold text-foreground">{t('title')}</h1>
{/* Section 1: Connection Settings */}
<section className="rounded-lg border border-border p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">
{t('connectionTitle')}
</h2>
<form onSubmit={handleSave} className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-medium text-foreground">
{t('serverUrl')}
</label>
<input
type="text"
value={formData.serverUrl}
onChange={(e) => setFormData({ ...formData, serverUrl: e.target.value })}
placeholder="ldap://ldap.example.com"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-foreground">
{t('baseDn')}
</label>
<input
type="text"
value={formData.baseDn}
onChange={(e) => setFormData({ ...formData, baseDn: e.target.value })}
placeholder="dc=example,dc=com"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-foreground">
{t('bindDn')}
</label>
<input
type="text"
value={formData.bindDn}
onChange={(e) => setFormData({ ...formData, bindDn: e.target.value })}
placeholder="cn=admin,dc=example,dc=com"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-foreground">
{t('bindPassword')}
</label>
<input
type="password"
value={formData.bindPassword}
onChange={(e) => setFormData({ ...formData, bindPassword: e.target.value })}
placeholder={config ? '********' : ''}
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
required={!config}
/>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-foreground">
{t('searchFilter')}
</label>
<input
type="text"
value={formData.searchFilter}
onChange={(e) => setFormData({ ...formData, searchFilter: e.target.value })}
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
/>
</div>
<div className="flex items-center gap-4 pt-2">
<button
type="submit"
disabled={saving}
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
>
{saving ? tCommon('loading') : t('save')}
</button>
{config && (
<button
type="button"
onClick={handleTestConnection}
className="rounded-md border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-muted transition-colors"
>
{t('testConnection')}
</button>
)}
</div>
{testResult && (
<div
className={`mt-2 rounded-md px-4 py-2 text-sm ${
testResult.success
? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
}`}
>
{testResult.success ? t('testSuccess') : `${t('testFailed')}: ${testResult.error}`}
</div>
)}
</form>
</section>
{/* Section 2: Field Mapping (D-16, D-17) */}
{config && (
<section className="rounded-lg border border-border p-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold text-foreground">
{t('fieldMapping.title')}
</h2>
<button
onClick={() => setShowMappingForm(true)}
className="rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:opacity-90 transition-opacity"
>
{t('fieldMapping.add')}
</button>
</div>
<div className="overflow-x-auto rounded-md border border-border">
<table className="w-full text-sm">
<thead className="bg-muted/50">
<tr>
<th className="px-4 py-3 text-left font-medium text-muted-foreground">
{t('fieldMapping.ldapField')}
</th>
<th className="px-4 py-3 text-left font-medium text-muted-foreground">
{t('fieldMapping.tesseraField')}
</th>
<th className="px-4 py-3 text-left font-medium text-muted-foreground">
{t('fieldMapping.default')}
</th>
<th className="px-4 py-3 text-right font-medium text-muted-foreground">
{tCommon('actions')}
</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{config.fieldMappings.map((mapping) => (
<tr key={mapping.id} className="hover:bg-muted/30 transition-colors">
<td className="px-4 py-3 font-mono text-foreground">
{mapping.ldapField}
</td>
<td className="px-4 py-3 font-mono text-foreground">
{mapping.tesseraField}
</td>
<td className="px-4 py-3">
{mapping.isDefault && (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="text-muted-foreground"
>
<rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
<path d="M7 11V7a5 5 0 0 1 10 0v4" />
</svg>
)}
</td>
<td className="px-4 py-3 text-right">
{!mapping.isDefault && (
<button
onClick={() => handleRemoveMapping(mapping.id)}
className="rounded px-2 py-1 text-xs text-destructive hover:bg-destructive/10 transition-colors"
>
{t('fieldMapping.remove')}
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Add mapping form */}
{showMappingForm && (
<form onSubmit={handleAddMapping} className="mt-4 flex items-end gap-3">
<div className="space-y-1">
<label className="text-xs font-medium text-muted-foreground">
{t('fieldMapping.ldapField')}
</label>
<input
type="text"
value={newMapping.ldapField}
onChange={(e) => setNewMapping({ ...newMapping, ldapField: e.target.value })}
className="flex h-9 w-40 rounded-md border border-input bg-background px-3 py-1 text-sm"
required
/>
</div>
<div className="space-y-1">
<label className="text-xs font-medium text-muted-foreground">
{t('fieldMapping.tesseraField')}
</label>
<input
type="text"
value={newMapping.tesseraField}
onChange={(e) => setNewMapping({ ...newMapping, tesseraField: e.target.value })}
className="flex h-9 w-40 rounded-md border border-input bg-background px-3 py-1 text-sm"
required
/>
</div>
<button
type="submit"
className="h-9 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:opacity-90 transition-opacity"
>
{tCommon('save')}
</button>
<button
type="button"
onClick={() => setShowMappingForm(false)}
className="h-9 rounded-md border border-border px-3 text-xs text-foreground hover:bg-muted transition-colors"
>
{tCommon('cancel')}
</button>
</form>
)}
</section>
)}
{/* Section 3: Sync Settings (D-14) */}
{config && (
<section className="rounded-lg border border-border p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">
{t('sync.title')}
</h2>
<div className="space-y-4">
{/* Sync interval */}
<div className="flex items-center gap-4">
<div className="space-y-1">
<label className="text-sm font-medium text-foreground">
{t('sync.interval')}
</label>
<div className="flex items-center gap-2">
<input
type="number"
min={0}
value={formData.syncIntervalMin}
onChange={(e) =>
setFormData({ ...formData, syncIntervalMin: parseInt(e.target.value, 10) || 0 })
}
className="flex h-10 w-24 rounded-md border border-input bg-background px-3 py-2 text-sm"
/>
<span className="text-sm text-muted-foreground">min</span>
{formData.syncIntervalMin === 0 && (
<span className="text-xs text-muted-foreground">
({t('sync.intervalDisabled')})
</span>
)}
</div>
</div>
</div>
{/* Enable/Disable toggle */}
<div className="flex items-center gap-3">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
checked={formData.isActive}
onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
className="sr-only peer"
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-primary" />
</label>
<span className="text-sm font-medium text-foreground">
{formData.isActive ? t('enable') : t('disable')}
</span>
</div>
{/* Save interval changes */}
<button
onClick={handleSave}
disabled={saving}
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
>
{t('save')}
</button>
{/* Last sync info */}
<div className="border-t border-border pt-4">
<p className="text-sm text-muted-foreground">
{t('sync.lastSync')}:{' '}
<span className="font-medium text-foreground">
{config.lastSyncAt
? new Date(config.lastSyncAt).toLocaleString()
: t('sync.neverSynced')}
</span>
</p>
</div>
{/* Manual sync button (D-14) */}
<button
onClick={handleSync}
disabled={syncing}
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
>
{syncing ? t('sync.syncing') : t('sync.trigger')}
</button>
{/* Sync result display */}
{syncResult && (
<div className="rounded-md border border-border bg-muted/30 p-4">
<p className="text-sm font-medium text-foreground mb-2">
{t('sync.result', {
created: syncResult.created,
updated: syncResult.updated,
deactivated: syncResult.deactivated,
})}
</p>
{syncResult.errors.length > 0 && (
<div className="mt-2 space-y-1">
{syncResult.errors.map((err, i) => (
<p key={i} className="text-xs text-destructive">
{err}
</p>
))}
</div>
)}
</div>
)}
</div>
</section>
)}
</div>
);
}
@@ -171,6 +171,34 @@ export function Sidebar() {
</a>
</li>
)}
{/* LDAP link -- ADMIN and SUPER_ADMIN (D-18) */}
<li>
<a
href="/admin/ldap"
className="flex items-center gap-3 rounded-md px-2 py-2 text-sm text-sidebar-foreground hover:bg-muted transition-colors"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="shrink-0"
>
<path d="M12 2L2 7l10 5 10-5-10-5z" />
<path d="M2 17l10 5 10-5" />
<path d="M2 12l10 5 10-5" />
</svg>
{!isCollapsed && (
<span className="truncate">{t('ldap')}</span>
)}
</a>
</li>
</ul>
</div>
)}
+2 -1
View File
@@ -87,7 +87,8 @@
},
"admin": "Verwaltung",
"users": "Benutzer",
"tenants": "Mandanten"
"tenants": "Mandanten",
"ldap": "LDAP"
},
"dashboard": {
"title": "Dashboard",