ldap_config.html 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. {% extends 'admin/base.html' %}
  2. {% block title %}{{ _("LDAP/AD y Grupos | Admin Squid") }}{% endblock %}
  3. {% block content %}
  4. <div class="max-w-7xl mx-auto space-y-6" x-data="ldapApp()" x-init="init()">
  5. <div class="bg-white shadow rounded-lg border border-gray-200 p-2">
  6. <nav class="flex flex-wrap gap-2" aria-label="{{ _('LDAP tabs') }}">
  7. <button type="button" @click="activeTab = 'ldap'" :class="activeTab === 'ldap' ? 'bg-blue-600 text-white shadow' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'" class="px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
  8. {{ _("LDAP/AD") }}
  9. </button>
  10. <button type="button" @click="activeTab = 'groups'" :class="activeTab === 'groups' ? 'bg-indigo-600 text-white shadow' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'" class="px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
  11. {{ _("Grupos") }}
  12. </button>
  13. </nav>
  14. </div>
  15. <div x-show="activeTab === 'ldap'" class="space-y-6">
  16. <!-- ── Header ────────────────────────────────────────────────────── -->
  17. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  18. <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
  19. <div>
  20. <h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
  21. <i class="fas fa-network-wired text-blue-600"></i>
  22. {{ _("LDAP/AD") }}
  23. </h2>
  24. <p class="text-sm text-gray-500 mt-1">{{ _("Configura la conexión y explora el directorio.") }}</p>
  25. </div>
  26. <!-- Connection status badge -->
  27. <div>
  28. <span :class="statusBadgeClass()" class="inline-flex items-center gap-2 px-4 py-2 rounded-full text-sm font-semibold">
  29. <span class="w-2 h-2 rounded-full" :class="statusDotClass()"></span>
  30. <span x-text="connectionStatus"></span>
  31. </span>
  32. </div>
  33. </div>
  34. </div>
  35. <!-- ── Stats Cards ───────────────────────────────────────────────── -->
  36. <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
  37. <div class="bg-white rounded-lg shadow border border-gray-200 p-6 flex items-center gap-4">
  38. <div class="w-14 h-14 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
  39. <i class="fas fa-users text-blue-600 text-2xl"></i>
  40. </div>
  41. <div>
  42. <p class="text-sm text-gray-500">{{ _("Total Usuarios") }}</p>
  43. <p class="text-3xl font-bold text-gray-800" x-text="stats.users ?? '—'"></p>
  44. </div>
  45. <button @click="loadStats()" :disabled="loadingStats" title="{{ _("Actualizar") }}" class="ml-auto text-gray-400 hover:text-blue-600 transition-colors disabled:opacity-40">
  46. <i class="fas fa-sync-alt" :class="loadingStats ? 'animate-spin' : ''"></i>
  47. </button>
  48. </div>
  49. <div class="bg-white rounded-lg shadow border border-gray-200 p-6 flex items-center gap-4">
  50. <div class="w-14 h-14 rounded-full bg-indigo-100 flex items-center justify-center flex-shrink-0">
  51. <i class="fas fa-layer-group text-indigo-600 text-2xl"></i>
  52. </div>
  53. <div>
  54. <p class="text-sm text-gray-500">{{ _("Total Grupos") }}</p>
  55. <p class="text-3xl font-bold text-gray-800" x-text="stats.groups ?? '—'"></p>
  56. </div>
  57. <button @click="loadStats()" :disabled="loadingStats" title="{{ _("Actualizar") }}" class="ml-auto text-gray-400 hover:text-indigo-600 transition-colors disabled:opacity-40">
  58. <i class="fas fa-sync-alt" :class="loadingStats ? 'animate-spin' : ''"></i>
  59. </button>
  60. </div>
  61. </div>
  62. <!-- ── Main grid ─────────────────────────────────────────────────── -->
  63. <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
  64. <!-- LEFT – Configuration form -->
  65. <div class="xl:col-span-1 bg-white shadow rounded-lg border border-gray-200 p-6 space-y-4">
  66. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
  67. <i class="fas fa-cog text-gray-500"></i> {{ _("Configuración de conexión") }}
  68. </h3>
  69. <div>
  70. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Servidor (host)") }}</label>
  71. <input x-model="cfg.host" type="text" placeholder="ldap.empresa.com"
  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. </div>
  74. <div class="grid grid-cols-2 gap-3">
  75. <div>
  76. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Puerto") }}</label>
  77. <input x-model.number="cfg.port" type="number" placeholder="389"
  78. 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" />
  79. </div>
  80. <div>
  81. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Autenticación") }}</label>
  82. <select x-model="cfg.auth_type"
  83. 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">
  84. <option value="SIMPLE">{{ _("SIMPLE (LDAP)") }}</option>
  85. <option value="NTLM">{{ _("NTLM (AD)") }}</option>
  86. </select>
  87. </div>
  88. </div>
  89. <div class="flex items-center gap-2">
  90. <input x-model="cfg.use_ssl" type="checkbox" id="use_ssl" class="rounded text-blue-600" />
  91. <label for="use_ssl" class="text-sm text-gray-700">{{ _("Usar SSL / LDAPS") }}</label>
  92. </div>
  93. <div>
  94. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Bind DN / Usuario") }}</label>
  95. <input x-model="cfg.bind_dn" type="text" placeholder="{{ _("CN=admin,DC=empresa,DC=com") }}"
  96. 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" />
  97. </div>
  98. <div>
  99. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Contraseña Bind") }}</label>
  100. <input x-model="cfg.bind_password" type="password" autocomplete="current-password" placeholder="••••••••"
  101. 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" />
  102. </div>
  103. <div>
  104. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Base DN") }}</label>
  105. <input x-model="cfg.base_dn" type="text" placeholder="{{ _("DC=empresa,DC=com") }}"
  106. 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" />
  107. </div>
  108. <!-- Action buttons -->
  109. <div class="flex gap-2 pt-2">
  110. <button @click="saveConfig()" :disabled="savingCfg"
  111. 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">
  112. <i class="fas fa-save"></i>
  113. <span x-text="savingCfg ? '{{ _('Guardando…') }}' : '{{ _('Guardar') }}'"></span>
  114. </button>
  115. <button @click="testConnection()" :disabled="testingConn"
  116. 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">
  117. <i class="fas fa-plug"></i>
  118. <span x-text="testingConn ? '{{ _('Probando…') }}' : '{{ _('Probar') }}'"></span>
  119. </button>
  120. </div>
  121. <div x-show="clientNotice" class="text-xs text-gray-500 italic mt-2">
  122. <span x-text="clientNotice"></span>
  123. </div>
  124. <!-- Inline alert -->
  125. <template x-if="cfgAlert.message">
  126. <div :class="cfgAlert.type === 'success' ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'"
  127. class="rounded-lg border p-3 text-sm flex items-start gap-2">
  128. <i :class="cfgAlert.type === 'success' ? 'fas fa-check-circle text-green-600' : 'fas fa-exclamation-circle text-red-600'" class="mt-0.5"></i>
  129. <span x-text="cfgAlert.message"></span>
  130. </div>
  131. </template>
  132. </div>
  133. <!-- RIGHT – Search & membership panels -->
  134. <div class="xl:col-span-2 space-y-6">
  135. <!-- Search Users -->
  136. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  137. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
  138. <i class="fas fa-user-search text-blue-500"></i> {{ _("Buscar Usuarios") }}
  139. </h3>
  140. <div class="flex gap-2 mb-4">
  141. <input x-model="userQuery" @keydown.enter="searchUsers()" type="text"
  142. placeholder="{{ _("Nombre, usuario, email…") }}"
  143. 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" />
  144. <button @click="searchUsers()" :disabled="searchingUsers"
  145. 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">
  146. <i class="fas fa-search" :class="searchingUsers ? 'animate-pulse' : ''"></i>
  147. {{ _("Buscar") }}
  148. </button>
  149. </div>
  150. <!-- Results table -->
  151. <div class="overflow-x-auto">
  152. <table class="min-w-full text-sm" x-show="userResults.length > 0">
  153. <thead class="bg-gray-50">
  154. <tr>
  155. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">{{ _("Nombre") }}</th>
  156. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden sm:table-cell">{{ _("Usuario") }}</th>
  157. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden md:table-cell">Email</th>
  158. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden lg:table-cell">{{ _("Departamento") }}</th>
  159. <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">{{ _("Grupos") }}</th>
  160. </tr>
  161. </thead>
  162. <tbody class="divide-y divide-gray-100">
  163. <template x-for="u in userResults" :key="u.dn">
  164. <tr class="hover:bg-gray-50 transition-colors">
  165. <td class="px-3 py-2 font-medium text-gray-900" x-text="u.display_name || u.cn"></td>
  166. <td class="px-3 py-2 text-gray-600 hidden sm:table-cell" x-text="u.username"></td>
  167. <td class="px-3 py-2 text-gray-600 hidden md:table-cell" x-text="u.email"></td>
  168. <td class="px-3 py-2 text-gray-600 hidden lg:table-cell" x-text="u.department"></td>
  169. <td class="px-3 py-2 text-center">
  170. <button @click="loadUserGroups(u.username)"
  171. class="text-indigo-600 hover:text-indigo-800 text-xs font-semibold hover:underline transition-colors"
  172. title="{{ _("Ver grupos del usuario") }}">
  173. <i class="fas fa-sitemap mr-1"></i>{{ _("Ver grupos") }}
  174. </button>
  175. </td>
  176. </tr>
  177. </template>
  178. </tbody>
  179. </table>
  180. <p x-show="userResults.length === 0 && userSearched" class="text-sm text-gray-500 text-center py-4">
  181. <i class="fas fa-inbox mr-2"></i>{{ _("No se encontraron usuarios.") }}
  182. </p>
  183. </div>
  184. </div>
  185. <!-- Search Groups -->
  186. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  187. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
  188. <i class="fas fa-layer-group text-indigo-500"></i> {{ _("Buscar Grupos en LDAP/AD") }}
  189. </h3>
  190. <div class="flex gap-2 mb-4">
  191. <input x-model="groupQuery" @keydown.enter="searchGroups()" type="text"
  192. placeholder="{{ _("Nombre del grupo…") }}"
  193. 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" />
  194. <button @click="searchGroups()" :disabled="searchingGroups"
  195. 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">
  196. <i class="fas fa-search" :class="searchingGroups ? 'animate-pulse' : ''"></i>
  197. {{ _("Buscar") }}
  198. </button>
  199. </div>
  200. <div class="overflow-x-auto">
  201. <table class="min-w-full text-sm" x-show="groupResults.length > 0">
  202. <thead class="bg-gray-50">
  203. <tr>
  204. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">{{ _("Nombre") }}</th>
  205. <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden sm:table-cell">{{ _("Descripción") }}</th>
  206. <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">{{ _("Miembros") }}</th>
  207. </tr>
  208. </thead>
  209. <tbody class="divide-y divide-gray-100">
  210. <template x-for="g in groupResults" :key="g.dn">
  211. <tr class="hover:bg-gray-50 transition-colors">
  212. <td class="px-3 py-2 font-medium text-gray-900" x-text="g.cn"></td>
  213. <td class="px-3 py-2 text-gray-600 hidden sm:table-cell" x-text="g.description || '—'"></td>
  214. <td class="px-3 py-2 text-center">
  215. <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>
  216. </td>
  217. </tr>
  218. </template>
  219. </tbody>
  220. </table>
  221. <p x-show="groupResults.length === 0 && groupSearched" class="text-sm text-gray-500 text-center py-4">
  222. <i class="fas fa-inbox mr-2"></i>{{ _("No se encontraron grupos.") }}
  223. </p>
  224. </div>
  225. </div>
  226. <!-- User Groups membership panel -->
  227. <div class="bg-white shadow rounded-lg border border-gray-200 p-6" x-show="membershipTarget">
  228. <div class="flex items-center justify-between mb-4">
  229. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
  230. <i class="fas fa-sitemap text-purple-500"></i>
  231. {{ _("Grupos de") }} <span class="text-purple-700 ml-1" x-text="membershipTarget"></span>
  232. </h3>
  233. <button @click="clearMembership()" class="text-gray-400 hover:text-gray-600 transition-colors text-xs">
  234. <i class="fas fa-times"></i> {{ _("Limpiar") }}
  235. </button>
  236. </div>
  237. <!-- Loading spinner -->
  238. <div x-show="loadingMembership" class="flex items-center justify-center py-8 text-gray-400">
  239. <i class="fas fa-circle-notch fa-spin text-2xl mr-3"></i> {{ _("Cargando grupos…") }}
  240. </div>
  241. <!-- Error -->
  242. <div x-show="!loadingMembership && membershipError"
  243. class="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg p-3 flex items-center gap-2">
  244. <i class="fas fa-exclamation-circle"></i>
  245. <span x-text="membershipError"></span>
  246. </div>
  247. <!-- Groups list -->
  248. <div x-show="!loadingMembership && !membershipError && membershipGroups.length > 0">
  249. <p class="text-xs text-gray-500 mb-3">
  250. <span x-text="membershipGroups.length"></span> {{ _("grupo(s) encontrado(s)") }}
  251. </p>
  252. <div class="flex flex-wrap gap-2">
  253. <template x-for="g in membershipGroups" :key="g.dn">
  254. <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">
  255. <i class="fas fa-layer-group text-purple-400"></i>
  256. <span x-text="g.cn"></span>
  257. </span>
  258. </template>
  259. </div>
  260. </div>
  261. <p x-show="!loadingMembership && !membershipError && membershipGroups.length === 0"
  262. class="text-sm text-gray-500 text-center py-4">
  263. <i class="fas fa-inbox mr-2"></i>{{ _("Este usuario no pertenece a ningún grupo.") }}
  264. </p>
  265. </div>
  266. </div>
  267. </div>
  268. </div>
  269. <div x-show="activeTab === 'groups'" class="space-y-6">
  270. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  271. <div class="flex items-center justify-between gap-3 mb-4">
  272. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
  273. <i class="fas fa-layer-group text-indigo-500"></i> {{ _("Grupos administrativos") }}
  274. </h3>
  275. <button @click="loadGroups()" :disabled="loadingGroups" class="text-sm text-indigo-600 hover:text-indigo-800 font-semibold disabled:opacity-50">
  276. <i class="fas fa-sync-alt" :class="loadingGroups ? 'animate-spin' : ''"></i> {{ _("Actualizar") }}
  277. </button>
  278. </div>
  279. <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-6">
  280. <div class="md:col-span-1">
  281. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Nombre del grupo") }}</label>
  282. <input x-model="groupForm.name" type="text" placeholder="{{ _('Ej. directivos') }}" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" />
  283. </div>
  284. <div class="md:col-span-1">
  285. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Descripción") }}</label>
  286. <input x-model="groupForm.description" type="text" placeholder="{{ _('Opcional') }}" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" />
  287. </div>
  288. <div class="md:col-span-1">
  289. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Origen") }}</label>
  290. <select x-model="groupForm.source" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
  291. <option value="custom">{{ _("Personalizado") }}</option>
  292. <!--<option value="ldap">{{ _("LDAP") }}</option>-->
  293. </select>
  294. </div>
  295. </div>
  296. <div class="flex justify-end">
  297. <button @click="createGroup()" :disabled="creatingGroup" 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">
  298. <i class="fas fa-plus"></i>
  299. <span x-text="creatingGroup ? '{{ _('Creando…') }}' : '{{ _('Crear grupo') }}'"></span>
  300. </button>
  301. </div>
  302. </div>
  303. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  304. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
  305. <i class="fas fa-users text-purple-500"></i> {{ _("Grupos creados") }}
  306. </h3>
  307. <div x-show="groupList.length === 0 && !loadingGroups" class="text-sm text-gray-500 text-center py-6">
  308. <i class="fas fa-inbox mr-2"></i>{{ _("Todavía no hay grupos definidos.") }}
  309. </div>
  310. <div x-show="loadingGroups" class="flex items-center justify-center py-8 text-gray-400">
  311. <i class="fas fa-circle-notch fa-spin text-2xl mr-3"></i> {{ _("Cargando grupos…") }}
  312. </div>
  313. <div class="space-y-4" x-show="groupList.length > 0 && !loadingGroups">
  314. <template x-for="group in groupList" :key="group.id">
  315. <div class="border border-gray-200 rounded-xl p-4 bg-gray-50">
  316. <div class="flex flex-col md:flex-row md:items-start md:justify-between gap-3">
  317. <div>
  318. <div class="flex items-center gap-2 flex-wrap">
  319. <h4 class="text-lg font-semibold text-gray-800" x-text="group.name"></h4>
  320. <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wide" :class="group.source === 'ldap' ? 'bg-blue-100 text-blue-700' : 'bg-indigo-100 text-indigo-700'" x-text="group.source === 'ldap' ? '{{ _('LDAP') }}' : '{{ _('Personalizado') }}'"></span>
  321. </div>
  322. <p class="text-sm text-gray-600 mt-1" x-text="group.description || '{{ _('Sin descripción') }}'"></p>
  323. </div>
  324. <button @click="deleteGroup(group.id, group.name)" class="text-red-600 hover:text-red-800 text-sm font-semibold transition-colors">
  325. <i class="fas fa-trash-alt mr-1"></i>{{ _("Eliminar") }}
  326. </button>
  327. </div>
  328. <div class="mt-4">
  329. <div class="flex flex-col sm:flex-row gap-2">
  330. <input x-model="memberInputs[group.id]" type="text" :placeholder="'{{ _('usuario1, usuario2, ...') }}'" 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" />
  331. <button @click="addMembers(group.id, group.name)" class="bg-indigo-600 hover:bg-indigo-700 text-white px-3 py-2 rounded-lg text-sm font-semibold transition-colors">
  332. <i class="fas fa-user-plus mr-1"></i>{{ _("Añadir usuarios") }}
  333. </button>
  334. </div>
  335. </div>
  336. <div class="mt-4" x-show="group.members && group.members.length > 0">
  337. <p class="text-xs text-gray-500 mb-2"><span x-text="group.member_count"></span> {{ _("usuario(s) asociado(s)") }}</p>
  338. <div class="flex flex-wrap gap-2">
  339. <template x-for="member in group.members" :key="member.id">
  340. <span class="inline-flex items-center gap-2 bg-white border border-gray-200 text-gray-700 text-xs font-medium px-3 py-1.5 rounded-full">
  341. <span x-text="member.username"></span>
  342. <button @click="removeMember(group.id, group.name, member.username)" class="text-red-500 hover:text-red-700" title="{{ _('Quitar usuario') }}">
  343. <i class="fas fa-times"></i>
  344. </button>
  345. </span>
  346. </template>
  347. </div>
  348. </div>
  349. <p x-show="group.members && group.members.length === 0" class="text-sm text-gray-500 mt-3">
  350. <i class="fas fa-inbox mr-2"></i>{{ _("Este grupo aún no tiene usuarios asociados.") }}
  351. </p>
  352. </div>
  353. </template>
  354. </div>
  355. </div>
  356. </div>
  357. </div>
  358. <script type="application/json" id="ldap-config-data">
  359. {{ cfg | tojson | safe }}
  360. </script>
  361. <script>
  362. function ldapApp() {
  363. const initialCfg = JSON.parse(document.getElementById('ldap-config-data').textContent || '{}');
  364. return {
  365. // Config form
  366. cfg: {
  367. host: initialCfg.host || "",
  368. port: initialCfg.port || 389,
  369. use_ssl: initialCfg.use_ssl || false,
  370. auth_type: initialCfg.auth_type || "SIMPLE",
  371. bind_dn: initialCfg.bind_dn || "",
  372. bind_password: initialCfg.bind_password || "",
  373. base_dn: initialCfg.base_dn || "",
  374. },
  375. savingCfg: false,
  376. testingConn: false,
  377. cfgAlert: { message: "", type: "" },
  378. // Connection status
  379. connectionStatus: "{{ _('Sin probar') }}",
  380. clientNotice: "",
  381. activeTab: "ldap",
  382. // Group management
  383. groupForm: { name: "", description: "", source: "custom" },
  384. groupList: [],
  385. loadingGroups: false,
  386. creatingGroup: false,
  387. memberInputs: {},
  388. // Stats
  389. stats: { users: null, groups: null },
  390. loadingStats: false,
  391. // User search
  392. userQuery: "",
  393. userResults: [],
  394. searchingUsers: false,
  395. userSearched: false,
  396. // Group search
  397. groupQuery: "",
  398. groupResults: [],
  399. searchingGroups: false,
  400. groupSearched: false,
  401. // Membership panel
  402. membershipTarget: "",
  403. membershipGroups: [],
  404. loadingMembership: false,
  405. membershipError: "",
  406. storageKey: "squidstats_ldap_config",
  407. // ── Helpers ────────────────────────────────────────────────────
  408. csrfToken() {
  409. return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
  410. },
  411. init() {
  412. if (this.cfg.host || this.cfg.base_dn || this.cfg.bind_dn) {
  413. this.clientNotice = '{{ _('Configuración cargada desde la base de datos.') }}';
  414. }
  415. this.$watch('cfg', () => { this.saveLocalConfig(); }, { deep: true });
  416. this.loadGroups();
  417. },
  418. loadLocalConfig() {
  419. try {
  420. const raw = localStorage.getItem(this.storageKey);
  421. if (!raw) return;
  422. const data = JSON.parse(raw);
  423. if (data && typeof data === 'object') {
  424. const { bind_password, ...safeData } = data;
  425. this.cfg = {
  426. ...this.cfg,
  427. ...safeData,
  428. use_ssl: safeData.use_ssl === true || safeData.use_ssl === 'true',
  429. };
  430. this.clientNotice = '{{ _('Configuración cargada desde el navegador. Los cambios se guardan localmente.') }}';
  431. }
  432. } catch (error) {
  433. console.warn('[LDAP DEBUG] loadLocalConfig error', error);
  434. }
  435. },
  436. saveLocalConfig() {
  437. try {
  438. const { bind_password, ...safeCfg } = this.cfg;
  439. localStorage.setItem(this.storageKey, JSON.stringify(safeCfg));
  440. this.clientNotice = '{{ _('Configuración guardada localmente en el navegador.') }}';
  441. } catch (error) {
  442. console.warn('[LDAP DEBUG] saveLocalConfig error', error);
  443. }
  444. },
  445. clearLocalConfig() {
  446. try {
  447. localStorage.removeItem(this.storageKey);
  448. this.clientNotice = '{{ _('Configuración local eliminada.') }}';
  449. } catch (error) {
  450. console.warn('[LDAP DEBUG] clearLocalConfig error', error);
  451. }
  452. },
  453. statusBadgeClass() {
  454. const map = {
  455. "{{ _('Conectado') }}": "bg-green-100 text-green-800",
  456. "{{ _('Error') }}": "bg-red-100 text-red-800",
  457. "{{ _('Sin probar') }}": "bg-gray-100 text-gray-600",
  458. "{{ _('Probando…') }}": "bg-yellow-100 text-yellow-800",
  459. };
  460. return map[this.connectionStatus] || "bg-gray-100 text-gray-600";
  461. },
  462. statusDotClass() {
  463. const map = {
  464. "{{ _('Conectado') }}": "bg-green-500",
  465. "{{ _('Error') }}": "bg-red-500",
  466. "{{ _('Sin probar') }}": "bg-gray-400",
  467. "{{ _('Probando…') }}": "bg-yellow-400",
  468. };
  469. return map[this.connectionStatus] || "bg-gray-400";
  470. },
  471. showAlert(message, type = "success") {
  472. this.cfgAlert = { message, type };
  473. setTimeout(() => { this.cfgAlert = { message: "", type: "" }; }, 4000);
  474. },
  475. // ── Actions ────────────────────────────────────────────────────
  476. async saveConfig() {
  477. this.savingCfg = true;
  478. try {
  479. const res = await fetch('/admin/api/ldap/save-config', {
  480. method: 'POST',
  481. headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
  482. body: JSON.stringify(this.cfg),
  483. });
  484. const data = await res.json();
  485. this.showAlert(data.message, data.status === 'success' ? 'success' : 'error');
  486. } catch {
  487. this.showAlert('{{ _('Error al guardar la configuración.') }}', 'error');
  488. } finally {
  489. this.savingCfg = false;
  490. }
  491. },
  492. async loadGroups() {
  493. this.loadingGroups = true;
  494. try {
  495. const res = await fetch('/admin/api/ldap/groups', {
  496. method: 'GET',
  497. headers: { 'X-CSRFToken': this.csrfToken() },
  498. });
  499. const data = await res.json();
  500. if (data.status === 'success') {
  501. this.groupList = data.groups || [];
  502. } else {
  503. this.showAlert(data.message || '{{ _('No se pudieron cargar los grupos.') }}', 'error');
  504. }
  505. } catch (error) {
  506. console.error('[LDAP DEBUG] loadGroups error', error);
  507. this.showAlert('{{ _('Error al cargar los grupos.') }}', 'error');
  508. } finally {
  509. this.loadingGroups = false;
  510. }
  511. },
  512. async createGroup() {
  513. if (!this.groupForm.name.trim()) {
  514. this.showAlert('{{ _('El nombre del grupo es obligatorio.') }}', 'error');
  515. return;
  516. }
  517. this.creatingGroup = true;
  518. try {
  519. const res = await fetch('/admin/api/ldap/groups', {
  520. method: 'POST',
  521. headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
  522. body: JSON.stringify({ action: 'create', ...this.groupForm }),
  523. });
  524. const data = await res.json();
  525. if (data.status === 'success') {
  526. this.groupForm = { name: '', description: '', source: 'custom' };
  527. this.groupList = data.group ? [data.group] : this.groupList;
  528. this.loadGroups();
  529. this.showAlert(data.message, 'success');
  530. } else {
  531. this.showAlert(data.message, 'error');
  532. }
  533. } catch (error) {
  534. console.error('[LDAP DEBUG] createGroup error', error);
  535. this.showAlert('{{ _('Error al crear el grupo.') }}', 'error');
  536. } finally {
  537. this.creatingGroup = false;
  538. }
  539. },
  540. async addMembers(groupId, groupName) {
  541. const raw = this.memberInputs[groupId] || '';
  542. const usernames = raw.split(/[\n,;]+/).map(item => item.trim()).filter(Boolean);
  543. if (!usernames.length) {
  544. this.showAlert('{{ _('Indica al menos un usuario para añadir.') }}', 'error');
  545. return;
  546. }
  547. try {
  548. const res = await fetch('/admin/api/ldap/groups', {
  549. method: 'POST',
  550. headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
  551. body: JSON.stringify({ action: 'add-members', group_id: groupId, group_name: groupName, usernames }),
  552. });
  553. const data = await res.json();
  554. if (data.status === 'success') {
  555. this.groupList = data.groups || [];
  556. this.memberInputs[groupId] = '';
  557. this.showAlert(data.message, 'success');
  558. } else {
  559. this.showAlert(data.message, 'error');
  560. }
  561. } catch (error) {
  562. console.error('[LDAP DEBUG] addMembers error', error);
  563. this.showAlert('{{ _('Error al añadir usuarios al grupo.') }}', 'error');
  564. }
  565. },
  566. async removeMember(groupId, groupName, username) {
  567. try {
  568. const res = await fetch('/admin/api/ldap/groups', {
  569. method: 'POST',
  570. headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
  571. body: JSON.stringify({ action: 'remove-member', group_id: groupId, group_name: groupName, username }),
  572. });
  573. const data = await res.json();
  574. if (data.status === 'success') {
  575. this.groupList = data.groups || [];
  576. this.showAlert(data.message, 'success');
  577. } else {
  578. this.showAlert(data.message, 'error');
  579. }
  580. } catch (error) {
  581. console.error('[LDAP DEBUG] removeMember error', error);
  582. this.showAlert('{{ _('Error al quitar el usuario del grupo.') }}', 'error');
  583. }
  584. },
  585. async deleteGroup(groupId, groupName) {
  586. const removeGroup = async () => {
  587. try {
  588. const res = await fetch('/admin/api/ldap/groups', {
  589. method: 'POST',
  590. headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
  591. body: JSON.stringify({ action: 'delete', group_id: groupId, group_name: groupName }),
  592. });
  593. const data = await res.json();
  594. if (data.status === 'success') {
  595. this.groupList = data.groups || [];
  596. this.showAlert(data.message, 'success');
  597. } else {
  598. this.showAlert(data.message, 'error');
  599. }
  600. } catch (error) {
  601. console.error('[LDAP DEBUG] deleteGroup error', error);
  602. this.showAlert('{{ _('Error al eliminar el grupo.') }}', 'error');
  603. }
  604. };
  605. if (typeof showCustomConfirm === 'function') {
  606. showCustomConfirm(
  607. {{ _('¿Está seguro de que desea eliminar este grupo y todos sus usuarios asociados?')|tojson }},
  608. removeGroup,
  609. );
  610. } else {
  611. await removeGroup();
  612. }
  613. },
  614. async testConnection() {
  615. this.testingConn = true;
  616. this.connectionStatus = "{{ _('Probando…') }}";
  617. try {
  618. const res = await fetch('/admin/api/ldap/test', {
  619. method: 'POST',
  620. headers: {
  621. 'Content-Type': 'application/json',
  622. 'X-CSRFToken': this.csrfToken(),
  623. },
  624. body: JSON.stringify(this.cfg),
  625. });
  626. const data = await res.json();
  627. this.connectionStatus = data.status === 'success' ? "{{ _('Conectado') }}" : "{{ _('Error') }}";
  628. this.showAlert(data.message, data.status);
  629. if (data.status === 'success') this.loadStats();
  630. } catch (error) {
  631. console.error('[LDAP DEBUG] testConnection error', error);
  632. this.connectionStatus = "{{ _('Error') }}";
  633. this.showAlert('{{ _('Error al conectar.') }}', 'error');
  634. } finally {
  635. this.testingConn = false;
  636. }
  637. },
  638. async loadStats() {
  639. this.loadingStats = true;
  640. try {
  641. const res = await fetch('/admin/api/ldap/stats', {
  642. method: 'POST',
  643. headers: {
  644. 'Content-Type': 'application/json',
  645. 'X-CSRFToken': this.csrfToken(),
  646. },
  647. body: JSON.stringify(this.cfg),
  648. });
  649. const data = await res.json();
  650. if (data.status === 'success') {
  651. this.stats = { users: data.users, groups: data.groups };
  652. } else {
  653. this.showAlert(data.message, 'error');
  654. }
  655. } catch (error) {
  656. console.error('[LDAP DEBUG] loadStats error', error);
  657. } finally {
  658. this.loadingStats = false;
  659. }
  660. },
  661. async searchUsers() {
  662. if (!this.userQuery.trim()) {
  663. if (typeof showNotification === 'function') {
  664. showNotification('{{ _('El campo de búsqueda de usuario no puede estar vacío.') }}', 'error');
  665. }
  666. return;
  667. }
  668. this.searchingUsers = true;
  669. this.userSearched = false;
  670. this.userResults = [];
  671. try {
  672. const res = await fetch('/admin/api/ldap/search-users', {
  673. method: 'POST',
  674. headers: {
  675. 'Content-Type': 'application/json',
  676. 'X-CSRFToken': this.csrfToken(),
  677. },
  678. body: JSON.stringify({ q: this.userQuery, ...this.cfg }),
  679. });
  680. const data = await res.json();
  681. this.userResults = data.results || [];
  682. this.userSearched = true;
  683. } catch (error) {
  684. console.error('[LDAP DEBUG] searchUsers error', error);
  685. this.userSearched = true;
  686. } finally {
  687. this.searchingUsers = false;
  688. }
  689. },
  690. async searchGroups() {
  691. this.searchingGroups = true;
  692. this.groupSearched = false;
  693. this.groupResults = [];
  694. try {
  695. const res = await fetch('/admin/api/ldap/search-groups', {
  696. method: 'POST',
  697. headers: {
  698. 'Content-Type': 'application/json',
  699. 'X-CSRFToken': this.csrfToken(),
  700. },
  701. body: JSON.stringify({ q: this.groupQuery, ...this.cfg }),
  702. });
  703. const data = await res.json();
  704. this.groupResults = data.results || [];
  705. this.groupSearched = true;
  706. } catch (error) {
  707. console.error('[LDAP DEBUG] searchGroups error', error);
  708. this.groupSearched = true;
  709. } finally {
  710. this.searchingGroups = false;
  711. }
  712. },
  713. async loadUserGroups(username) {
  714. this.membershipTarget = username;
  715. this.membershipGroups = [];
  716. this.membershipError = "";
  717. this.loadingMembership = true;
  718. try {
  719. const res = await fetch('/admin/api/ldap/user-groups', {
  720. method: 'POST',
  721. headers: {
  722. 'Content-Type': 'application/json',
  723. 'X-CSRFToken': this.csrfToken(),
  724. },
  725. body: JSON.stringify({ username, ...this.cfg }),
  726. });
  727. const data = await res.json();
  728. if (data.status === 'success') {
  729. this.membershipGroups = data.groups;
  730. } else {
  731. this.membershipError = data.message;
  732. }
  733. } catch (error) {
  734. console.error('[LDAP DEBUG] loadUserGroups error', error);
  735. this.membershipError = 'Error al cargar los grupos del usuario.';
  736. } finally {
  737. this.loadingMembership = false;
  738. }
  739. },
  740. clearMembership() {
  741. this.membershipTarget = "";
  742. this.membershipGroups = [];
  743. this.membershipError = "";
  744. },
  745. };
  746. }
  747. </script>
  748. {% endblock %}