LDAPSettings.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import { useState, useEffect } from 'react';
  2. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { Shield, Lock, Unlock, AlertTriangle, CheckCircle, Loader2, Send } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { AppSettings } from '../api/client';
  7. import { Card, CardContent, CardHeader } from './Card';
  8. import { Button } from './Button';
  9. import { Collapsible } from './Collapsible';
  10. import { useToast } from '../contexts/ToastContext';
  11. import { useAuth } from '../contexts/AuthContext';
  12. const SECURITY_PORT_MAP: Record<string, string> = {
  13. starttls: '389',
  14. ldaps: '636',
  15. };
  16. interface LDAPFormState {
  17. ldap_server_url: string;
  18. ldap_bind_dn: string;
  19. ldap_bind_password: string;
  20. ldap_search_base: string;
  21. ldap_user_filter: string;
  22. ldap_security: string;
  23. ldap_group_mapping: string;
  24. ldap_auto_provision: boolean;
  25. ldap_default_group: string;
  26. }
  27. export function LDAPSettings() {
  28. const { t } = useTranslation();
  29. const { showToast } = useToast();
  30. const queryClient = useQueryClient();
  31. const { authEnabled } = useAuth();
  32. const [form, setForm] = useState<LDAPFormState>({
  33. ldap_server_url: '',
  34. ldap_bind_dn: '',
  35. ldap_bind_password: '',
  36. ldap_search_base: '',
  37. ldap_user_filter: '(sAMAccountName={username})',
  38. ldap_security: 'starttls',
  39. ldap_group_mapping: '',
  40. ldap_auto_provision: false,
  41. ldap_default_group: '',
  42. });
  43. // Fetch settings
  44. const { data: settings, isLoading } = useQuery({
  45. queryKey: ['settings'],
  46. queryFn: () => api.getSettings(),
  47. });
  48. // Fetch LDAP status
  49. const { data: ldapStatus } = useQuery({
  50. queryKey: ['ldapStatus'],
  51. queryFn: () => api.getLDAPStatus(),
  52. });
  53. // Fetch groups for mapping display
  54. const { data: groups = [] } = useQuery({
  55. queryKey: ['groups'],
  56. queryFn: () => api.getGroups(),
  57. });
  58. // Load settings into form
  59. useEffect(() => {
  60. if (settings) {
  61. setForm({
  62. ldap_server_url: settings.ldap_server_url || '',
  63. ldap_bind_dn: settings.ldap_bind_dn || '',
  64. ldap_bind_password: '', // Never show password
  65. ldap_search_base: settings.ldap_search_base || '',
  66. ldap_user_filter: settings.ldap_user_filter || '(sAMAccountName={username})',
  67. ldap_security: settings.ldap_security || 'starttls',
  68. ldap_group_mapping: settings.ldap_group_mapping || '',
  69. ldap_auto_provision: settings.ldap_auto_provision ?? false,
  70. ldap_default_group: settings.ldap_default_group || '',
  71. });
  72. }
  73. }, [settings]);
  74. // Save settings
  75. const saveMutation = useMutation({
  76. mutationFn: (data: Partial<AppSettings>) => api.updateSettings(data),
  77. onSuccess: () => {
  78. queryClient.invalidateQueries({ queryKey: ['settings'] });
  79. queryClient.invalidateQueries({ queryKey: ['ldapStatus'] });
  80. showToast(t('settings.ldap.settingsSaved') || 'LDAP settings saved', 'success');
  81. },
  82. onError: (error: Error) => {
  83. showToast(error.message, 'error');
  84. },
  85. });
  86. // Toggle LDAP
  87. const toggleMutation = useMutation({
  88. mutationFn: (enabled: boolean) => api.updateSettings({ ldap_enabled: enabled }),
  89. onSuccess: () => {
  90. queryClient.invalidateQueries({ queryKey: ['settings'] });
  91. queryClient.invalidateQueries({ queryKey: ['ldapStatus'] });
  92. showToast(
  93. ldapStatus?.ldap_enabled
  94. ? (t('settings.ldap.disabled') || 'LDAP authentication disabled')
  95. : (t('settings.ldap.enabled') || 'LDAP authentication enabled'),
  96. 'success'
  97. );
  98. },
  99. onError: (error: Error) => {
  100. showToast(error.message, 'error');
  101. },
  102. });
  103. // Test connection
  104. const testMutation = useMutation({
  105. // What the form holds, saved or not.
  106. mutationFn: () =>
  107. api.testLDAP({
  108. ldap_server_url: form.ldap_server_url,
  109. ldap_bind_dn: form.ldap_bind_dn,
  110. ldap_bind_password: form.ldap_bind_password,
  111. ldap_search_base: form.ldap_search_base,
  112. ldap_user_filter: form.ldap_user_filter,
  113. ldap_security: form.ldap_security,
  114. }),
  115. onSuccess: (data: { success: boolean; message: string }) => {
  116. showToast(data.message, data.success ? 'success' : 'error');
  117. },
  118. onError: (error: Error) => {
  119. showToast(error.message, 'error');
  120. },
  121. });
  122. // A saved bind password only goes to the server it was entered for.
  123. const bindPasswordNeedsReentry =
  124. !!settings?.ldap_bind_dn &&
  125. !form.ldap_bind_password &&
  126. (form.ldap_server_url !== (settings.ldap_server_url || '') ||
  127. form.ldap_security !== (settings.ldap_security || 'starttls'));
  128. const handleSave = () => {
  129. if (!form.ldap_server_url) {
  130. showToast(t('settings.ldap.errors.serverRequired') || 'LDAP server URL is required', 'error');
  131. return;
  132. }
  133. if (!form.ldap_search_base) {
  134. showToast(t('settings.ldap.errors.searchBaseRequired') || 'Search base DN is required', 'error');
  135. return;
  136. }
  137. // Build the update payload — only include password if user entered one
  138. const update: Record<string, unknown> = {
  139. ldap_server_url: form.ldap_server_url,
  140. ldap_bind_dn: form.ldap_bind_dn,
  141. ldap_search_base: form.ldap_search_base,
  142. ldap_user_filter: form.ldap_user_filter,
  143. ldap_security: form.ldap_security,
  144. ldap_group_mapping: form.ldap_group_mapping,
  145. ldap_auto_provision: form.ldap_auto_provision,
  146. ldap_default_group: form.ldap_default_group,
  147. };
  148. if (form.ldap_bind_password) {
  149. update.ldap_bind_password = form.ldap_bind_password;
  150. }
  151. saveMutation.mutate(update as Partial<AppSettings>);
  152. };
  153. const handleToggle = () => {
  154. if (!authEnabled) {
  155. showToast(t('settings.ldap.errors.enableAuthFirst') || 'Enable authentication first', 'error');
  156. return;
  157. }
  158. if (!ldapStatus?.ldap_enabled && !ldapStatus?.ldap_configured) {
  159. showToast(t('settings.ldap.errors.configureLdapFirst') || 'Save LDAP settings first', 'error');
  160. return;
  161. }
  162. toggleMutation.mutate(!ldapStatus?.ldap_enabled);
  163. };
  164. if (isLoading) {
  165. return (
  166. <div className="flex items-center justify-center p-12">
  167. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  168. </div>
  169. );
  170. }
  171. const ldapEnabled = ldapStatus?.ldap_enabled ?? false;
  172. const inputClasses = "w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors";
  173. return (
  174. <div className="space-y-3">
  175. {/* LDAP Toggle */}
  176. <Card id="card-ldap-toggle">
  177. <CardHeader>
  178. <div className="flex items-center justify-between">
  179. <div className="flex items-center gap-2">
  180. <Shield className="w-5 h-5 text-bambu-green" />
  181. <h2 className="text-lg font-semibold text-white">
  182. {t('settings.ldap.title') || 'LDAP Authentication'}
  183. </h2>
  184. </div>
  185. <Button
  186. onClick={handleToggle}
  187. disabled={toggleMutation.isPending}
  188. variant={ldapEnabled ? 'danger' : 'primary'}
  189. >
  190. {ldapEnabled ? (
  191. <>
  192. <Unlock className="w-4 h-4" />
  193. {t('common.disable') || 'Disable'}
  194. </>
  195. ) : (
  196. <>
  197. <Lock className="w-4 h-4" />
  198. {t('common.enable') || 'Enable'}
  199. </>
  200. )}
  201. </Button>
  202. </div>
  203. </CardHeader>
  204. <CardContent>
  205. {ldapEnabled ? (
  206. <div className="bg-green-50 dark:bg-green-500/10 border border-green-300 dark:border-green-500/30 rounded-lg p-4">
  207. <div className="flex items-start gap-3">
  208. <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400 mt-0.5 flex-shrink-0" />
  209. <div className="space-y-2">
  210. <p className="text-white font-medium">
  211. {t('settings.ldap.enabledDesc') || 'LDAP authentication is enabled'}
  212. </p>
  213. <ul className="text-sm text-green-700 dark:text-green-300 space-y-1 list-disc list-inside">
  214. <li>{t('settings.ldap.feature1') || 'Users can login with LDAP credentials'}</li>
  215. <li>{t('settings.ldap.feature2') || 'Local admin account remains as fallback'}</li>
  216. <li>{t('settings.ldap.feature3') || 'LDAP groups are mapped to BamBuddy groups on login'}</li>
  217. </ul>
  218. </div>
  219. </div>
  220. </div>
  221. ) : (
  222. <div className="bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg p-4">
  223. <div className="flex items-start gap-3">
  224. <AlertTriangle className="w-5 h-5 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  225. <div>
  226. <p className="text-white font-medium">
  227. {t('settings.ldap.disabledDesc') || 'LDAP authentication is disabled'}
  228. </p>
  229. <p className="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
  230. {t('settings.ldap.disabledHint') || 'Configure and save LDAP settings below, then enable.'}
  231. </p>
  232. </div>
  233. </div>
  234. </div>
  235. )}
  236. </CardContent>
  237. </Card>
  238. {/* LDAP Server Configuration */}
  239. <Card id="card-ldap-server">
  240. <CardHeader>
  241. <h2 className="text-lg font-semibold text-white">
  242. {t('settings.ldap.serverConfig') || 'LDAP Server Configuration'}
  243. </h2>
  244. </CardHeader>
  245. <CardContent>
  246. <div className="space-y-3">
  247. {/* Server URL + Security (side by side) */}
  248. <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
  249. <div className="md:col-span-2">
  250. <label className="block text-sm font-medium text-bambu-gray mb-1">
  251. {t('settings.ldap.serverUrl') || 'Server URL'}
  252. </label>
  253. <input
  254. type="text"
  255. className={inputClasses}
  256. placeholder="ldaps://ldap.example.com:636"
  257. value={form.ldap_server_url}
  258. onChange={e => setForm({ ...form, ldap_server_url: e.target.value })}
  259. />
  260. <p className="text-xs text-bambu-gray mt-1">
  261. {t('settings.ldap.serverUrlHint') || 'Use ldaps:// for SSL or ldap:// with StartTLS'}
  262. </p>
  263. </div>
  264. <div>
  265. <label className="block text-sm font-medium text-bambu-gray mb-1">
  266. {t('settings.ldap.security') || 'Security'}
  267. </label>
  268. <div className="flex gap-2">
  269. {(['starttls', 'ldaps'] as const).map(sec => (
  270. <button
  271. key={sec}
  272. onClick={() => setForm({ ...form, ldap_security: sec })}
  273. className={`flex-1 px-2 py-2 rounded-lg text-sm font-medium transition-colors ${
  274. form.ldap_security === sec
  275. ? 'bg-bambu-green text-black'
  276. : 'bg-bambu-dark-secondary text-bambu-gray hover:text-white border border-bambu-dark-tertiary'
  277. }`}
  278. >
  279. {sec === 'starttls' ? 'StartTLS' : 'LDAPS'}
  280. </button>
  281. ))}
  282. </div>
  283. <p className="text-xs text-bambu-gray mt-1">
  284. {t('settings.ldap.securityHint') || `Default port: ${SECURITY_PORT_MAP[form.ldap_security]}`}
  285. </p>
  286. </div>
  287. </div>
  288. {/* Bind DN + Password (side by side) */}
  289. <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
  290. <div>
  291. <label className="block text-sm font-medium text-bambu-gray mb-1">
  292. {t('settings.ldap.bindDn') || 'Bind DN (Service Account)'}
  293. </label>
  294. <input
  295. type="text"
  296. className={inputClasses}
  297. placeholder="cn=service-account,ou=service,dc=example,dc=com"
  298. value={form.ldap_bind_dn}
  299. onChange={e => setForm({ ...form, ldap_bind_dn: e.target.value })}
  300. />
  301. </div>
  302. <div>
  303. <label className="block text-sm font-medium text-bambu-gray mb-1">
  304. {t('settings.ldap.bindPassword') || 'Bind Password'}
  305. </label>
  306. <input
  307. type="password"
  308. className={inputClasses}
  309. placeholder={settings?.ldap_bind_dn ? '••••••••' : ''}
  310. value={form.ldap_bind_password}
  311. onChange={e => setForm({ ...form, ldap_bind_password: e.target.value })}
  312. />
  313. {bindPasswordNeedsReentry && (
  314. <p className="text-xs mt-1 text-yellow-400">{t('common.secretReenter')}</p>
  315. )}
  316. </div>
  317. </div>
  318. {/* Search Base + User Filter (side by side) */}
  319. <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
  320. <div>
  321. <label className="block text-sm font-medium text-bambu-gray mb-1">
  322. {t('settings.ldap.searchBase') || 'Search Base DN'}
  323. </label>
  324. <input
  325. type="text"
  326. className={inputClasses}
  327. placeholder="ou=users,dc=example,dc=com"
  328. value={form.ldap_search_base}
  329. onChange={e => setForm({ ...form, ldap_search_base: e.target.value })}
  330. />
  331. </div>
  332. <div>
  333. <label className="block text-sm font-medium text-bambu-gray mb-1">
  334. {t('settings.ldap.userFilter') || 'User Search Filter'}
  335. </label>
  336. <input
  337. type="text"
  338. className={inputClasses}
  339. placeholder="(sAMAccountName={username})"
  340. value={form.ldap_user_filter}
  341. onChange={e => setForm({ ...form, ldap_user_filter: e.target.value })}
  342. />
  343. </div>
  344. </div>
  345. {/* Advanced (collapsed by default) */}
  346. <Collapsible
  347. summary={
  348. <span className="text-sm font-medium text-bambu-gray">
  349. {t('settings.ldap.advanced') || 'Advanced'}
  350. </span>
  351. }
  352. className="border-t border-bambu-dark-tertiary pt-3"
  353. summaryClassName="py-1"
  354. >
  355. <div className="space-y-3">
  356. {/* Auto Provision */}
  357. <div className="flex items-center justify-between">
  358. <div>
  359. <label className="block text-sm font-medium text-white">
  360. {t('settings.ldap.autoProvision') || 'Auto-provision users'}
  361. </label>
  362. <p className="text-xs text-bambu-gray mt-0.5">
  363. {t('settings.ldap.autoProvisionHint') || 'Automatically create a BamBuddy account on first LDAP login'}
  364. </p>
  365. </div>
  366. <button
  367. onClick={() => setForm({ ...form, ldap_auto_provision: !form.ldap_auto_provision })}
  368. className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${
  369. form.ldap_auto_provision ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  370. }`}
  371. >
  372. <span
  373. className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
  374. form.ldap_auto_provision ? 'translate-x-6' : 'translate-x-1'
  375. }`}
  376. />
  377. </button>
  378. </div>
  379. {/* Default Group (fallback for users with no mapped groups) */}
  380. <div>
  381. <label className="block text-sm font-medium text-bambu-gray mb-1">
  382. {t('settings.ldap.defaultGroup') || 'Default group'}
  383. </label>
  384. <select
  385. className={inputClasses}
  386. value={form.ldap_default_group}
  387. onChange={e => setForm({ ...form, ldap_default_group: e.target.value })}
  388. >
  389. <option value="">{t('settings.ldap.defaultGroupNone') || '— None (reject login) —'}</option>
  390. {groups.map(g => (
  391. <option key={g.id} value={g.name}>{g.name}</option>
  392. ))}
  393. </select>
  394. <p className="text-xs text-bambu-gray mt-1">
  395. {t('settings.ldap.defaultGroupHint') || 'Fallback group assigned when an LDAP user authenticates but is not listed in any mapped group. Leave empty to leave unmapped users without permissions.'}
  396. </p>
  397. </div>
  398. {/* Group Mapping */}
  399. <div>
  400. <label className="block text-sm font-medium text-bambu-gray mb-1">
  401. {t('settings.ldap.groupMapping') || 'Group Mapping (JSON)'}
  402. </label>
  403. <textarea
  404. className={`${inputClasses} font-mono text-sm`}
  405. rows={4}
  406. placeholder={'{\n "CN=PrintFarm_Admins,OU=Groups,DC=example,DC=com": "Administrators",\n "CN=PrintFarm_Users,OU=Groups,DC=example,DC=com": "Operators"\n}'}
  407. value={form.ldap_group_mapping}
  408. onChange={e => setForm({ ...form, ldap_group_mapping: e.target.value })}
  409. />
  410. <p className="text-xs text-bambu-gray mt-1">
  411. {t('settings.ldap.groupMappingHint') || 'Map LDAP group DNs to BamBuddy groups. Available groups: '}{groups.map(g => g.name).join(', ')}
  412. </p>
  413. </div>
  414. </div>
  415. </Collapsible>
  416. {/* Action Buttons */}
  417. <div className="flex gap-3 pt-2">
  418. <Button
  419. onClick={handleSave}
  420. disabled={saveMutation.isPending}
  421. >
  422. {saveMutation.isPending ? (
  423. <Loader2 className="w-4 h-4 animate-spin" />
  424. ) : (
  425. <CheckCircle className="w-4 h-4" />
  426. )}
  427. {t('common.save') || 'Save'}
  428. </Button>
  429. <Button
  430. variant="secondary"
  431. onClick={() => testMutation.mutate()}
  432. disabled={testMutation.isPending}
  433. >
  434. {testMutation.isPending ? (
  435. <Loader2 className="w-4 h-4 animate-spin" />
  436. ) : (
  437. <Send className="w-4 h-4" />
  438. )}
  439. {t('settings.ldap.testConnection') || 'Test Connection'}
  440. </Button>
  441. </div>
  442. </div>
  443. </CardContent>
  444. </Card>
  445. </div>
  446. );
  447. }