Files
tessera-ctl/apps/web/src/app/(portal)/admin/ldap/page.tsx
T
schalli af9e968c6f
Tessera CI/CD / Lint & Type Check (push) Successful in 45s
Tessera CI/CD / Tests (push) Successful in 49s
Tessera CI/CD / Build & Publish Images (push) Successful in 1m45s
feat(ldap): opt-in skip TLS verification for ldaps (internal CA)
Add a per-tenant "Skip TLS certificate verification" toggle to the LDAP
admin page so admins can connect to an AD whose ldaps:// certificate is
signed by an internal/self-signed CA (Node error: "unable to verify the
first certificate"). When enabled, ldapts is given
tlsOptions.rejectUnauthorized=false; the flag is ignored for plain ldap://
(no TLS). Defaults to full verification.

New Boolean column LdapConfig.tlsRejectUnauthorized (@default(true)) +
migration; wired through DTOs, config service, all Client creations
(test/groups/user-search/import/sync) and the test-connection endpoint. UI
checkbox with an insecure-network warning (de/en). 3 new service specs;
API 218 green, web 131 green, both apps tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 14:18:55 +02:00

1094 lines
39 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;
tlsRejectUnauthorized: boolean;
groupFilterDns: string[];
userExcludeList: string[];
lastSyncAt: string | null;
fieldMappings: FieldMapping[];
}
interface LdapDirectoryEntry {
dn: string;
name: string;
type: 'group' | 'ou';
}
interface LdapUserSearchResult {
dn: string;
username: string;
displayName: string;
email: string;
alreadyImported: boolean;
}
interface UserImportResult {
created: number;
updated: number;
skipped: number;
errors: string[];
}
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,
tlsRejectUnauthorized: 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 [discoverSearch, setDiscoverSearch] = useState('');
// Per-user exclude/denylist (individual usernames never imported)
const [userExcludeList, setUserExcludeList] = useState<string[]>([]);
const [newExcludeUser, setNewExcludeUser] = useState('');
const [savingExclude, setSavingExclude] = useState(false);
// Individual user search & import
const [userSearchQuery, setUserSearchQuery] = useState('');
const [userSearchResults, setUserSearchResults] = useState<
LdapUserSearchResult[] | null
>(null);
const [userSearching, setUserSearching] = useState(false);
const [selectedUserDns, setSelectedUserDns] = useState<string[]>([]);
const [importingUsers, setImportingUsers] = useState(false);
const [userImportResult, setUserImportResult] =
useState<UserImportResult | null>(null);
const filteredDiscovered = discovered?.filter((entry) => {
const q = discoverSearch.trim().toLowerCase();
if (!q) return true;
return (
entry.name.toLowerCase().includes(q) || entry.dn.toLowerCase().includes(q)
);
});
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,
tlsRejectUnauthorized: data.tlsRejectUnauthorized ?? true,
});
setGroupFilterDns(data.groupFilterDns ?? []);
setUserExcludeList(data.userExcludeList ?? []);
}
}
} 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 {
// Send the currently entered values so a connection can be validated
// before ever saving a config. bindPassword is omitted when blank so
// the backend falls back to the saved config's password (masked
// fields never get re-sent once a config already exists).
const body: Record<string, unknown> = {};
if (formData.serverUrl) body.serverUrl = formData.serverUrl;
if (formData.bindDn) body.bindDn = formData.bindDn;
if (formData.bindPassword) body.bindPassword = formData.bindPassword;
// Always send the current TLS-verification choice so the test reflects it.
body.tlsRejectUnauthorized = formData.tlsRejectUnauthorized;
const res = await fetch(`${API_URL}/ldap/test-connection`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(body),
});
const data = await res.json();
if (res.ok) {
setTestResult(data);
} else {
setTestResult({ success: false, error: data.message || 'Test failed' });
}
} 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);
}
};
const handleAddExcludeUser = () => {
const name = newExcludeUser.trim().toLowerCase();
if (!name || userExcludeList.includes(name)) return;
setUserExcludeList((prev) => [...prev, name]);
setNewExcludeUser('');
};
const handleRemoveExcludeUser = (name: string) => {
setUserExcludeList((prev) => prev.filter((u) => u !== name));
};
const handleSearchUsers = async () => {
const q = userSearchQuery.trim();
if (!q) return;
setUserSearching(true);
setUserImportResult(null);
try {
const res = await fetch(
`${API_URL}/ldap/users/search?q=${encodeURIComponent(q)}`,
{ credentials: 'include' },
);
if (res.ok) {
const data = await res.json();
setUserSearchResults(data);
setSelectedUserDns([]);
}
} catch {
// silently fail
} finally {
setUserSearching(false);
}
};
const toggleUserDn = (dn: string) => {
setSelectedUserDns((prev) =>
prev.includes(dn) ? prev.filter((d) => d !== dn) : [...prev, dn],
);
};
const handleImportUsers = async (dns: string[]) => {
if (dns.length === 0) return;
setImportingUsers(true);
setUserImportResult(null);
try {
const res = await fetch(`${API_URL}/ldap/users/import`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ dns }),
});
if (res.ok) {
const data = await res.json();
setUserImportResult(data);
setSelectedUserDns([]);
// Re-run the search so alreadyImported flags refresh.
await handleSearchUsers();
}
} catch {
// silently fail
} finally {
setImportingUsers(false);
}
};
const handleSaveExcludeList = async () => {
setSavingExclude(true);
try {
const res = await fetch(`${API_URL}/ldap/config`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ userExcludeList }),
});
if (res.ok) {
await fetchConfig();
}
} catch {
// silently fail
} finally {
setSavingExclude(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="cn=admin,dc=example,dc=com (leer = anonymous bind)"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
/>
</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?.bindPassword ? '********' : ''}
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
/>
</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="space-y-1">
<label className="flex items-center gap-2 text-sm text-foreground">
<input
type="checkbox"
checked={!formData.tlsRejectUnauthorized}
onChange={(e) =>
setFormData({
...formData,
tlsRejectUnauthorized: !e.target.checked,
})
}
/>
{t('tlsSkip.label')}
</label>
<p className="text-xs text-muted-foreground">{t('tlsSkip.hint')}</p>
</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>
<button
type="button"
onClick={handleTestConnection}
disabled={!config && !formData.serverUrl}
className="rounded-md border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-muted transition-colors disabled:opacity-50"
>
{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 space-y-2">
<input
type="text"
value={discoverSearch}
onChange={(e) => setDiscoverSearch(e.target.value)}
placeholder={t('groupFilter.searchPlaceholder')}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm"
/>
<div className="max-h-64 overflow-y-auto rounded-md border border-border divide-y divide-border">
{filteredDiscovered && filteredDiscovered.length > 0 ? (
filteredDiscovered.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>
))
) : (
<p className="px-4 py-3 text-sm text-muted-foreground">
{t('groupFilter.noMatches')}
</p>
)}
</div>
</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 2.55: Individual user search & import */}
{config && (
<section className="rounded-lg border border-border p-6">
<h2 className="text-lg font-semibold text-foreground mb-2">
{t('userSearch.title')}
</h2>
<p className="text-sm text-muted-foreground mb-4">
{t('userSearch.description')}
</p>
<div className="flex items-end gap-3 mb-4">
<div className="flex-1 space-y-1">
<input
type="text"
value={userSearchQuery}
onChange={(e) => setUserSearchQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleSearchUsers();
}}
placeholder={t('userSearch.placeholder')}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm"
/>
</div>
<button
type="button"
onClick={handleSearchUsers}
disabled={userSearching || !userSearchQuery.trim()}
className="h-9 rounded-md border border-border px-4 text-sm font-medium text-foreground hover:bg-muted transition-colors disabled:opacity-50"
>
{userSearching ? tCommon('loading') : t('userSearch.search')}
</button>
</div>
{userSearchResults && userSearchResults.length > 0 && (
<div className="mb-4 max-h-64 overflow-y-auto rounded-md border border-border divide-y divide-border">
{userSearchResults.map((u) => (
<label
key={u.dn}
className={`flex items-center gap-3 px-4 py-2 text-sm ${
u.alreadyImported
? 'opacity-60'
: 'hover:bg-muted/30 cursor-pointer'
}`}
>
<input
type="checkbox"
disabled={u.alreadyImported}
checked={selectedUserDns.includes(u.dn)}
onChange={() => toggleUserDn(u.dn)}
/>
<span className="font-medium text-foreground">
{u.displayName || u.username}
</span>
<span className="text-xs text-muted-foreground">
{u.username}
</span>
{u.email && (
<span className="truncate text-xs text-muted-foreground">
{u.email}
</span>
)}
{u.alreadyImported && (
<span className="ml-auto shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
{t('userSearch.alreadyImported')}
</span>
)}
</label>
))}
</div>
)}
{userSearchResults && userSearchResults.length === 0 && (
<p className="mb-4 text-sm text-muted-foreground">
{t('userSearch.noResults')}
</p>
)}
{userSearchResults && userSearchResults.length > 0 && (
<button
type="button"
onClick={() => handleImportUsers(selectedUserDns)}
disabled={importingUsers || selectedUserDns.length === 0}
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
>
{importingUsers
? tCommon('loading')
: `${t('userSearch.importSelected')} (${selectedUserDns.length})`}
</button>
)}
{userImportResult && (
<p className="mt-3 text-sm text-muted-foreground">
{userImportResult.created} {t('userSearch.created')},{' '}
{userImportResult.skipped} {t('userSearch.skipped')}
{userImportResult.errors.length > 0 && (
<>
, {userImportResult.errors.length} {t('userSearch.errors')}
</>
)}
</p>
)}
</section>
)}
{/* Section 2.6: Per-user exclude/denylist */}
{config && (
<section className="rounded-lg border border-border p-6">
<h2 className="text-lg font-semibold text-foreground mb-2">
{t('userExclude.title')}
</h2>
<p className="text-sm text-muted-foreground mb-4">
{t('userExclude.description')}
</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('userExclude.username')}
</label>
<input
type="text"
value={newExcludeUser}
onChange={(e) => setNewExcludeUser(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddExcludeUser();
}
}}
placeholder="administrator, krbtgt, guest, ldap$ ..."
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={handleAddExcludeUser}
className="h-9 rounded-md border border-border px-3 text-xs font-medium text-foreground hover:bg-muted transition-colors"
>
{t('userExclude.add')}
</button>
</div>
<div className="mb-4">
<p className="text-xs font-medium text-muted-foreground mb-2">
{t('userExclude.excluded')}
</p>
{userExcludeList.length === 0 ? (
<p className="text-sm text-muted-foreground">{t('userExclude.empty')}</p>
) : (
<ul className="flex flex-wrap gap-2">
{userExcludeList.map((name) => (
<li
key={name}
className="flex items-center gap-2 rounded-md border border-border px-3 py-1.5 text-sm"
>
<span className="font-mono text-xs text-foreground">{name}</span>
<button
type="button"
onClick={() => handleRemoveExcludeUser(name)}
className="shrink-0 rounded px-1.5 py-0.5 text-xs text-destructive hover:bg-destructive/10 transition-colors"
>
{t('fieldMapping.remove')}
</button>
</li>
))}
</ul>
)}
</div>
<button
type="button"
onClick={handleSaveExcludeList}
disabled={savingExclude}
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
>
{savingExclude ? tCommon('loading') : t('userExclude.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>
);
}