| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815 |
- {% extends 'admin/base.html' %}
- {% block title %}{{ _("LDAP/AD y Grupos | Admin Squid") }}{% endblock %}
- {% block content %}
- <div class="max-w-7xl mx-auto space-y-6" x-data="ldapApp()" x-init="init()">
- <div class="bg-white shadow rounded-lg border border-gray-200 p-2">
- <nav class="flex flex-wrap gap-2" aria-label="{{ _('LDAP tabs') }}">
- <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">
- {{ _("LDAP/AD") }}
- </button>
- <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">
- {{ _("Grupos") }}
- </button>
- </nav>
- </div>
- <div x-show="activeTab === 'ldap'" class="space-y-6">
- <!-- ── Header ────────────────────────────────────────────────────── -->
- <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
- <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
- <div>
- <h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
- <i class="fas fa-network-wired text-blue-600"></i>
- {{ _("LDAP/AD") }}
- </h2>
- <p class="text-sm text-gray-500 mt-1">{{ _("Configura la conexión y explora el directorio.") }}</p>
- </div>
- <!-- Connection status badge -->
- <div>
- <span :class="statusBadgeClass()" class="inline-flex items-center gap-2 px-4 py-2 rounded-full text-sm font-semibold">
- <span class="w-2 h-2 rounded-full" :class="statusDotClass()"></span>
- <span x-text="connectionStatus"></span>
- </span>
- </div>
- </div>
- </div>
- <!-- ── Stats Cards ───────────────────────────────────────────────── -->
- <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
- <div class="bg-white rounded-lg shadow border border-gray-200 p-6 flex items-center gap-4">
- <div class="w-14 h-14 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
- <i class="fas fa-users text-blue-600 text-2xl"></i>
- </div>
- <div>
- <p class="text-sm text-gray-500">{{ _("Total Usuarios") }}</p>
- <p class="text-3xl font-bold text-gray-800" x-text="stats.users ?? '—'"></p>
- </div>
- <button @click="loadStats()" :disabled="loadingStats" title="{{ _("Actualizar") }}" class="ml-auto text-gray-400 hover:text-blue-600 transition-colors disabled:opacity-40">
- <i class="fas fa-sync-alt" :class="loadingStats ? 'animate-spin' : ''"></i>
- </button>
- </div>
- <div class="bg-white rounded-lg shadow border border-gray-200 p-6 flex items-center gap-4">
- <div class="w-14 h-14 rounded-full bg-indigo-100 flex items-center justify-center flex-shrink-0">
- <i class="fas fa-layer-group text-indigo-600 text-2xl"></i>
- </div>
- <div>
- <p class="text-sm text-gray-500">{{ _("Total Grupos") }}</p>
- <p class="text-3xl font-bold text-gray-800" x-text="stats.groups ?? '—'"></p>
- </div>
- <button @click="loadStats()" :disabled="loadingStats" title="{{ _("Actualizar") }}" class="ml-auto text-gray-400 hover:text-indigo-600 transition-colors disabled:opacity-40">
- <i class="fas fa-sync-alt" :class="loadingStats ? 'animate-spin' : ''"></i>
- </button>
- </div>
- </div>
- <!-- ── Main grid ─────────────────────────────────────────────────── -->
- <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
- <!-- LEFT – Configuration form -->
- <div class="xl:col-span-1 bg-white shadow rounded-lg border border-gray-200 p-6 space-y-4">
- <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
- <i class="fas fa-cog text-gray-500"></i> {{ _("Configuración de conexión") }}
- </h3>
- <div>
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Servidor (host)") }}</label>
- <input x-model="cfg.host" type="text" placeholder="ldap.empresa.com"
- 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" />
- </div>
- <div class="grid grid-cols-2 gap-3">
- <div>
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Puerto") }}</label>
- <input x-model.number="cfg.port" type="number" placeholder="389"
- 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" />
- </div>
- <div>
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Autenticación") }}</label>
- <select x-model="cfg.auth_type"
- 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">
- <option value="SIMPLE">{{ _("SIMPLE (LDAP)") }}</option>
- <option value="NTLM">{{ _("NTLM (AD)") }}</option>
- </select>
- </div>
- </div>
- <div class="flex items-center gap-2">
- <input x-model="cfg.use_ssl" type="checkbox" id="use_ssl" class="rounded text-blue-600" />
- <label for="use_ssl" class="text-sm text-gray-700">{{ _("Usar SSL / LDAPS") }}</label>
- </div>
- <div>
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Bind DN / Usuario") }}</label>
- <input x-model="cfg.bind_dn" type="text" placeholder="{{ _("CN=admin,DC=empresa,DC=com") }}"
- 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" />
- </div>
- <div>
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Contraseña Bind") }}</label>
- <input x-model="cfg.bind_password" type="password" autocomplete="current-password" placeholder="••••••••"
- 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" />
- </div>
- <div>
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Base DN") }}</label>
- <input x-model="cfg.base_dn" type="text" placeholder="{{ _("DC=empresa,DC=com") }}"
- 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" />
- </div>
- <!-- Action buttons -->
- <div class="flex gap-2 pt-2">
- <button @click="saveConfig()" :disabled="savingCfg"
- 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">
- <i class="fas fa-save"></i>
- <span x-text="savingCfg ? '{{ _('Guardando…') }}' : '{{ _('Guardar') }}'"></span>
- </button>
- <button @click="testConnection()" :disabled="testingConn"
- 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">
- <i class="fas fa-plug"></i>
- <span x-text="testingConn ? '{{ _('Probando…') }}' : '{{ _('Probar') }}'"></span>
- </button>
- </div>
- <div x-show="clientNotice" class="text-xs text-gray-500 italic mt-2">
- <span x-text="clientNotice"></span>
- </div>
- <!-- Inline alert -->
- <template x-if="cfgAlert.message">
- <div :class="cfgAlert.type === 'success' ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'"
- class="rounded-lg border p-3 text-sm flex items-start gap-2">
- <i :class="cfgAlert.type === 'success' ? 'fas fa-check-circle text-green-600' : 'fas fa-exclamation-circle text-red-600'" class="mt-0.5"></i>
- <span x-text="cfgAlert.message"></span>
- </div>
- </template>
- </div>
- <!-- RIGHT – Search & membership panels -->
- <div class="xl:col-span-2 space-y-6">
- <!-- Search Users -->
- <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
- <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
- <i class="fas fa-user-search text-blue-500"></i> {{ _("Buscar Usuarios") }}
- </h3>
- <div class="flex gap-2 mb-4">
- <input x-model="userQuery" @keydown.enter="searchUsers()" type="text"
- placeholder="{{ _("Nombre, usuario, email…") }}"
- 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" />
- <button @click="searchUsers()" :disabled="searchingUsers"
- 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">
- <i class="fas fa-search" :class="searchingUsers ? 'animate-pulse' : ''"></i>
- {{ _("Buscar") }}
- </button>
- </div>
- <!-- Results table -->
- <div class="overflow-x-auto">
- <table class="min-w-full text-sm" x-show="userResults.length > 0">
- <thead class="bg-gray-50">
- <tr>
- <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">{{ _("Nombre") }}</th>
- <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden sm:table-cell">{{ _("Usuario") }}</th>
- <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden md:table-cell">Email</th>
- <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden lg:table-cell">{{ _("Departamento") }}</th>
- <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">{{ _("Grupos") }}</th>
- </tr>
- </thead>
- <tbody class="divide-y divide-gray-100">
- <template x-for="u in userResults" :key="u.dn">
- <tr class="hover:bg-gray-50 transition-colors">
- <td class="px-3 py-2 font-medium text-gray-900" x-text="u.display_name || u.cn"></td>
- <td class="px-3 py-2 text-gray-600 hidden sm:table-cell" x-text="u.username"></td>
- <td class="px-3 py-2 text-gray-600 hidden md:table-cell" x-text="u.email"></td>
- <td class="px-3 py-2 text-gray-600 hidden lg:table-cell" x-text="u.department"></td>
- <td class="px-3 py-2 text-center">
- <button @click="loadUserGroups(u.username)"
- class="text-indigo-600 hover:text-indigo-800 text-xs font-semibold hover:underline transition-colors"
- title="{{ _("Ver grupos del usuario") }}">
- <i class="fas fa-sitemap mr-1"></i>{{ _("Ver grupos") }}
- </button>
- </td>
- </tr>
- </template>
- </tbody>
- </table>
- <p x-show="userResults.length === 0 && userSearched" class="text-sm text-gray-500 text-center py-4">
- <i class="fas fa-inbox mr-2"></i>{{ _("No se encontraron usuarios.") }}
- </p>
- </div>
- </div>
- <!-- Search Groups -->
- <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
- <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
- <i class="fas fa-layer-group text-indigo-500"></i> {{ _("Buscar Grupos en LDAP/AD") }}
- </h3>
- <div class="flex gap-2 mb-4">
- <input x-model="groupQuery" @keydown.enter="searchGroups()" type="text"
- placeholder="{{ _("Nombre del grupo…") }}"
- 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" />
- <button @click="searchGroups()" :disabled="searchingGroups"
- 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">
- <i class="fas fa-search" :class="searchingGroups ? 'animate-pulse' : ''"></i>
- {{ _("Buscar") }}
- </button>
- </div>
- <div class="overflow-x-auto">
- <table class="min-w-full text-sm" x-show="groupResults.length > 0">
- <thead class="bg-gray-50">
- <tr>
- <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">{{ _("Nombre") }}</th>
- <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase hidden sm:table-cell">{{ _("Descripción") }}</th>
- <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">{{ _("Miembros") }}</th>
- </tr>
- </thead>
- <tbody class="divide-y divide-gray-100">
- <template x-for="g in groupResults" :key="g.dn">
- <tr class="hover:bg-gray-50 transition-colors">
- <td class="px-3 py-2 font-medium text-gray-900" x-text="g.cn"></td>
- <td class="px-3 py-2 text-gray-600 hidden sm:table-cell" x-text="g.description || '—'"></td>
- <td class="px-3 py-2 text-center">
- <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>
- </td>
- </tr>
- </template>
- </tbody>
- </table>
- <p x-show="groupResults.length === 0 && groupSearched" class="text-sm text-gray-500 text-center py-4">
- <i class="fas fa-inbox mr-2"></i>{{ _("No se encontraron grupos.") }}
- </p>
- </div>
- </div>
- <!-- User Groups membership panel -->
- <div class="bg-white shadow rounded-lg border border-gray-200 p-6" x-show="membershipTarget">
- <div class="flex items-center justify-between mb-4">
- <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
- <i class="fas fa-sitemap text-purple-500"></i>
- {{ _("Grupos de") }} <span class="text-purple-700 ml-1" x-text="membershipTarget"></span>
- </h3>
- <button @click="clearMembership()" class="text-gray-400 hover:text-gray-600 transition-colors text-xs">
- <i class="fas fa-times"></i> {{ _("Limpiar") }}
- </button>
- </div>
- <!-- Loading spinner -->
- <div x-show="loadingMembership" class="flex items-center justify-center py-8 text-gray-400">
- <i class="fas fa-circle-notch fa-spin text-2xl mr-3"></i> {{ _("Cargando grupos…") }}
- </div>
- <!-- Error -->
- <div x-show="!loadingMembership && membershipError"
- class="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg p-3 flex items-center gap-2">
- <i class="fas fa-exclamation-circle"></i>
- <span x-text="membershipError"></span>
- </div>
- <!-- Groups list -->
- <div x-show="!loadingMembership && !membershipError && membershipGroups.length > 0">
- <p class="text-xs text-gray-500 mb-3">
- <span x-text="membershipGroups.length"></span> {{ _("grupo(s) encontrado(s)") }}
- </p>
- <div class="flex flex-wrap gap-2">
- <template x-for="g in membershipGroups" :key="g.dn">
- <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">
- <i class="fas fa-layer-group text-purple-400"></i>
- <span x-text="g.cn"></span>
- </span>
- </template>
- </div>
- </div>
- <p x-show="!loadingMembership && !membershipError && membershipGroups.length === 0"
- class="text-sm text-gray-500 text-center py-4">
- <i class="fas fa-inbox mr-2"></i>{{ _("Este usuario no pertenece a ningún grupo.") }}
- </p>
- </div>
- </div>
- </div>
- </div>
- <div x-show="activeTab === 'groups'" class="space-y-6">
- <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
- <div class="flex items-center justify-between gap-3 mb-4">
- <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
- <i class="fas fa-layer-group text-indigo-500"></i> {{ _("Grupos administrativos") }}
- </h3>
- <button @click="loadGroups()" :disabled="loadingGroups" class="text-sm text-indigo-600 hover:text-indigo-800 font-semibold disabled:opacity-50">
- <i class="fas fa-sync-alt" :class="loadingGroups ? 'animate-spin' : ''"></i> {{ _("Actualizar") }}
- </button>
- </div>
- <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-6">
- <div class="md:col-span-1">
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Nombre del grupo") }}</label>
- <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" />
- </div>
- <div class="md:col-span-1">
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Descripción") }}</label>
- <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" />
- </div>
- <div class="md:col-span-1">
- <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Origen") }}</label>
- <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">
- <option value="custom">{{ _("Personalizado") }}</option>
- <!--<option value="ldap">{{ _("LDAP") }}</option>-->
- </select>
- </div>
- </div>
- <div class="flex justify-end">
- <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">
- <i class="fas fa-plus"></i>
- <span x-text="creatingGroup ? '{{ _('Creando…') }}' : '{{ _('Crear grupo') }}'"></span>
- </button>
- </div>
- </div>
- <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
- <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
- <i class="fas fa-users text-purple-500"></i> {{ _("Grupos creados") }}
- </h3>
- <div x-show="groupList.length === 0 && !loadingGroups" class="text-sm text-gray-500 text-center py-6">
- <i class="fas fa-inbox mr-2"></i>{{ _("Todavía no hay grupos definidos.") }}
- </div>
- <div x-show="loadingGroups" class="flex items-center justify-center py-8 text-gray-400">
- <i class="fas fa-circle-notch fa-spin text-2xl mr-3"></i> {{ _("Cargando grupos…") }}
- </div>
- <div class="space-y-4" x-show="groupList.length > 0 && !loadingGroups">
- <template x-for="group in groupList" :key="group.id">
- <div class="border border-gray-200 rounded-xl p-4 bg-gray-50">
- <div class="flex flex-col md:flex-row md:items-start md:justify-between gap-3">
- <div>
- <div class="flex items-center gap-2 flex-wrap">
- <h4 class="text-lg font-semibold text-gray-800" x-text="group.name"></h4>
- <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>
- </div>
- <p class="text-sm text-gray-600 mt-1" x-text="group.description || '{{ _('Sin descripción') }}'"></p>
- </div>
- <button @click="deleteGroup(group.id, group.name)" class="text-red-600 hover:text-red-800 text-sm font-semibold transition-colors">
- <i class="fas fa-trash-alt mr-1"></i>{{ _("Eliminar") }}
- </button>
- </div>
- <div class="mt-4">
- <div class="flex flex-col sm:flex-row gap-2">
- <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" />
- <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">
- <i class="fas fa-user-plus mr-1"></i>{{ _("Añadir usuarios") }}
- </button>
- </div>
- </div>
- <div class="mt-4" x-show="group.members && group.members.length > 0">
- <p class="text-xs text-gray-500 mb-2"><span x-text="group.member_count"></span> {{ _("usuario(s) asociado(s)") }}</p>
- <div class="flex flex-wrap gap-2">
- <template x-for="member in group.members" :key="member.id">
- <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">
- <span x-text="member.username"></span>
- <button @click="removeMember(group.id, group.name, member.username)" class="text-red-500 hover:text-red-700" title="{{ _('Quitar usuario') }}">
- <i class="fas fa-times"></i>
- </button>
- </span>
- </template>
- </div>
- </div>
- <p x-show="group.members && group.members.length === 0" class="text-sm text-gray-500 mt-3">
- <i class="fas fa-inbox mr-2"></i>{{ _("Este grupo aún no tiene usuarios asociados.") }}
- </p>
- </div>
- </template>
- </div>
- </div>
- </div>
- </div>
- <script type="application/json" id="ldap-config-data">
- {{ cfg | tojson | safe }}
- </script>
- <script>
- function ldapApp() {
- const initialCfg = JSON.parse(document.getElementById('ldap-config-data').textContent || '{}');
- return {
- // Config form
- cfg: {
- host: initialCfg.host || "",
- port: initialCfg.port || 389,
- use_ssl: initialCfg.use_ssl || false,
- auth_type: initialCfg.auth_type || "SIMPLE",
- bind_dn: initialCfg.bind_dn || "",
- bind_password: initialCfg.bind_password || "",
- base_dn: initialCfg.base_dn || "",
- },
- savingCfg: false,
- testingConn: false,
- cfgAlert: { message: "", type: "" },
- // Connection status
- connectionStatus: "{{ _('Sin probar') }}",
- clientNotice: "",
- activeTab: "ldap",
- // Group management
- groupForm: { name: "", description: "", source: "custom" },
- groupList: [],
- loadingGroups: false,
- creatingGroup: false,
- memberInputs: {},
- // Stats
- stats: { users: null, groups: null },
- loadingStats: false,
- // User search
- userQuery: "",
- userResults: [],
- searchingUsers: false,
- userSearched: false,
- // Group search
- groupQuery: "",
- groupResults: [],
- searchingGroups: false,
- groupSearched: false,
- // Membership panel
- membershipTarget: "",
- membershipGroups: [],
- loadingMembership: false,
- membershipError: "",
- storageKey: "squidstats_ldap_config",
- // ── Helpers ────────────────────────────────────────────────────
- csrfToken() {
- return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
- },
- init() {
- if (this.cfg.host || this.cfg.base_dn || this.cfg.bind_dn) {
- this.clientNotice = '{{ _('Configuración cargada desde la base de datos.') }}';
- }
- this.$watch('cfg', () => { this.saveLocalConfig(); }, { deep: true });
- this.loadGroups();
- },
- loadLocalConfig() {
- try {
- const raw = localStorage.getItem(this.storageKey);
- if (!raw) return;
- const data = JSON.parse(raw);
- if (data && typeof data === 'object') {
- const { bind_password, ...safeData } = data;
- this.cfg = {
- ...this.cfg,
- ...safeData,
- use_ssl: safeData.use_ssl === true || safeData.use_ssl === 'true',
- };
- this.clientNotice = '{{ _('Configuración cargada desde el navegador. Los cambios se guardan localmente.') }}';
- }
- } catch (error) {
- console.warn('[LDAP DEBUG] loadLocalConfig error', error);
- }
- },
- saveLocalConfig() {
- try {
- const { bind_password, ...safeCfg } = this.cfg;
- localStorage.setItem(this.storageKey, JSON.stringify(safeCfg));
- this.clientNotice = '{{ _('Configuración guardada localmente en el navegador.') }}';
- } catch (error) {
- console.warn('[LDAP DEBUG] saveLocalConfig error', error);
- }
- },
- clearLocalConfig() {
- try {
- localStorage.removeItem(this.storageKey);
- this.clientNotice = '{{ _('Configuración local eliminada.') }}';
- } catch (error) {
- console.warn('[LDAP DEBUG] clearLocalConfig error', error);
- }
- },
- statusBadgeClass() {
- const map = {
- "{{ _('Conectado') }}": "bg-green-100 text-green-800",
- "{{ _('Error') }}": "bg-red-100 text-red-800",
- "{{ _('Sin probar') }}": "bg-gray-100 text-gray-600",
- "{{ _('Probando…') }}": "bg-yellow-100 text-yellow-800",
- };
- return map[this.connectionStatus] || "bg-gray-100 text-gray-600";
- },
- statusDotClass() {
- const map = {
- "{{ _('Conectado') }}": "bg-green-500",
- "{{ _('Error') }}": "bg-red-500",
- "{{ _('Sin probar') }}": "bg-gray-400",
- "{{ _('Probando…') }}": "bg-yellow-400",
- };
- return map[this.connectionStatus] || "bg-gray-400";
- },
- showAlert(message, type = "success") {
- this.cfgAlert = { message, type };
- setTimeout(() => { this.cfgAlert = { message: "", type: "" }; }, 4000);
- },
- // ── Actions ────────────────────────────────────────────────────
- async saveConfig() {
- this.savingCfg = true;
- try {
- const res = await fetch('/admin/api/ldap/save-config', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
- body: JSON.stringify(this.cfg),
- });
- const data = await res.json();
- this.showAlert(data.message, data.status === 'success' ? 'success' : 'error');
- } catch {
- this.showAlert('{{ _('Error al guardar la configuración.') }}', 'error');
- } finally {
- this.savingCfg = false;
- }
- },
- async loadGroups() {
- this.loadingGroups = true;
- try {
- const res = await fetch('/admin/api/ldap/groups', {
- method: 'GET',
- headers: { 'X-CSRFToken': this.csrfToken() },
- });
- const data = await res.json();
- if (data.status === 'success') {
- this.groupList = data.groups || [];
- } else {
- this.showAlert(data.message || '{{ _('No se pudieron cargar los grupos.') }}', 'error');
- }
- } catch (error) {
- console.error('[LDAP DEBUG] loadGroups error', error);
- this.showAlert('{{ _('Error al cargar los grupos.') }}', 'error');
- } finally {
- this.loadingGroups = false;
- }
- },
- async createGroup() {
- if (!this.groupForm.name.trim()) {
- this.showAlert('{{ _('El nombre del grupo es obligatorio.') }}', 'error');
- return;
- }
- this.creatingGroup = true;
- try {
- const res = await fetch('/admin/api/ldap/groups', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
- body: JSON.stringify({ action: 'create', ...this.groupForm }),
- });
- const data = await res.json();
- if (data.status === 'success') {
- this.groupForm = { name: '', description: '', source: 'custom' };
- this.groupList = data.group ? [data.group] : this.groupList;
- this.loadGroups();
- this.showAlert(data.message, 'success');
- } else {
- this.showAlert(data.message, 'error');
- }
- } catch (error) {
- console.error('[LDAP DEBUG] createGroup error', error);
- this.showAlert('{{ _('Error al crear el grupo.') }}', 'error');
- } finally {
- this.creatingGroup = false;
- }
- },
- async addMembers(groupId, groupName) {
- const raw = this.memberInputs[groupId] || '';
- const usernames = raw.split(/[\n,;]+/).map(item => item.trim()).filter(Boolean);
- if (!usernames.length) {
- this.showAlert('{{ _('Indica al menos un usuario para añadir.') }}', 'error');
- return;
- }
- try {
- const res = await fetch('/admin/api/ldap/groups', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
- body: JSON.stringify({ action: 'add-members', group_id: groupId, group_name: groupName, usernames }),
- });
- const data = await res.json();
- if (data.status === 'success') {
- this.groupList = data.groups || [];
- this.memberInputs[groupId] = '';
- this.showAlert(data.message, 'success');
- } else {
- this.showAlert(data.message, 'error');
- }
- } catch (error) {
- console.error('[LDAP DEBUG] addMembers error', error);
- this.showAlert('{{ _('Error al añadir usuarios al grupo.') }}', 'error');
- }
- },
- async removeMember(groupId, groupName, username) {
- try {
- const res = await fetch('/admin/api/ldap/groups', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
- body: JSON.stringify({ action: 'remove-member', group_id: groupId, group_name: groupName, username }),
- });
- const data = await res.json();
- if (data.status === 'success') {
- this.groupList = data.groups || [];
- this.showAlert(data.message, 'success');
- } else {
- this.showAlert(data.message, 'error');
- }
- } catch (error) {
- console.error('[LDAP DEBUG] removeMember error', error);
- this.showAlert('{{ _('Error al quitar el usuario del grupo.') }}', 'error');
- }
- },
- async deleteGroup(groupId, groupName) {
- const removeGroup = async () => {
- try {
- const res = await fetch('/admin/api/ldap/groups', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
- body: JSON.stringify({ action: 'delete', group_id: groupId, group_name: groupName }),
- });
- const data = await res.json();
- if (data.status === 'success') {
- this.groupList = data.groups || [];
- this.showAlert(data.message, 'success');
- } else {
- this.showAlert(data.message, 'error');
- }
- } catch (error) {
- console.error('[LDAP DEBUG] deleteGroup error', error);
- this.showAlert('{{ _('Error al eliminar el grupo.') }}', 'error');
- }
- };
- if (typeof showCustomConfirm === 'function') {
- showCustomConfirm(
- {{ _('¿Está seguro de que desea eliminar este grupo y todos sus usuarios asociados?')|tojson }},
- removeGroup,
- );
- } else {
- await removeGroup();
- }
- },
- async testConnection() {
- this.testingConn = true;
- this.connectionStatus = "{{ _('Probando…') }}";
- try {
- const res = await fetch('/admin/api/ldap/test', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': this.csrfToken(),
- },
- body: JSON.stringify(this.cfg),
- });
- const data = await res.json();
- this.connectionStatus = data.status === 'success' ? "{{ _('Conectado') }}" : "{{ _('Error') }}";
- this.showAlert(data.message, data.status);
- if (data.status === 'success') this.loadStats();
- } catch (error) {
- console.error('[LDAP DEBUG] testConnection error', error);
- this.connectionStatus = "{{ _('Error') }}";
- this.showAlert('{{ _('Error al conectar.') }}', 'error');
- } finally {
- this.testingConn = false;
- }
- },
- async loadStats() {
- this.loadingStats = true;
- try {
- const res = await fetch('/admin/api/ldap/stats', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': this.csrfToken(),
- },
- body: JSON.stringify(this.cfg),
- });
- const data = await res.json();
- if (data.status === 'success') {
- this.stats = { users: data.users, groups: data.groups };
- } else {
- this.showAlert(data.message, 'error');
- }
- } catch (error) {
- console.error('[LDAP DEBUG] loadStats error', error);
- } finally {
- this.loadingStats = false;
- }
- },
- async searchUsers() {
- if (!this.userQuery.trim()) {
- if (typeof showNotification === 'function') {
- showNotification('{{ _('El campo de búsqueda de usuario no puede estar vacío.') }}', 'error');
- }
- return;
- }
- this.searchingUsers = true;
- this.userSearched = false;
- this.userResults = [];
- try {
- const res = await fetch('/admin/api/ldap/search-users', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': this.csrfToken(),
- },
- body: JSON.stringify({ q: this.userQuery, ...this.cfg }),
- });
- const data = await res.json();
- this.userResults = data.results || [];
- this.userSearched = true;
- } catch (error) {
- console.error('[LDAP DEBUG] searchUsers error', error);
- this.userSearched = true;
- } finally {
- this.searchingUsers = false;
- }
- },
- async searchGroups() {
- this.searchingGroups = true;
- this.groupSearched = false;
- this.groupResults = [];
- try {
- const res = await fetch('/admin/api/ldap/search-groups', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': this.csrfToken(),
- },
- body: JSON.stringify({ q: this.groupQuery, ...this.cfg }),
- });
- const data = await res.json();
- this.groupResults = data.results || [];
- this.groupSearched = true;
- } catch (error) {
- console.error('[LDAP DEBUG] searchGroups error', error);
- this.groupSearched = true;
- } finally {
- this.searchingGroups = false;
- }
- },
- async loadUserGroups(username) {
- this.membershipTarget = username;
- this.membershipGroups = [];
- this.membershipError = "";
- this.loadingMembership = true;
- try {
- const res = await fetch('/admin/api/ldap/user-groups', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': this.csrfToken(),
- },
- body: JSON.stringify({ username, ...this.cfg }),
- });
- const data = await res.json();
- if (data.status === 'success') {
- this.membershipGroups = data.groups;
- } else {
- this.membershipError = data.message;
- }
- } catch (error) {
- console.error('[LDAP DEBUG] loadUserGroups error', error);
- this.membershipError = 'Error al cargar los grupos del usuario.';
- } finally {
- this.loadingMembership = false;
- }
- },
- clearMembership() {
- this.membershipTarget = "";
- this.membershipGroups = [];
- this.membershipError = "";
- },
- };
- }
- </script>
- {% endblock %}
|