Files
tessera-ctl/apps/web/src/app/(portal)/admin/ldap/page.tsx
T
schalli 75b58491e9 feat(ldap): AD connection prefill + group/OU import filter UI
New-config form now defaults to the CTL Active Directory connection
values (balios.ctl.local:3268, dc=ctl,dc=local, AD person filter,
down-level bind-DN hint) with the password left blank; editing an
existing config still shows its real saved values.

Adds a group/OU import filter section: discover AD groups/OUs via
GET /ldap/groups, toggle selection or add DNs manually, persist via
PATCH /ldap/config. Empty selection keeps today's "import everyone
under base DN" behavior.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-07 09:39:58 +02:00

748 lines
27 KiB
TypeScript

'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;
groupFilterDns: string[];
lastSyncAt: string | null;
fieldMappings: FieldMapping[];
}
interface LdapDirectoryEntry {
dn: string;
name: string;
type: 'group' | 'ou';
}
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.
// Defaults are pre-filled with the known-good CTL Active Directory
// connection values (sourced from the working XWiki LDAP config) so a
// brand-new setup only needs the service-account password. fetchConfig()
// below overwrites these with the real saved values whenever a config
// already exists.
const [formData, setFormData] = useState({
serverUrl: 'ldap://balios.ctl.local:3268',
baseDn: 'dc=ctl,dc=local',
bindDn: '',
bindPassword: '',
searchFilter: '(&(objectClass=user)(objectCategory=person))',
syncIntervalMin: 60,
isActive: true,
});
// New mapping form
const [newMapping, setNewMapping] = useState({ ldapField: '', tesseraField: '' });
const [showMappingForm, setShowMappingForm] = useState(false);
// Group/OU import filter (selective sync)
const [groupFilterDns, setGroupFilterDns] = useState<string[]>([]);
const [discovered, setDiscovered] = useState<LdapDirectoryEntry[] | null>(null);
const [discovering, setDiscovering] = useState(false);
const [manualDn, setManualDn] = useState('');
const [savingFilter, setSavingFilter] = 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,
});
setGroupFilterDns(data.groupFilterDns ?? []);
}
}
} 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
}
};
const handleDiscoverGroups = async () => {
setDiscovering(true);
try {
const res = await fetch(`${API_URL}/ldap/groups`, {
credentials: 'include',
});
if (res.ok) {
const data = await res.json();
setDiscovered(data);
}
} catch {
// silently fail
} finally {
setDiscovering(false);
}
};
const toggleGroupFilterDn = (dn: string) => {
setGroupFilterDns((prev) =>
prev.includes(dn) ? prev.filter((d) => d !== dn) : [...prev, dn],
);
};
const handleAddManualDn = () => {
const dn = manualDn.trim();
if (!dn || groupFilterDns.includes(dn)) return;
setGroupFilterDns((prev) => [...prev, dn]);
setManualDn('');
};
const handleRemoveGroupFilterDn = (dn: string) => {
setGroupFilterDns((prev) => prev.filter((d) => d !== dn));
};
const handleSaveGroupFilter = async () => {
setSavingFilter(true);
try {
const res = await fetch(`${API_URL}/ldap/config`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ groupFilterDns }),
});
if (res.ok) {
await fetchConfig();
}
} catch {
// silently fail
} finally {
setSavingFilter(false);
}
};
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="ctl\serviceaccount"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
required
/>
<p className="text-xs text-muted-foreground">{t('bindDnHint')}</p>
</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 2.5: Group/OU import filter (selective sync) */}
{config && (
<section className="rounded-lg border border-border p-6">
<h2 className="text-lg font-semibold text-foreground mb-2">
{t('groupFilter.title')}
</h2>
<p className="text-sm text-muted-foreground mb-4">
{t('groupFilter.description')}
</p>
<div className="flex items-center gap-3 mb-4">
<button
type="button"
onClick={handleDiscoverGroups}
disabled={discovering}
className="rounded-md border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-muted transition-colors disabled:opacity-50"
>
{discovering ? tCommon('loading') : t('groupFilter.discover')}
</button>
</div>
{discovered && discovered.length > 0 && (
<div className="mb-4 max-h-64 overflow-y-auto rounded-md border border-border divide-y divide-border">
{discovered.map((entry) => (
<label
key={entry.dn}
className="flex items-center gap-3 px-4 py-2 text-sm hover:bg-muted/30 cursor-pointer"
>
<input
type="checkbox"
checked={groupFilterDns.includes(entry.dn)}
onChange={() => toggleGroupFilterDn(entry.dn)}
/>
<span className="rounded bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
{entry.type === 'ou' ? t('groupFilter.typeOu') : t('groupFilter.typeGroup')}
</span>
<span className="font-medium text-foreground">{entry.name}</span>
<span className="font-mono text-xs text-muted-foreground truncate">
{entry.dn}
</span>
</label>
))}
</div>
)}
{discovered && discovered.length === 0 && (
<p className="mb-4 text-sm text-muted-foreground">{t('groupFilter.noneFound')}</p>
)}
<div className="flex items-end gap-3 mb-4">
<div className="flex-1 space-y-1">
<label className="text-xs font-medium text-muted-foreground">
{t('groupFilter.manualDn')}
</label>
<input
type="text"
value={manualDn}
onChange={(e) => setManualDn(e.target.value)}
placeholder="CN=Beispiel,OU=Gruppen,DC=ctl,DC=local"
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm font-mono"
/>
</div>
<button
type="button"
onClick={handleAddManualDn}
className="h-9 rounded-md border border-border px-3 text-xs font-medium text-foreground hover:bg-muted transition-colors"
>
{t('groupFilter.addDn')}
</button>
</div>
<div className="mb-4">
<p className="text-xs font-medium text-muted-foreground mb-2">
{t('groupFilter.selected')}
</p>
{groupFilterDns.length === 0 ? (
<p className="text-sm text-muted-foreground">{t('groupFilter.emptyMeansAll')}</p>
) : (
<ul className="space-y-1">
{groupFilterDns.map((dn) => (
<li
key={dn}
className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-1.5 text-sm"
>
<span className="font-mono text-xs text-foreground truncate">{dn}</span>
<button
type="button"
onClick={() => handleRemoveGroupFilterDn(dn)}
className="shrink-0 rounded px-2 py-1 text-xs text-destructive hover:bg-destructive/10 transition-colors"
>
{t('fieldMapping.remove')}
</button>
</li>
))}
</ul>
)}
</div>
<button
type="button"
onClick={handleSaveGroupFilter}
disabled={savingFilter}
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
>
{savingFilter ? tCommon('loading') : t('groupFilter.save')}
</button>
</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>
);
}