LDAPSettings.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. mutationFn: () => api.testLDAP(),
  106. onSuccess: (data: { success: boolean; message: string }) => {
  107. showToast(data.message, data.success ? 'success' : 'error');
  108. },
  109. onError: (error: Error) => {
  110. showToast(error.message, 'error');
  111. },
  112. });
  113. const handleSave = () => {
  114. if (!form.ldap_server_url) {
  115. showToast(t('settings.ldap.errors.serverRequired') || 'LDAP server URL is required', 'error');
  116. return;
  117. }
  118. if (!form.ldap_search_base) {
  119. showToast(t('settings.ldap.errors.searchBaseRequired') || 'Search base DN is required', 'error');
  120. return;
  121. }
  122. // Build the update payload — only include password if user entered one
  123. const update: Record<string, unknown> = {
  124. ldap_server_url: form.ldap_server_url,
  125. ldap_bind_dn: form.ldap_bind_dn,
  126. ldap_search_base: form.ldap_search_base,
  127. ldap_user_filter: form.ldap_user_filter,
  128. ldap_security: form.ldap_security,
  129. ldap_group_mapping: form.ldap_group_mapping,
  130. ldap_auto_provision: form.ldap_auto_provision,
  131. ldap_default_group: form.ldap_default_group,
  132. };
  133. if (form.ldap_bind_password) {
  134. update.ldap_bind_password = form.ldap_bind_password;
  135. }
  136. saveMutation.mutate(update as Partial<AppSettings>);
  137. };
  138. const handleToggle = () => {
  139. if (!authEnabled) {
  140. showToast(t('settings.ldap.errors.enableAuthFirst') || 'Enable authentication first', 'error');
  141. return;
  142. }
  143. if (!ldapStatus?.ldap_enabled && !ldapStatus?.ldap_configured) {
  144. showToast(t('settings.ldap.errors.configureLdapFirst') || 'Save LDAP settings first', 'error');
  145. return;
  146. }
  147. toggleMutation.mutate(!ldapStatus?.ldap_enabled);
  148. };
  149. if (isLoading) {
  150. return (
  151. <div className="flex items-center justify-center p-12">
  152. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  153. </div>
  154. );
  155. }
  156. const ldapEnabled = ldapStatus?.ldap_enabled ?? false;
  157. 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";
  158. return (
  159. <div className="space-y-3">
  160. {/* LDAP Toggle */}
  161. <Card id="card-ldap-toggle">
  162. <CardHeader>
  163. <div className="flex items-center justify-between">
  164. <div className="flex items-center gap-2">
  165. <Shield className="w-5 h-5 text-bambu-green" />
  166. <h2 className="text-lg font-semibold text-white">
  167. {t('settings.ldap.title') || 'LDAP Authentication'}
  168. </h2>
  169. </div>
  170. <Button
  171. onClick={handleToggle}
  172. disabled={toggleMutation.isPending}
  173. variant={ldapEnabled ? 'danger' : 'primary'}
  174. >
  175. {ldapEnabled ? (
  176. <>
  177. <Unlock className="w-4 h-4" />
  178. {t('common.disable') || 'Disable'}
  179. </>
  180. ) : (
  181. <>
  182. <Lock className="w-4 h-4" />
  183. {t('common.enable') || 'Enable'}
  184. </>
  185. )}
  186. </Button>
  187. </div>
  188. </CardHeader>
  189. <CardContent>
  190. {ldapEnabled ? (
  191. <div className="bg-green-50 dark:bg-green-500/10 border border-green-300 dark:border-green-500/30 rounded-lg p-4">
  192. <div className="flex items-start gap-3">
  193. <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400 mt-0.5 flex-shrink-0" />
  194. <div className="space-y-2">
  195. <p className="text-white font-medium">
  196. {t('settings.ldap.enabledDesc') || 'LDAP authentication is enabled'}
  197. </p>
  198. <ul className="text-sm text-green-700 dark:text-green-300 space-y-1 list-disc list-inside">
  199. <li>{t('settings.ldap.feature1') || 'Users can login with LDAP credentials'}</li>
  200. <li>{t('settings.ldap.feature2') || 'Local admin account remains as fallback'}</li>
  201. <li>{t('settings.ldap.feature3') || 'LDAP groups are mapped to BamBuddy groups on login'}</li>
  202. </ul>
  203. </div>
  204. </div>
  205. </div>
  206. ) : (
  207. <div className="bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg p-4">
  208. <div className="flex items-start gap-3">
  209. <AlertTriangle className="w-5 h-5 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  210. <div>
  211. <p className="text-white font-medium">
  212. {t('settings.ldap.disabledDesc') || 'LDAP authentication is disabled'}
  213. </p>
  214. <p className="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
  215. {t('settings.ldap.disabledHint') || 'Configure and save LDAP settings below, then enable.'}
  216. </p>
  217. </div>
  218. </div>
  219. </div>
  220. )}
  221. </CardContent>
  222. </Card>
  223. {/* LDAP Server Configuration */}
  224. <Card id="card-ldap-server">
  225. <CardHeader>
  226. <h2 className="text-lg font-semibold text-white">
  227. {t('settings.ldap.serverConfig') || 'LDAP Server Configuration'}
  228. </h2>
  229. </CardHeader>
  230. <CardContent>
  231. <div className="space-y-3">
  232. {/* Server URL + Security (side by side) */}
  233. <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
  234. <div className="md:col-span-2">
  235. <label className="block text-sm font-medium text-bambu-gray mb-1">
  236. {t('settings.ldap.serverUrl') || 'Server URL'}
  237. </label>
  238. <input
  239. type="text"
  240. className={inputClasses}
  241. placeholder="ldaps://ldap.example.com:636"
  242. value={form.ldap_server_url}
  243. onChange={e => setForm({ ...form, ldap_server_url: e.target.value })}
  244. />
  245. <p className="text-xs text-bambu-gray mt-1">
  246. {t('settings.ldap.serverUrlHint') || 'Use ldaps:// for SSL or ldap:// with StartTLS'}
  247. </p>
  248. </div>
  249. <div>
  250. <label className="block text-sm font-medium text-bambu-gray mb-1">
  251. {t('settings.ldap.security') || 'Security'}
  252. </label>
  253. <div className="flex gap-2">
  254. {(['starttls', 'ldaps'] as const).map(sec => (
  255. <button
  256. key={sec}
  257. onClick={() => setForm({ ...form, ldap_security: sec })}
  258. className={`flex-1 px-2 py-2 rounded-lg text-sm font-medium transition-colors ${
  259. form.ldap_security === sec
  260. ? 'bg-bambu-green text-black'
  261. : 'bg-bambu-dark-secondary text-bambu-gray hover:text-white border border-bambu-dark-tertiary'
  262. }`}
  263. >
  264. {sec === 'starttls' ? 'StartTLS' : 'LDAPS'}
  265. </button>
  266. ))}
  267. </div>
  268. <p className="text-xs text-bambu-gray mt-1">
  269. {t('settings.ldap.securityHint') || `Default port: ${SECURITY_PORT_MAP[form.ldap_security]}`}
  270. </p>
  271. </div>
  272. </div>
  273. {/* Bind DN + Password (side by side) */}
  274. <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
  275. <div>
  276. <label className="block text-sm font-medium text-bambu-gray mb-1">
  277. {t('settings.ldap.bindDn') || 'Bind DN (Service Account)'}
  278. </label>
  279. <input
  280. type="text"
  281. className={inputClasses}
  282. placeholder="cn=service-account,ou=service,dc=example,dc=com"
  283. value={form.ldap_bind_dn}
  284. onChange={e => setForm({ ...form, ldap_bind_dn: e.target.value })}
  285. />
  286. </div>
  287. <div>
  288. <label className="block text-sm font-medium text-bambu-gray mb-1">
  289. {t('settings.ldap.bindPassword') || 'Bind Password'}
  290. </label>
  291. <input
  292. type="password"
  293. className={inputClasses}
  294. placeholder={settings?.ldap_bind_dn ? '••••••••' : ''}
  295. value={form.ldap_bind_password}
  296. onChange={e => setForm({ ...form, ldap_bind_password: e.target.value })}
  297. />
  298. </div>
  299. </div>
  300. {/* Search Base + User Filter (side by side) */}
  301. <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
  302. <div>
  303. <label className="block text-sm font-medium text-bambu-gray mb-1">
  304. {t('settings.ldap.searchBase') || 'Search Base DN'}
  305. </label>
  306. <input
  307. type="text"
  308. className={inputClasses}
  309. placeholder="ou=users,dc=example,dc=com"
  310. value={form.ldap_search_base}
  311. onChange={e => setForm({ ...form, ldap_search_base: e.target.value })}
  312. />
  313. </div>
  314. <div>
  315. <label className="block text-sm font-medium text-bambu-gray mb-1">
  316. {t('settings.ldap.userFilter') || 'User Search Filter'}
  317. </label>
  318. <input
  319. type="text"
  320. className={inputClasses}
  321. placeholder="(sAMAccountName={username})"
  322. value={form.ldap_user_filter}
  323. onChange={e => setForm({ ...form, ldap_user_filter: e.target.value })}
  324. />
  325. </div>
  326. </div>
  327. {/* Advanced (collapsed by default) */}
  328. <Collapsible
  329. summary={
  330. <span className="text-sm font-medium text-bambu-gray">
  331. {t('settings.ldap.advanced') || 'Advanced'}
  332. </span>
  333. }
  334. className="border-t border-bambu-dark-tertiary pt-3"
  335. summaryClassName="py-1"
  336. >
  337. <div className="space-y-3">
  338. {/* Auto Provision */}
  339. <div className="flex items-center justify-between">
  340. <div>
  341. <label className="block text-sm font-medium text-white">
  342. {t('settings.ldap.autoProvision') || 'Auto-provision users'}
  343. </label>
  344. <p className="text-xs text-bambu-gray mt-0.5">
  345. {t('settings.ldap.autoProvisionHint') || 'Automatically create a BamBuddy account on first LDAP login'}
  346. </p>
  347. </div>
  348. <button
  349. onClick={() => setForm({ ...form, ldap_auto_provision: !form.ldap_auto_provision })}
  350. className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${
  351. form.ldap_auto_provision ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  352. }`}
  353. >
  354. <span
  355. className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
  356. form.ldap_auto_provision ? 'translate-x-6' : 'translate-x-1'
  357. }`}
  358. />
  359. </button>
  360. </div>
  361. {/* Default Group (fallback for users with no mapped groups) */}
  362. <div>
  363. <label className="block text-sm font-medium text-bambu-gray mb-1">
  364. {t('settings.ldap.defaultGroup') || 'Default group'}
  365. </label>
  366. <select
  367. className={inputClasses}
  368. value={form.ldap_default_group}
  369. onChange={e => setForm({ ...form, ldap_default_group: e.target.value })}
  370. >
  371. <option value="">{t('settings.ldap.defaultGroupNone') || '— None (reject login) —'}</option>
  372. {groups.map(g => (
  373. <option key={g.id} value={g.name}>{g.name}</option>
  374. ))}
  375. </select>
  376. <p className="text-xs text-bambu-gray mt-1">
  377. {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.'}
  378. </p>
  379. </div>
  380. {/* Group Mapping */}
  381. <div>
  382. <label className="block text-sm font-medium text-bambu-gray mb-1">
  383. {t('settings.ldap.groupMapping') || 'Group Mapping (JSON)'}
  384. </label>
  385. <textarea
  386. className={`${inputClasses} font-mono text-sm`}
  387. rows={4}
  388. placeholder={'{\n "CN=PrintFarm_Admins,OU=Groups,DC=example,DC=com": "Administrators",\n "CN=PrintFarm_Users,OU=Groups,DC=example,DC=com": "Operators"\n}'}
  389. value={form.ldap_group_mapping}
  390. onChange={e => setForm({ ...form, ldap_group_mapping: e.target.value })}
  391. />
  392. <p className="text-xs text-bambu-gray mt-1">
  393. {t('settings.ldap.groupMappingHint') || 'Map LDAP group DNs to BamBuddy groups. Available groups: '}{groups.map(g => g.name).join(', ')}
  394. </p>
  395. </div>
  396. </div>
  397. </Collapsible>
  398. {/* Action Buttons */}
  399. <div className="flex gap-3 pt-2">
  400. <Button
  401. onClick={handleSave}
  402. disabled={saveMutation.isPending}
  403. >
  404. {saveMutation.isPending ? (
  405. <Loader2 className="w-4 h-4 animate-spin" />
  406. ) : (
  407. <CheckCircle className="w-4 h-4" />
  408. )}
  409. {t('common.save') || 'Save'}
  410. </Button>
  411. <Button
  412. variant="secondary"
  413. onClick={() => testMutation.mutate()}
  414. disabled={testMutation.isPending}
  415. >
  416. {testMutation.isPending ? (
  417. <Loader2 className="w-4 h-4 animate-spin" />
  418. ) : (
  419. <Send className="w-4 h-4" />
  420. )}
  421. {t('settings.ldap.testConnection') || 'Test Connection'}
  422. </Button>
  423. </div>
  424. </div>
  425. </CardContent>
  426. </Card>
  427. </div>
  428. );
  429. }