ldap_config.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. {% extends 'admin/base.html' %}
  2. {% block title %}{{ _("LDAP / Active Directory | Admin Squid") }}{% endblock %}
  3. {% block content %}
  4. <div class="max-w-7xl mx-auto space-y-6" x-data="ldapApp()" x-init="init()">
  5. <!-- ── Header ────────────────────────────────────────────────────── -->
  6. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  7. <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
  8. <div>
  9. <h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
  10. <i class="fas fa-network-wired text-blue-600"></i>
  11. {{ _("LDAP / Active Directory") }}
  12. </h2>
  13. <p class="text-sm text-gray-500 mt-1">{{ _("Configura la conexión y explora el directorio.") }}</p>
  14. </div>
  15. <!-- Connection status badge -->
  16. <div>
  17. <span :class="statusBadgeClass()" class="inline-flex items-center gap-2 px-4 py-2 rounded-full text-sm font-semibold">
  18. <span class="w-2 h-2 rounded-full" :class="statusDotClass()"></span>
  19. <span x-text="connectionStatus"></span>
  20. </span>
  21. </div>
  22. </div>
  23. </div>
  24. <!-- ── Stats Cards ───────────────────────────────────────────────── -->
  25. <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
  26. <div class="bg-white rounded-lg shadow border border-gray-200 p-6 flex items-center gap-4">
  27. <div class="w-14 h-14 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
  28. <i class="fas fa-users text-blue-600 text-2xl"></i>
  29. </div>
  30. <div>
  31. <p class="text-sm text-gray-500">{{ _("Total Usuarios") }}</p>
  32. <p class="text-3xl font-bold text-gray-800" x-text="stats.users ?? '—'"></p>
  33. </div>
  34. <button @click="loadStats()" :disabled="loadingStats" title="{{ _("Actualizar") }}" class="ml-auto text-gray-400 hover:text-blue-600 transition-colors disabled:opacity-40">
  35. <i class="fas fa-sync-alt" :class="loadingStats ? 'animate-spin' : ''"></i>
  36. </button>
  37. </div>
  38. <div class="bg-white rounded-lg shadow border border-gray-200 p-6 flex items-center gap-4">
  39. <div class="w-14 h-14 rounded-full bg-indigo-100 flex items-center justify-center flex-shrink-0">
  40. <i class="fas fa-layer-group text-indigo-600 text-2xl"></i>
  41. </div>
  42. <div>
  43. <p class="text-sm text-gray-500">{{ _("Total Grupos") }}</p>
  44. <p class="text-3xl font-bold text-gray-800" x-text="stats.groups ?? '—'"></p>
  45. </div>
  46. <button @click="loadStats()" :disabled="loadingStats" title="{{ _("Actualizar") }}" class="ml-auto text-gray-400 hover:text-indigo-600 transition-colors disabled:opacity-40">
  47. <i class="fas fa-sync-alt" :class="loadingStats ? 'animate-spin' : ''"></i>
  48. </button>
  49. </div>
  50. </div>
  51. <!-- ── Main grid ─────────────────────────────────────────────────── -->
  52. <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
  53. <!-- LEFT – Configuration form -->
  54. <div class="xl:col-span-1 bg-white shadow rounded-lg border border-gray-200 p-6 space-y-4">
  55. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
  56. <i class="fas fa-cog text-gray-500"></i> {{ _("Configuración de conexión") }}
  57. </h3>
  58. <div>
  59. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Servidor (host)") }}</label>
  60. <input x-model="cfg.host" type="text" placeholder="ldap.empresa.com"
  61. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  62. </div>
  63. <div class="grid grid-cols-2 gap-3">
  64. <div>
  65. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Puerto") }}</label>
  66. <input x-model.number="cfg.port" type="number" placeholder="389"
  67. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  68. </div>
  69. <div>
  70. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Autenticación") }}</label>
  71. <select x-model="cfg.auth_type"
  72. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
  73. <option value="SIMPLE">{{ _("SIMPLE (LDAP)") }}</option>
  74. <option value="NTLM">{{ _("NTLM (AD)") }}</option>
  75. </select>
  76. </div>
  77. </div>
  78. <div class="flex items-center gap-2">
  79. <input x-model="cfg.use_ssl" type="checkbox" id="use_ssl" class="rounded text-blue-600" />
  80. <label for="use_ssl" class="text-sm text-gray-700">{{ _("Usar SSL / LDAPS") }}</label>
  81. </div>
  82. <div>
  83. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Bind DN / Usuario") }}</label>
  84. <input x-model="cfg.bind_dn" type="text" placeholder="{{ _("CN=admin,DC=empresa,DC=com") }}"
  85. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  86. </div>
  87. <div>
  88. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Contraseña Bind") }}</label>
  89. <input x-model="cfg.bind_password" type="password" autocomplete="current-password" placeholder="••••••••"
  90. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  91. </div>
  92. <div>
  93. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Base DN") }}</label>
  94. <input x-model="cfg.base_dn" type="text" placeholder="{{ _("DC=empresa,DC=com") }}"
  95. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  96. </div>
  97. <!-- Action buttons -->
  98. <div class="flex gap-2 pt-2">
  99. <button @click="saveConfig()" :disabled="savingCfg"
  100. class="flex-1 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors flex items-center justify-center gap-2">
  101. <i class="fas fa-save"></i>
  102. <span x-text="savingCfg ? '{{ _('Guardando…') }}' : '{{ _('Guardar') }}'"></span>
  103. </button>
  104. <button @click="testConnection()" :disabled="testingConn"
  105. class="flex-1 bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors flex items-center justify-center gap-2">
  106. <i class="fas fa-plug"></i>
  107. <span x-text="testingConn ? '{{ _('Probando…') }}' : '{{ _('Probar') }}'"></span>
  108. </button>
  109. </div>
  110. <div x-show="clientNotice" class="text-xs text-gray-500 italic mt-2">
  111. <span x-text="clientNotice"></span>
  112. </div>
  113. <!-- Inline alert -->
  114. <template x-if="cfgAlert.message">
  115. <div :class="cfgAlert.type === 'success' ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'"
  116. class="rounded-lg border p-3 text-sm flex items-start gap-2">
  117. <i :class="cfgAlert.type === 'success' ? 'fas fa-check-circle text-green-600' : 'fas fa-exclamation-circle text-red-600'" class="mt-0.5"></i>
  118. <span x-text="cfgAlert.message"></span>
  119. </div>
  120. </template>
  121. </div>
  122. <!-- RIGHT – Search & membership panels -->
  123. <div class="xl:col-span-2 space-y-6">
  124. <!-- Search Users -->
  125. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  126. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
  127. <i class="fas fa-user-search text-blue-500"></i> {{ _("Buscar Usuarios") }}
  128. </h3>
  129. <div class="flex gap-2 mb-4">
  130. <input x-model="userQuery" @keydown.enter="searchUsers()" type="text"
  131. placeholder="{{ _("Nombre, usuario, email…") }}"
  132. class="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  133. <button @click="searchUsers()" :disabled="searchingUsers"
  134. class="bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white px-4 py-2 rounded-lg text-sm font-semibold transition-colors flex items-center gap-2">
  135. <i class="fas fa-search" :class="searchingUsers ? 'animate-pulse' : ''"></i>
  136. {{ _("Buscar") }}
  137. </button>
  138. </div>
  139. <!-- Results table -->
  140. <div class="overflow-x-auto">
  141. <table class="min-w-full text-sm" x-show="userResults.length > 0">
  142. <thead class="bg-gray-50">
  143. <tr>
  144. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">{{ _("Nombre") }}</th>
  145. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden sm:table-cell">{{ _("Usuario") }}</th>
  146. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden md:table-cell">Email</th>
  147. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden lg:table-cell">{{ _("Departamento") }}</th>
  148. <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">{{ _("Grupos") }}</th>
  149. </tr>
  150. </thead>
  151. <tbody class="divide-y divide-gray-100">
  152. <template x-for="u in userResults" :key="u.dn">
  153. <tr class="hover:bg-gray-50 transition-colors">
  154. <td class="px-3 py-2 font-medium text-gray-900" x-text="u.display_name || u.cn"></td>
  155. <td class="px-3 py-2 text-gray-600 hidden sm:table-cell" x-text="u.username"></td>
  156. <td class="px-3 py-2 text-gray-600 hidden md:table-cell" x-text="u.email"></td>
  157. <td class="px-3 py-2 text-gray-600 hidden lg:table-cell" x-text="u.department"></td>
  158. <td class="px-3 py-2 text-center">
  159. <button @click="loadUserGroups(u.username)"
  160. class="text-indigo-600 hover:text-indigo-800 text-xs font-semibold hover:underline transition-colors"
  161. title="{{ _("Ver grupos del usuario") }}">
  162. <i class="fas fa-sitemap mr-1"></i>{{ _("Ver grupos") }}
  163. </button>
  164. </td>
  165. </tr>
  166. </template>
  167. </tbody>
  168. </table>
  169. <p x-show="userResults.length === 0 && userSearched" class="text-sm text-gray-500 text-center py-4">
  170. <i class="fas fa-inbox mr-2"></i>{{ _("No se encontraron usuarios.") }}
  171. </p>
  172. </div>
  173. </div>
  174. <!-- Search Groups -->
  175. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  176. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
  177. <i class="fas fa-layer-group text-indigo-500"></i> {{ _("Buscar Grupos") }}
  178. </h3>
  179. <div class="flex gap-2 mb-4">
  180. <input x-model="groupQuery" @keydown.enter="searchGroups()" type="text"
  181. placeholder="{{ _("Nombre del grupo…") }}"
  182. class="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" />
  183. <button @click="searchGroups()" :disabled="searchingGroups"
  184. class="bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white px-4 py-2 rounded-lg text-sm font-semibold transition-colors flex items-center gap-2">
  185. <i class="fas fa-search" :class="searchingGroups ? 'animate-pulse' : ''"></i>
  186. {{ _("Buscar") }}
  187. </button>
  188. </div>
  189. <div class="overflow-x-auto">
  190. <table class="min-w-full text-sm" x-show="groupResults.length > 0">
  191. <thead class="bg-gray-50">
  192. <tr>
  193. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">{{ _("Nombre") }}</th>
  194. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden sm:table-cell">{{ _("Descripción") }}</th>
  195. <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">{{ _("Miembros") }}</th>
  196. </tr>
  197. </thead>
  198. <tbody class="divide-y divide-gray-100">
  199. <template x-for="g in groupResults" :key="g.dn">
  200. <tr class="hover:bg-gray-50 transition-colors">
  201. <td class="px-3 py-2 font-medium text-gray-900" x-text="g.cn"></td>
  202. <td class="px-3 py-2 text-gray-600 hidden sm:table-cell" x-text="g.description || '—'"></td>
  203. <td class="px-3 py-2 text-center">
  204. <span class="bg-indigo-100 text-indigo-700 text-xs font-semibold px-2 py-0.5 rounded-full" x-text="g.member_count"></span>
  205. </td>
  206. </tr>
  207. </template>
  208. </tbody>
  209. </table>
  210. <p x-show="groupResults.length === 0 && groupSearched" class="text-sm text-gray-500 text-center py-4">
  211. <i class="fas fa-inbox mr-2"></i>{{ _("No se encontraron grupos.") }}
  212. </p>
  213. </div>
  214. </div>
  215. <!-- User Groups membership panel -->
  216. <div class="bg-white shadow rounded-lg border border-gray-200 p-6" x-show="membershipTarget">
  217. <div class="flex items-center justify-between mb-4">
  218. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
  219. <i class="fas fa-sitemap text-purple-500"></i>
  220. {{ _("Grupos de") }} <span class="text-purple-700 ml-1" x-text="membershipTarget"></span>
  221. </h3>
  222. <button @click="clearMembership()" class="text-gray-400 hover:text-gray-600 transition-colors text-xs">
  223. <i class="fas fa-times"></i> {{ _("Limpiar") }}
  224. </button>
  225. </div>
  226. <!-- Loading spinner -->
  227. <div x-show="loadingMembership" class="flex items-center justify-center py-8 text-gray-400">
  228. <i class="fas fa-circle-notch fa-spin text-2xl mr-3"></i> {{ _("Cargando grupos…") }}
  229. </div>
  230. <!-- Error -->
  231. <div x-show="!loadingMembership && membershipError"
  232. class="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg p-3 flex items-center gap-2">
  233. <i class="fas fa-exclamation-circle"></i>
  234. <span x-text="membershipError"></span>
  235. </div>
  236. <!-- Groups list -->
  237. <div x-show="!loadingMembership && !membershipError && membershipGroups.length > 0">
  238. <p class="text-xs text-gray-500 mb-3">
  239. <span x-text="membershipGroups.length"></span> {{ _("grupo(s) encontrado(s)") }}
  240. </p>
  241. <div class="flex flex-wrap gap-2">
  242. <template x-for="g in membershipGroups" :key="g.dn">
  243. <span class="inline-flex items-center gap-1 bg-purple-50 border border-purple-200 text-purple-700 text-xs font-medium px-3 py-1.5 rounded-full">
  244. <i class="fas fa-layer-group text-purple-400"></i>
  245. <span x-text="g.cn"></span>
  246. </span>
  247. </template>
  248. </div>
  249. </div>
  250. <p x-show="!loadingMembership && !membershipError && membershipGroups.length === 0"
  251. class="text-sm text-gray-500 text-center py-4">
  252. <i class="fas fa-inbox mr-2"></i>{{ _("Este usuario no pertenece a ningún grupo.") }}
  253. </p>
  254. </div>
  255. </div>
  256. </div>
  257. </div>
  258. <script type="application/json" id="ldap-config-data">
  259. {{ cfg | tojson | safe }}
  260. </script>
  261. <script>
  262. function ldapApp() {
  263. const initialCfg = JSON.parse(document.getElementById('ldap-config-data').textContent || '{}');
  264. return {
  265. // Config form
  266. cfg: {
  267. host: initialCfg.host || "",
  268. port: initialCfg.port || 389,
  269. use_ssl: initialCfg.use_ssl || false,
  270. auth_type: initialCfg.auth_type || "SIMPLE",
  271. bind_dn: initialCfg.bind_dn || "",
  272. bind_password: initialCfg.bind_password || "",
  273. base_dn: initialCfg.base_dn || "",
  274. },
  275. savingCfg: false,
  276. testingConn: false,
  277. cfgAlert: { message: "", type: "" },
  278. // Connection status
  279. connectionStatus: "{{ _('Sin probar') }}",
  280. clientNotice: "",
  281. // Stats
  282. stats: { users: null, groups: null },
  283. loadingStats: false,
  284. // User search
  285. userQuery: "",
  286. userResults: [],
  287. searchingUsers: false,
  288. userSearched: false,
  289. // Group search
  290. groupQuery: "",
  291. groupResults: [],
  292. searchingGroups: false,
  293. groupSearched: false,
  294. // Membership panel
  295. membershipTarget: "",
  296. membershipGroups: [],
  297. loadingMembership: false,
  298. membershipError: "",
  299. storageKey: "squidstats_ldap_config",
  300. // ── Helpers ────────────────────────────────────────────────────
  301. csrfToken() {
  302. return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
  303. },
  304. init() {
  305. if (this.cfg.host || this.cfg.base_dn || this.cfg.bind_dn) {
  306. this.clientNotice = '{{ _('Configuración cargada desde la base de datos.') }}';
  307. }
  308. this.$watch('cfg', () => { this.saveLocalConfig(); }, { deep: true });
  309. },
  310. loadLocalConfig() {
  311. try {
  312. const raw = localStorage.getItem(this.storageKey);
  313. if (!raw) return;
  314. const data = JSON.parse(raw);
  315. if (data && typeof data === 'object') {
  316. const { bind_password, ...safeData } = data;
  317. this.cfg = {
  318. ...this.cfg,
  319. ...safeData,
  320. use_ssl: safeData.use_ssl === true || safeData.use_ssl === 'true',
  321. };
  322. this.clientNotice = '{{ _('Configuración cargada desde el navegador. Los cambios se guardan localmente.') }}';
  323. }
  324. } catch (error) {
  325. console.warn('[LDAP DEBUG] loadLocalConfig error', error);
  326. }
  327. },
  328. saveLocalConfig() {
  329. try {
  330. const { bind_password, ...safeCfg } = this.cfg;
  331. localStorage.setItem(this.storageKey, JSON.stringify(safeCfg));
  332. this.clientNotice = '{{ _('Configuración guardada localmente en el navegador.') }}';
  333. } catch (error) {
  334. console.warn('[LDAP DEBUG] saveLocalConfig error', error);
  335. }
  336. },
  337. clearLocalConfig() {
  338. try {
  339. localStorage.removeItem(this.storageKey);
  340. this.clientNotice = '{{ _('Configuración local eliminada.') }}';
  341. } catch (error) {
  342. console.warn('[LDAP DEBUG] clearLocalConfig error', error);
  343. }
  344. },
  345. statusBadgeClass() {
  346. const map = {
  347. "{{ _('Conectado') }}": "bg-green-100 text-green-800",
  348. "{{ _('Error') }}": "bg-red-100 text-red-800",
  349. "{{ _('Sin probar') }}": "bg-gray-100 text-gray-600",
  350. "{{ _('Probando…') }}": "bg-yellow-100 text-yellow-800",
  351. };
  352. return map[this.connectionStatus] || "bg-gray-100 text-gray-600";
  353. },
  354. statusDotClass() {
  355. const map = {
  356. "{{ _('Conectado') }}": "bg-green-500",
  357. "{{ _('Error') }}": "bg-red-500",
  358. "{{ _('Sin probar') }}": "bg-gray-400",
  359. "{{ _('Probando…') }}": "bg-yellow-400",
  360. };
  361. return map[this.connectionStatus] || "bg-gray-400";
  362. },
  363. showAlert(message, type = "success") {
  364. this.cfgAlert = { message, type };
  365. setTimeout(() => { this.cfgAlert = { message: "", type: "" }; }, 4000);
  366. },
  367. // ── Actions ────────────────────────────────────────────────────
  368. async saveConfig() {
  369. this.savingCfg = true;
  370. try {
  371. const res = await fetch('/admin/api/ldap/save-config', {
  372. method: 'POST',
  373. headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
  374. body: JSON.stringify(this.cfg),
  375. });
  376. const data = await res.json();
  377. this.showAlert(data.message, data.status === 'success' ? 'success' : 'error');
  378. } catch {
  379. this.showAlert('{{ _('Error al guardar la configuración.') }}', 'error');
  380. } finally {
  381. this.savingCfg = false;
  382. }
  383. },
  384. async testConnection() {
  385. this.testingConn = true;
  386. this.connectionStatus = "{{ _('Probando…') }}";
  387. try {
  388. const res = await fetch('/admin/api/ldap/test', {
  389. method: 'POST',
  390. headers: {
  391. 'Content-Type': 'application/json',
  392. 'X-CSRFToken': this.csrfToken(),
  393. },
  394. body: JSON.stringify(this.cfg),
  395. });
  396. const data = await res.json();
  397. this.connectionStatus = data.status === 'success' ? "{{ _('Conectado') }}" : "{{ _('Error') }}";
  398. this.showAlert(data.message, data.status);
  399. if (data.status === 'success') this.loadStats();
  400. } catch (error) {
  401. console.error('[LDAP DEBUG] testConnection error', error);
  402. this.connectionStatus = "{{ _('Error') }}";
  403. this.showAlert('{{ _('Error al conectar.') }}', 'error');
  404. } finally {
  405. this.testingConn = false;
  406. }
  407. },
  408. async loadStats() {
  409. this.loadingStats = true;
  410. try {
  411. const res = await fetch('/admin/api/ldap/stats', {
  412. method: 'POST',
  413. headers: {
  414. 'Content-Type': 'application/json',
  415. 'X-CSRFToken': this.csrfToken(),
  416. },
  417. body: JSON.stringify(this.cfg),
  418. });
  419. const data = await res.json();
  420. if (data.status === 'success') {
  421. this.stats = { users: data.users, groups: data.groups };
  422. } else {
  423. this.showAlert(data.message, 'error');
  424. }
  425. } catch (error) {
  426. console.error('[LDAP DEBUG] loadStats error', error);
  427. } finally {
  428. this.loadingStats = false;
  429. }
  430. },
  431. async searchUsers() {
  432. if (!this.userQuery.trim()) {
  433. if (typeof showNotification === 'function') {
  434. showNotification('{{ _('El campo de búsqueda de usuario no puede estar vacío.') }}', 'error');
  435. }
  436. return;
  437. }
  438. this.searchingUsers = true;
  439. this.userSearched = false;
  440. this.userResults = [];
  441. try {
  442. const res = await fetch('/admin/api/ldap/search-users', {
  443. method: 'POST',
  444. headers: {
  445. 'Content-Type': 'application/json',
  446. 'X-CSRFToken': this.csrfToken(),
  447. },
  448. body: JSON.stringify({ q: this.userQuery, ...this.cfg }),
  449. });
  450. const data = await res.json();
  451. this.userResults = data.results || [];
  452. this.userSearched = true;
  453. } catch (error) {
  454. console.error('[LDAP DEBUG] searchUsers error', error);
  455. this.userSearched = true;
  456. } finally {
  457. this.searchingUsers = false;
  458. }
  459. },
  460. async searchGroups() {
  461. this.searchingGroups = true;
  462. this.groupSearched = false;
  463. this.groupResults = [];
  464. try {
  465. const res = await fetch('/admin/api/ldap/search-groups', {
  466. method: 'POST',
  467. headers: {
  468. 'Content-Type': 'application/json',
  469. 'X-CSRFToken': this.csrfToken(),
  470. },
  471. body: JSON.stringify({ q: this.groupQuery, ...this.cfg }),
  472. });
  473. const data = await res.json();
  474. this.groupResults = data.results || [];
  475. this.groupSearched = true;
  476. } catch (error) {
  477. console.error('[LDAP DEBUG] searchGroups error', error);
  478. this.groupSearched = true;
  479. } finally {
  480. this.searchingGroups = false;
  481. }
  482. },
  483. async loadUserGroups(username) {
  484. this.membershipTarget = username;
  485. this.membershipGroups = [];
  486. this.membershipError = "";
  487. this.loadingMembership = true;
  488. try {
  489. const res = await fetch('/admin/api/ldap/user-groups', {
  490. method: 'POST',
  491. headers: {
  492. 'Content-Type': 'application/json',
  493. 'X-CSRFToken': this.csrfToken(),
  494. },
  495. body: JSON.stringify({ username, ...this.cfg }),
  496. });
  497. const data = await res.json();
  498. if (data.status === 'success') {
  499. this.membershipGroups = data.groups;
  500. } else {
  501. this.membershipError = data.message;
  502. }
  503. } catch (error) {
  504. console.error('[LDAP DEBUG] loadUserGroups error', error);
  505. this.membershipError = 'Error al cargar los grupos del usuario.';
  506. } finally {
  507. this.loadingMembership = false;
  508. }
  509. },
  510. clearMembership() {
  511. this.membershipTarget = "";
  512. this.membershipGroups = [];
  513. this.membershipError = "";
  514. },
  515. };
  516. }
  517. </script>
  518. {% endblock %}