feat(hostinger): VPS actions, DNS editing, domain lock/privacy, nameservers, auto-renewal
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -54,6 +55,37 @@ func (c *HostingerClient) getRaw(ctx context.Context, path string) ([]byte, erro
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// writeRaw envía una petición HTTP autenticada con método y body opcionales.
|
||||
func (c *HostingerClient) writeRaw(ctx context.Context, method, path string, payload interface{}) ([]byte, error) {
|
||||
var reqBody io.Reader
|
||||
if payload != nil {
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hostinger: serializar body: %w", err)
|
||||
}
|
||||
reqBody = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, hostingerBaseURL+path, reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hostinger: crear request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hostinger: ejecutar request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hostinger: leer body: %w", err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("hostinger: status %d – %s", resp.StatusCode, string(body))
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// get realiza una petición GET autenticada y decodifica el cuerpo en dest.
|
||||
func (c *HostingerClient) get(path string, dest interface{}) error {
|
||||
body, err := c.getRaw(context.Background(), path)
|
||||
@@ -115,6 +147,19 @@ type HostingerNameServers struct {
|
||||
NS4 string `json:"ns4"`
|
||||
}
|
||||
|
||||
// HostingerDNSZoneInput es un grupo de registros para PUT /dns/v1/zones/{domain}.
|
||||
type HostingerDNSZoneInput struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
TTL int `json:"ttl,omitempty"`
|
||||
Records []HostingerDNSZoneValue `json:"records"`
|
||||
}
|
||||
|
||||
// HostingerDNSZoneValue es el valor de contenido de un registro DNS.
|
||||
type HostingerDNSZoneValue struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// HostingerSubscription representa una suscripción de facturación.
|
||||
type HostingerSubscription struct {
|
||||
ID string `json:"id"`
|
||||
@@ -263,6 +308,122 @@ func (c *HostingerClient) GetOrders() ([]HostingerSubscription, error) {
|
||||
return arr, nil
|
||||
}
|
||||
|
||||
// ─── DNS: escritura ─────────────────────────────────────────────────────────
|
||||
|
||||
// UpdateDNSZone agrega/actualiza registros en la zona DNS.
|
||||
// overwrite=true reemplaza registros del mismo tipo/nombre; false los agrega.
|
||||
func (c *HostingerClient) UpdateDNSZone(domain string, overwrite bool, zone []HostingerDNSZoneInput) error {
|
||||
path := fmt.Sprintf("/dns/v1/zones/%s", domain)
|
||||
_, err := c.writeRaw(context.Background(), http.MethodPut, path,
|
||||
map[string]interface{}{"overwrite": overwrite, "zone": zone})
|
||||
return err
|
||||
}
|
||||
|
||||
// ResetDNS restaura la zona DNS de un dominio a sus valores por defecto.
|
||||
func (c *HostingerClient) ResetDNS(domain string) error {
|
||||
path := fmt.Sprintf("/dns/v1/zones/%s/reset", domain)
|
||||
_, err := c.writeRaw(context.Background(), http.MethodPost, path, map[string]bool{"sync": true})
|
||||
return err
|
||||
}
|
||||
|
||||
// ─── Domains: escritura ──────────────────────────────────────────────────────
|
||||
|
||||
// UpdateNameservers actualiza los nameservers de un dominio.
|
||||
func (c *HostingerClient) UpdateNameservers(domain, ns1, ns2, ns3, ns4 string) error {
|
||||
path := fmt.Sprintf("/domains/v1/portfolio/%s/nameservers", domain)
|
||||
_, err := c.writeRaw(context.Background(), http.MethodPut, path,
|
||||
map[string]string{"ns1": ns1, "ns2": ns2, "ns3": ns3, "ns4": ns4})
|
||||
return err
|
||||
}
|
||||
|
||||
// SetDomainLock activa (PUT) o desactiva (DELETE) el bloqueo del dominio.
|
||||
func (c *HostingerClient) SetDomainLock(domain string, enable bool) error {
|
||||
path := fmt.Sprintf("/domains/v1/portfolio/%s/domain-lock", domain)
|
||||
method := http.MethodPut
|
||||
if !enable {
|
||||
method = http.MethodDelete
|
||||
}
|
||||
_, err := c.writeRaw(context.Background(), method, path, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetPrivacyProtection activa (PUT) o desactiva (DELETE) la protección WHOIS.
|
||||
func (c *HostingerClient) SetPrivacyProtection(domain string, enable bool) error {
|
||||
path := fmt.Sprintf("/domains/v1/portfolio/%s/privacy-protection", domain)
|
||||
method := http.MethodPut
|
||||
if !enable {
|
||||
method = http.MethodDelete
|
||||
}
|
||||
_, err := c.writeRaw(context.Background(), method, path, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// ─── VPS: acciones ───────────────────────────────────────────────────────────
|
||||
|
||||
// VPSAction ejecuta una acción en una VM: start | stop | restart.
|
||||
func (c *HostingerClient) VPSAction(vmID int, action string) error {
|
||||
path := fmt.Sprintf("/vps/v1/virtual-machines/%d/%s", vmID, action)
|
||||
_, err := c.writeRaw(context.Background(), http.MethodPost, path, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetVPSRootPassword cambia la contraseña root de una VM.
|
||||
func (c *HostingerClient) SetVPSRootPassword(vmID int, password string) error {
|
||||
path := fmt.Sprintf("/vps/v1/virtual-machines/%d/root-password", vmID)
|
||||
_, err := c.writeRaw(context.Background(), http.MethodPut, path, map[string]string{"password": password})
|
||||
return err
|
||||
}
|
||||
|
||||
// SetVPSHostname cambia el hostname de una VM.
|
||||
func (c *HostingerClient) SetVPSHostname(vmID int, hostname string) error {
|
||||
path := fmt.Sprintf("/vps/v1/virtual-machines/%d/hostname", vmID)
|
||||
_, err := c.writeRaw(context.Background(), http.MethodPut, path, map[string]string{"hostname": hostname})
|
||||
return err
|
||||
}
|
||||
|
||||
// GetVPSMetrics obtiene las métricas de uso de una VM.
|
||||
func (c *HostingerClient) GetVPSMetrics(vmID int) (json.RawMessage, error) {
|
||||
path := fmt.Sprintf("/vps/v1/virtual-machines/%d/metrics", vmID)
|
||||
body, err := c.getRaw(context.Background(), path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.RawMessage(body), nil
|
||||
}
|
||||
|
||||
// GetVPSBackups obtiene los backups de una VM.
|
||||
func (c *HostingerClient) GetVPSBackups(vmID int) (json.RawMessage, error) {
|
||||
path := fmt.Sprintf("/vps/v1/virtual-machines/%d/backups", vmID)
|
||||
body, err := c.getRaw(context.Background(), path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.RawMessage(body), nil
|
||||
}
|
||||
|
||||
// ─── Billing: acciones ───────────────────────────────────────────────────────
|
||||
|
||||
// ToggleAutoRenewal activa (true) o desactiva la autorenovación de una suscripción.
|
||||
func (c *HostingerClient) ToggleAutoRenewal(subscriptionID string, enable bool) (*HostingerSubscription, error) {
|
||||
var path, method string
|
||||
if enable {
|
||||
path = fmt.Sprintf("/billing/v1/subscriptions/%s/auto-renewal/enable", subscriptionID)
|
||||
method = http.MethodPatch
|
||||
} else {
|
||||
path = fmt.Sprintf("/billing/v1/subscriptions/%s/auto-renewal/disable", subscriptionID)
|
||||
method = http.MethodDelete
|
||||
}
|
||||
body, err := c.writeRaw(context.Background(), method, path, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var sub HostingerSubscription
|
||||
if err := json.Unmarshal(body, &sub); err != nil {
|
||||
return nil, fmt.Errorf("hostinger: no se pudo interpretar respuesta: %w", err)
|
||||
}
|
||||
return &sub, nil
|
||||
}
|
||||
|
||||
// GetHostingAccounts obtiene las cuentas de hosting.
|
||||
// Endpoint: GET /hosting/v1/websites
|
||||
func (c *HostingerClient) GetHostingAccounts() ([]HostingerHosting, error) {
|
||||
|
||||
@@ -78,6 +78,38 @@
|
||||
class="mt-3 w-full text-center text-xs py-1.5 rounded border border-[#8eb02f] text-[#6d8c24] hover:bg-green-50 transition">
|
||||
Ver DNS del hostname
|
||||
</button>
|
||||
<!-- Acciones de estado -->
|
||||
<div class="mt-2 flex gap-1.5">
|
||||
<button x-show="v.state !== 'running'"
|
||||
@click="vpsAction(v.id, 'start')"
|
||||
:disabled="vpsActionLoading[v.id]"
|
||||
class="flex-1 text-xs py-1.5 rounded bg-green-500 text-white hover:bg-green-600 disabled:opacity-40 transition">
|
||||
<span x-text="vpsActionLoading[v.id]==='start' ? '...' : '▶ Start'"></span>
|
||||
</button>
|
||||
<button x-show="v.state === 'running'"
|
||||
@click="vpsAction(v.id, 'stop')"
|
||||
:disabled="vpsActionLoading[v.id]"
|
||||
class="flex-1 text-xs py-1.5 rounded bg-red-500 text-white hover:bg-red-600 disabled:opacity-40 transition">
|
||||
<span x-text="vpsActionLoading[v.id]==='stop' ? '...' : '■ Stop'"></span>
|
||||
</button>
|
||||
<button x-show="v.state === 'running'"
|
||||
@click="vpsAction(v.id, 'restart')"
|
||||
:disabled="vpsActionLoading[v.id]"
|
||||
class="flex-1 text-xs py-1.5 rounded bg-yellow-500 text-white hover:bg-yellow-600 disabled:opacity-40 transition">
|
||||
<span x-text="vpsActionLoading[v.id]==='restart' ? '...' : '↺ Restart'"></span>
|
||||
</button>
|
||||
</div>
|
||||
<!-- Configuración avanzada -->
|
||||
<div class="mt-1.5 flex gap-1.5">
|
||||
<button @click="vpsPasswordForm={id:v.id,password:''}; vpsPasswordModal=true"
|
||||
class="flex-1 text-xs py-1.5 rounded border border-gray-300 text-gray-600 hover:bg-gray-50 transition">
|
||||
🔑 Password
|
||||
</button>
|
||||
<button @click="vpsHostnameForm={id:v.id,hostname:v.hostname}; vpsHostnameModal=true"
|
||||
class="flex-1 text-xs py-1.5 rounded border border-gray-300 text-gray-600 hover:bg-gray-50 transition">
|
||||
✏️ Hostname
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -109,10 +141,31 @@
|
||||
<td class="py-2 px-3 text-xs text-gray-500" x-text="d.registered_at || '—'"></td>
|
||||
<td class="py-2 px-3 text-xs text-gray-500" x-text="d.expires_at || '—'"></td>
|
||||
<td class="py-2 px-3">
|
||||
<button @click="loadDNSForDomain(d.domain)"
|
||||
class="text-xs px-2 py-1 rounded border border-[#8eb02f] text-[#6d8c24] hover:bg-green-50 transition">
|
||||
Ver DNS
|
||||
</button>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<button @click="loadDNSForDomain(d.domain)"
|
||||
class="text-xs px-2 py-1 rounded border border-[#8eb02f] text-[#6d8c24] hover:bg-green-50 transition">
|
||||
DNS
|
||||
</button>
|
||||
<button @click="nsForm={domain:d.domain,ns1:'',ns2:'',ns3:'',ns4:''}; nsModal=true"
|
||||
class="text-xs px-2 py-1 rounded border border-blue-400 text-blue-600 hover:bg-blue-50 transition">
|
||||
NS
|
||||
</button>
|
||||
<button @click="toggleDomainLock(d.domain, true)"
|
||||
class="text-xs px-2 py-1 rounded border border-gray-300 text-gray-500 hover:bg-gray-50 transition"
|
||||
title="Bloquear dominio">
|
||||
🔒
|
||||
</button>
|
||||
<button @click="toggleDomainLock(d.domain, false)"
|
||||
class="text-xs px-2 py-1 rounded border border-gray-300 text-gray-500 hover:bg-gray-50 transition"
|
||||
title="Desbloquear dominio">
|
||||
🔓
|
||||
</button>
|
||||
<button @click="togglePrivacy(d.domain, true)"
|
||||
class="text-xs px-2 py-1 rounded border border-purple-300 text-purple-600 hover:bg-purple-50 transition"
|
||||
title="Activar privacy WHOIS">
|
||||
👁
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
@@ -166,6 +219,7 @@
|
||||
<th class="py-2 px-3">Precio</th>
|
||||
<th class="py-2 px-3">Período</th>
|
||||
<th class="py-2 px-3">Vence / Próximo cobro</th>
|
||||
<th class="py-2 px-3">Auto-renovar</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -180,6 +234,16 @@
|
||||
<td class="py-2 px-3 text-xs font-semibold font-mono" x-text="o.total_price ? o.currency_code + '\u00a0' + new Intl.NumberFormat('es-CO').format(o.total_price / 100) : '—'"></td>
|
||||
<td class="py-2 px-3 text-xs text-gray-500" x-text="o.billing_period + '\u00a0' + (o.billing_period_unit === 'year' ? (o.billing_period === 1 ? 'año' : 'años') : (o.billing_period === 1 ? 'mes' : 'meses'))"></td>
|
||||
<td class="py-2 px-3 text-xs text-gray-500" x-text="o.expires_at || o.next_billing_at || '—'"></td>
|
||||
<td class="py-2 px-3">
|
||||
<button x-show="!o.is_auto_renewed" @click="toggleAutoRenewal(o.id, true)"
|
||||
class="text-xs px-2 py-1 rounded border border-green-400 text-green-600 hover:bg-green-50 transition">
|
||||
Activar
|
||||
</button>
|
||||
<button x-show="o.is_auto_renewed" @click="toggleAutoRenewal(o.id, false)"
|
||||
class="text-xs px-2 py-1 rounded border border-red-300 text-red-500 hover:bg-red-50 transition">
|
||||
Desactivar
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
@@ -189,6 +253,106 @@
|
||||
|
||||
</div><!-- /container -->
|
||||
|
||||
<!-- ─── Modal: VPS Root Password ─── -->
|
||||
<div x-show="vpsPasswordModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
|
||||
@click.self="vpsPasswordModal=false">
|
||||
<div class="bg-white rounded-xl shadow-xl w-full max-w-sm">
|
||||
<div class="flex items-center justify-between px-5 py-4 border-b">
|
||||
<h3 class="font-semibold text-sm">Cambiar contraseña root</h3>
|
||||
<button @click="vpsPasswordModal=false" class="text-gray-400 hover:text-gray-600">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="p-5 space-y-4">
|
||||
<div>
|
||||
<label class="text-xs font-medium text-gray-600">Nueva contraseña *</label>
|
||||
<input x-model="vpsPasswordForm.password" type="password" required autocomplete="new-password"
|
||||
class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono"
|
||||
placeholder="Mín. 8 caracteres, letras y números" />
|
||||
</div>
|
||||
<div class="flex gap-3 justify-end">
|
||||
<button @click="vpsPasswordModal=false" class="px-4 py-2 rounded border text-sm text-gray-600 hover:bg-gray-50">Cancelar</button>
|
||||
<button @click="setRootPassword()" :disabled="loading || !vpsPasswordForm.password"
|
||||
class="px-4 py-2 rounded text-sm bg-[#8eb02f] text-white hover:bg-[#6d8c24] disabled:opacity-40 transition">
|
||||
Guardar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ─── Modal: VPS Hostname ─── -->
|
||||
<div x-show="vpsHostnameModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
|
||||
@click.self="vpsHostnameModal=false">
|
||||
<div class="bg-white rounded-xl shadow-xl w-full max-w-sm">
|
||||
<div class="flex items-center justify-between px-5 py-4 border-b">
|
||||
<h3 class="font-semibold text-sm">Cambiar Hostname</h3>
|
||||
<button @click="vpsHostnameModal=false" class="text-gray-400 hover:text-gray-600">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="p-5 space-y-4">
|
||||
<div>
|
||||
<label class="text-xs font-medium text-gray-600">Hostname *</label>
|
||||
<input x-model="vpsHostnameForm.hostname" type="text" required
|
||||
class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono"
|
||||
placeholder="servidor.ejemplo.com" />
|
||||
</div>
|
||||
<div class="flex gap-3 justify-end">
|
||||
<button @click="vpsHostnameModal=false" class="px-4 py-2 rounded border text-sm text-gray-600 hover:bg-gray-50">Cancelar</button>
|
||||
<button @click="setHostname()" :disabled="loading || !vpsHostnameForm.hostname"
|
||||
class="px-4 py-2 rounded text-sm bg-[#8eb02f] text-white hover:bg-[#6d8c24] disabled:opacity-40 transition">
|
||||
Guardar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ─── Modal: Nameservers ─── -->
|
||||
<div x-show="nsModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
|
||||
@click.self="nsModal=false">
|
||||
<div class="bg-white rounded-xl shadow-xl w-full max-w-md">
|
||||
<div class="flex items-center justify-between px-5 py-4 border-b">
|
||||
<h3 class="font-semibold text-sm">Editar Nameservers — <span class="font-mono text-[#6d8c24]" x-text="nsForm.domain"></span></h3>
|
||||
<button @click="nsModal=false" class="text-gray-400 hover:text-gray-600">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="p-5 space-y-3">
|
||||
<div>
|
||||
<label class="text-xs font-medium text-gray-600 uppercase">NS1</label>
|
||||
<input x-model="nsForm.ns1" type="text" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" placeholder="ns1.hostinger.com" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs font-medium text-gray-600 uppercase">NS2</label>
|
||||
<input x-model="nsForm.ns2" type="text" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" placeholder="ns2.hostinger.com" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs font-medium text-gray-600 uppercase">NS3</label>
|
||||
<input x-model="nsForm.ns3" type="text" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" placeholder="ns3.hostinger.com" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs font-medium text-gray-600 uppercase">NS4</label>
|
||||
<input x-model="nsForm.ns4" type="text" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" placeholder="ns4.hostinger.com" />
|
||||
</div>
|
||||
<div class="flex gap-3 justify-end pt-2">
|
||||
<button @click="nsModal=false" class="px-4 py-2 rounded border text-sm text-gray-600 hover:bg-gray-50">Cancelar</button>
|
||||
<button @click="updateNameservers()" :disabled="loading"
|
||||
class="px-4 py-2 rounded text-sm bg-[#8eb02f] text-white hover:bg-[#6d8c24] disabled:opacity-40 transition">
|
||||
Guardar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ─── Modal: DNS Records ─── -->
|
||||
<div x-show="dnsModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
|
||||
@click.self="dnsModal=false">
|
||||
@@ -232,11 +396,46 @@
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- Agregar registro DNS -->
|
||||
<div class="mt-5 border-t pt-4">
|
||||
<p class="text-xs font-semibold text-gray-500 mb-2">Agregar registro</p>
|
||||
<div class="grid grid-cols-2 gap-2 mb-2">
|
||||
<div>
|
||||
<label class="text-xs text-gray-500">Tipo</label>
|
||||
<select x-model="dnsAddForm.type" class="w-full border rounded px-2 py-1 text-xs">
|
||||
<option>A</option><option>AAAA</option><option>CNAME</option>
|
||||
<option>MX</option><option>TXT</option><option>NS</option>
|
||||
<option>SRV</option><option>CAA</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs text-gray-500">TTL</label>
|
||||
<input x-model.number="dnsAddForm.ttl" type="number" class="w-full border rounded px-2 py-1 text-xs" placeholder="14400" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs text-gray-500">Nombre</label>
|
||||
<input x-model="dnsAddForm.name" type="text" class="w-full border rounded px-2 py-1 text-xs font-mono" placeholder="@ o subdominio" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs text-gray-500">Contenido</label>
|
||||
<input x-model="dnsAddForm.content" type="text" class="w-full border rounded px-2 py-1 text-xs font-mono" placeholder="IP, hostname..." />
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button @click="addDNSRecord()" :disabled="loading || !dnsAddForm.content"
|
||||
class="flex-1 py-1.5 rounded text-xs bg-[#8eb02f] text-white hover:bg-[#6d8c24] disabled:opacity-40 transition">
|
||||
+ Agregar registro
|
||||
</button>
|
||||
<button @click="resetDNS()" :disabled="loading"
|
||||
class="px-3 py-1.5 rounded text-xs bg-red-100 text-red-600 hover:bg-red-200 disabled:opacity-40 transition">
|
||||
Reset DNS
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ─── Modal: Configurar Token ─── -->
|
||||
<div x-show="configModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
|
||||
@click.self="configModal=false">
|
||||
<div class="bg-white rounded-xl shadow-xl w-full max-w-md">
|
||||
@@ -293,9 +492,19 @@ document.addEventListener('alpine:init', () => {
|
||||
dnsRecords: [],
|
||||
dnsDomain: '',
|
||||
dnsNameServers: null,
|
||||
dnsAddForm: { name: '', type: 'A', content: '', ttl: 14400 },
|
||||
dnsModal: false,
|
||||
configModal: false,
|
||||
cfgForm: { id: 0, token: '', nota: '' },
|
||||
// VPS actions
|
||||
vpsActionLoading: {},
|
||||
vpsPasswordModal: false,
|
||||
vpsPasswordForm: { id: 0, password: '' },
|
||||
vpsHostnameModal: false,
|
||||
vpsHostnameForm: { id: 0, hostname: '' },
|
||||
// Nameservers
|
||||
nsModal: false,
|
||||
nsForm: { domain: '', ns1: '', ns2: '', ns3: '', ns4: '' },
|
||||
toast: { show: false, msg: '', type: 'ok' },
|
||||
|
||||
async init() {
|
||||
@@ -376,6 +585,121 @@ document.addEventListener('alpine:init', () => {
|
||||
showToast(msg, type = 'ok') {
|
||||
this.toast = { show: true, msg, type };
|
||||
setTimeout(() => this.toast.show = false, 3500);
|
||||
},
|
||||
|
||||
async vpsAction(id, action) {
|
||||
this.vpsActionLoading = { ...this.vpsActionLoading, [id]: action };
|
||||
try {
|
||||
await axios.post(`/app/hostinger/vps/${id}/${action}`);
|
||||
this.showToast(`${action.charAt(0).toUpperCase()+action.slice(1)} enviado`);
|
||||
setTimeout(() => this.loadTab(), 1500);
|
||||
} catch (e) {
|
||||
this.showToast(e.response?.data?.error || `Error: ${action}`, 'error');
|
||||
}
|
||||
const updated = { ...this.vpsActionLoading };
|
||||
delete updated[id];
|
||||
this.vpsActionLoading = updated;
|
||||
},
|
||||
|
||||
async setRootPassword() {
|
||||
this.loading = true;
|
||||
try {
|
||||
await axios.put(`/app/hostinger/vps/${this.vpsPasswordForm.id}/root-password`,
|
||||
{ password: this.vpsPasswordForm.password });
|
||||
this.showToast('Contraseña cambiada correctamente');
|
||||
this.vpsPasswordModal = false;
|
||||
this.vpsPasswordForm = { id: 0, password: '' };
|
||||
} catch (e) {
|
||||
this.showToast(e.response?.data?.error || 'Error al cambiar contraseña', 'error');
|
||||
}
|
||||
this.loading = false;
|
||||
},
|
||||
|
||||
async setHostname() {
|
||||
this.loading = true;
|
||||
try {
|
||||
await axios.put(`/app/hostinger/vps/${this.vpsHostnameForm.id}/hostname`,
|
||||
{ hostname: this.vpsHostnameForm.hostname });
|
||||
this.showToast('Hostname actualizado');
|
||||
this.vpsHostnameModal = false;
|
||||
this.vpsHostnameForm = { id: 0, hostname: '' };
|
||||
await this.loadTab();
|
||||
} catch (e) {
|
||||
this.showToast(e.response?.data?.error || 'Error al cambiar hostname', 'error');
|
||||
}
|
||||
this.loading = false;
|
||||
},
|
||||
|
||||
async updateNameservers() {
|
||||
this.loading = true;
|
||||
try {
|
||||
await axios.put(`/app/hostinger/domains/${encodeURIComponent(this.nsForm.domain)}/nameservers`,
|
||||
{ ns1: this.nsForm.ns1, ns2: this.nsForm.ns2, ns3: this.nsForm.ns3, ns4: this.nsForm.ns4 });
|
||||
this.showToast('Nameservers actualizados');
|
||||
this.nsModal = false;
|
||||
await this.loadTab();
|
||||
} catch (e) {
|
||||
this.showToast(e.response?.data?.error || 'Error al actualizar nameservers', 'error');
|
||||
}
|
||||
this.loading = false;
|
||||
},
|
||||
|
||||
async toggleDomainLock(domain, enable) {
|
||||
try {
|
||||
if (enable) await axios.put(`/app/hostinger/domains/${encodeURIComponent(domain)}/domain-lock`);
|
||||
else await axios.delete(`/app/hostinger/domains/${encodeURIComponent(domain)}/domain-lock`);
|
||||
this.showToast(enable ? 'Dominio bloqueado' : 'Dominio desbloqueado');
|
||||
await this.loadTab();
|
||||
} catch (e) { this.showToast(e.response?.data?.error || 'Error', 'error'); }
|
||||
},
|
||||
|
||||
async togglePrivacy(domain, enable) {
|
||||
try {
|
||||
if (enable) await axios.put(`/app/hostinger/domains/${encodeURIComponent(domain)}/privacy`);
|
||||
else await axios.delete(`/app/hostinger/domains/${encodeURIComponent(domain)}/privacy`);
|
||||
this.showToast(enable ? 'Privacy activada' : 'Privacy desactivada');
|
||||
await this.loadTab();
|
||||
} catch (e) { this.showToast(e.response?.data?.error || 'Error', 'error'); }
|
||||
},
|
||||
|
||||
async toggleAutoRenewal(id, enable) {
|
||||
try {
|
||||
if (enable) await axios.patch(`/app/hostinger/billing/${id}/auto-renewal/enable`);
|
||||
else await axios.delete(`/app/hostinger/billing/${id}/auto-renewal/disable`);
|
||||
this.showToast(enable ? 'Autorenovación activada' : 'Autorenovación desactivada');
|
||||
await this.loadTab();
|
||||
} catch (e) { this.showToast(e.response?.data?.error || 'Error', 'error'); }
|
||||
},
|
||||
|
||||
async addDNSRecord() {
|
||||
this.loading = true;
|
||||
try {
|
||||
await axios.put(`/app/hostinger/dns/${encodeURIComponent(this.dnsDomain)}`, {
|
||||
overwrite: false,
|
||||
zone: [{ name: this.dnsAddForm.name, type: this.dnsAddForm.type,
|
||||
ttl: this.dnsAddForm.ttl,
|
||||
records: [{ content: this.dnsAddForm.content }] }]
|
||||
});
|
||||
this.showToast('Registro DNS agregado');
|
||||
this.dnsAddForm = { name: '', type: 'A', content: '', ttl: 14400 };
|
||||
await this.loadDNSForDomain(this.dnsDomain);
|
||||
} catch (e) {
|
||||
this.showToast(e.response?.data?.error || 'Error al agregar registro', 'error');
|
||||
}
|
||||
this.loading = false;
|
||||
},
|
||||
|
||||
async resetDNS() {
|
||||
if (!confirm(`¿Resetear la zona DNS de ${this.dnsDomain}? Se restaurarán los valores por defecto.`)) return;
|
||||
this.loading = true;
|
||||
try {
|
||||
await axios.post(`/app/hostinger/dns/${encodeURIComponent(this.dnsDomain)}/reset`);
|
||||
this.showToast('Zona DNS reseteada');
|
||||
await this.loadDNSForDomain(this.dnsDomain);
|
||||
} catch (e) {
|
||||
this.showToast(e.response?.data?.error || 'Error al resetear DNS', 'error');
|
||||
}
|
||||
this.loading = false;
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -141,3 +141,240 @@ func GetHostingerHosting(c *fiber.Ctx) error {
|
||||
}
|
||||
return c.JSON(fiber.Map{"data": data})
|
||||
}
|
||||
|
||||
// ─── DNS: escritura ──────────────────────────────────────────────────────────
|
||||
|
||||
// UpdateHostingerDNS agrega o actualiza registros DNS.
|
||||
func UpdateHostingerDNS(c *fiber.Ctx) error {
|
||||
domain := c.Params("domain")
|
||||
if domain == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "dominio requerido"})
|
||||
}
|
||||
var body struct {
|
||||
Overwrite bool `json:"overwrite"`
|
||||
Zone []services.HostingerDNSZoneInput `json:"zone"`
|
||||
}
|
||||
if err := c.BodyParser(&body); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "body inválido"})
|
||||
}
|
||||
client, err := hostingerClient()
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
if err := client.UpdateDNSZone(domain, body.Overwrite, body.Zone); err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "DNS actualizado"})
|
||||
}
|
||||
|
||||
// ResetHostingerDNS resetea la zona DNS de un dominio.
|
||||
func ResetHostingerDNS(c *fiber.Ctx) error {
|
||||
domain := c.Params("domain")
|
||||
if domain == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "dominio requerido"})
|
||||
}
|
||||
client, err := hostingerClient()
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
if err := client.ResetDNS(domain); err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Zona DNS reseteada"})
|
||||
}
|
||||
|
||||
// ─── Domains: escritura ──────────────────────────────────────────────────────
|
||||
|
||||
// UpdateHostingerNameservers actualiza los nameservers de un dominio.
|
||||
func UpdateHostingerNameservers(c *fiber.Ctx) error {
|
||||
domain := c.Params("domain")
|
||||
var body struct {
|
||||
NS1 string `json:"ns1"`
|
||||
NS2 string `json:"ns2"`
|
||||
NS3 string `json:"ns3"`
|
||||
NS4 string `json:"ns4"`
|
||||
}
|
||||
if err := c.BodyParser(&body); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "body inválido"})
|
||||
}
|
||||
client, err := hostingerClient()
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
if err := client.UpdateNameservers(domain, body.NS1, body.NS2, body.NS3, body.NS4); err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Nameservers actualizados"})
|
||||
}
|
||||
|
||||
// EnableHostingerDomainLock activa el bloqueo del dominio.
|
||||
func EnableHostingerDomainLock(c *fiber.Ctx) error {
|
||||
return hostingerDomainToggle(c, "domain-lock", true)
|
||||
}
|
||||
|
||||
// DisableHostingerDomainLock desactiva el bloqueo del dominio.
|
||||
func DisableHostingerDomainLock(c *fiber.Ctx) error {
|
||||
return hostingerDomainToggle(c, "domain-lock", false)
|
||||
}
|
||||
|
||||
// EnableHostingerPrivacy activa la protección WHOIS.
|
||||
func EnableHostingerPrivacy(c *fiber.Ctx) error {
|
||||
return hostingerDomainToggle(c, "privacy", true)
|
||||
}
|
||||
|
||||
// DisableHostingerPrivacy desactiva la protección WHOIS.
|
||||
func DisableHostingerPrivacy(c *fiber.Ctx) error {
|
||||
return hostingerDomainToggle(c, "privacy", false)
|
||||
}
|
||||
|
||||
func hostingerDomainToggle(c *fiber.Ctx, feature string, enable bool) error {
|
||||
domain := c.Params("domain")
|
||||
client, err := hostingerClient()
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
var e error
|
||||
switch feature {
|
||||
case "domain-lock":
|
||||
e = client.SetDomainLock(domain, enable)
|
||||
case "privacy":
|
||||
e = client.SetPrivacyProtection(domain, enable)
|
||||
}
|
||||
if e != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": e.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Operación realizada"})
|
||||
}
|
||||
|
||||
// ─── VPS: acciones ───────────────────────────────────────────────────────────
|
||||
|
||||
// StartHostingerVPS arranca una VM.
|
||||
func StartHostingerVPS(c *fiber.Ctx) error { return vpsAction(c, "start") }
|
||||
|
||||
// StopHostingerVPS apaga una VM.
|
||||
func StopHostingerVPS(c *fiber.Ctx) error { return vpsAction(c, "stop") }
|
||||
|
||||
// RestartHostingerVPS reinicia una VM.
|
||||
func RestartHostingerVPS(c *fiber.Ctx) error { return vpsAction(c, "restart") }
|
||||
|
||||
func vpsAction(c *fiber.Ctx, action string) error {
|
||||
id, err := c.ParamsInt("id")
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
|
||||
}
|
||||
client, errC := hostingerClient()
|
||||
if errC != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
if err := client.VPSAction(id, action); err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": action + " enviado"})
|
||||
}
|
||||
|
||||
// SetHostingerVPSRootPassword cambia la contraseña root de una VM.
|
||||
func SetHostingerVPSRootPassword(c *fiber.Ctx) error {
|
||||
id, err := c.ParamsInt("id")
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
|
||||
}
|
||||
var body struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := c.BodyParser(&body); err != nil || body.Password == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "password requerido"})
|
||||
}
|
||||
client, errC := hostingerClient()
|
||||
if errC != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
if err := client.SetVPSRootPassword(id, body.Password); err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Contraseña actualizada"})
|
||||
}
|
||||
|
||||
// SetHostingerVPSHostname cambia el hostname de una VM.
|
||||
func SetHostingerVPSHostname(c *fiber.Ctx) error {
|
||||
id, err := c.ParamsInt("id")
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
|
||||
}
|
||||
var body struct {
|
||||
Hostname string `json:"hostname"`
|
||||
}
|
||||
if err := c.BodyParser(&body); err != nil || body.Hostname == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "hostname requerido"})
|
||||
}
|
||||
client, errC := hostingerClient()
|
||||
if errC != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
if err := client.SetVPSHostname(id, body.Hostname); err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Hostname actualizado"})
|
||||
}
|
||||
|
||||
// GetHostingerVPSMetrics retorna las métricas de una VM.
|
||||
func GetHostingerVPSMetrics(c *fiber.Ctx) error {
|
||||
id, err := c.ParamsInt("id")
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
|
||||
}
|
||||
client, errC := hostingerClient()
|
||||
if errC != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
data, err := client.GetVPSMetrics(id)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(data)
|
||||
}
|
||||
|
||||
// GetHostingerVPSBackups retorna los backups de una VM.
|
||||
func GetHostingerVPSBackups(c *fiber.Ctx) error {
|
||||
id, err := c.ParamsInt("id")
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
|
||||
}
|
||||
client, errC := hostingerClient()
|
||||
if errC != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
data, err := client.GetVPSBackups(id)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(data)
|
||||
}
|
||||
|
||||
// ─── Billing: acciones ───────────────────────────────────────────────────────
|
||||
|
||||
// EnableHostingerAutoRenewal activa la autorenovación de una suscripción.
|
||||
func EnableHostingerAutoRenewal(c *fiber.Ctx) error {
|
||||
return hostingerAutoRenewalToggle(c, true)
|
||||
}
|
||||
|
||||
// DisableHostingerAutoRenewal desactiva la autorenovación de una suscripción.
|
||||
func DisableHostingerAutoRenewal(c *fiber.Ctx) error {
|
||||
return hostingerAutoRenewalToggle(c, false)
|
||||
}
|
||||
|
||||
func hostingerAutoRenewalToggle(c *fiber.Ctx, enable bool) error {
|
||||
subID := c.Params("id")
|
||||
if subID == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id requerido"})
|
||||
}
|
||||
client, err := hostingerClient()
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusFailedDependency).JSON(fiber.Map{"error": "No se encontró configuración activa de Hostinger"})
|
||||
}
|
||||
sub, err := client.ToggleAutoRenewal(subID, enable)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"data": sub})
|
||||
}
|
||||
|
||||
|
||||
@@ -117,8 +117,27 @@ func UserRoutes(app fiber.Router) {
|
||||
protected.Get("/hostinger/vps", controllers.GetHostingerVPS)
|
||||
protected.Get("/hostinger/domains", controllers.GetHostingerDomains)
|
||||
protected.Get("/hostinger/dns/:domain", controllers.GetHostingerDNS)
|
||||
protected.Put("/hostinger/dns/:domain", controllers.UpdateHostingerDNS)
|
||||
protected.Post("/hostinger/dns/:domain/reset", controllers.ResetHostingerDNS)
|
||||
protected.Get("/hostinger/orders", controllers.GetHostingerOrders)
|
||||
protected.Get("/hostinger/hosting", controllers.GetHostingerHosting)
|
||||
// Domains: escritura
|
||||
protected.Put("/hostinger/domains/:domain/nameservers", controllers.UpdateHostingerNameservers)
|
||||
protected.Put("/hostinger/domains/:domain/domain-lock", controllers.EnableHostingerDomainLock)
|
||||
protected.Delete("/hostinger/domains/:domain/domain-lock", controllers.DisableHostingerDomainLock)
|
||||
protected.Put("/hostinger/domains/:domain/privacy", controllers.EnableHostingerPrivacy)
|
||||
protected.Delete("/hostinger/domains/:domain/privacy", controllers.DisableHostingerPrivacy)
|
||||
// VPS: acciones
|
||||
protected.Post("/hostinger/vps/:id/start", controllers.StartHostingerVPS)
|
||||
protected.Post("/hostinger/vps/:id/stop", controllers.StopHostingerVPS)
|
||||
protected.Post("/hostinger/vps/:id/restart", controllers.RestartHostingerVPS)
|
||||
protected.Put("/hostinger/vps/:id/root-password", controllers.SetHostingerVPSRootPassword)
|
||||
protected.Put("/hostinger/vps/:id/hostname", controllers.SetHostingerVPSHostname)
|
||||
protected.Get("/hostinger/vps/:id/metrics", controllers.GetHostingerVPSMetrics)
|
||||
protected.Get("/hostinger/vps/:id/backups", controllers.GetHostingerVPSBackups)
|
||||
// Billing: autorenovación
|
||||
protected.Patch("/hostinger/billing/:id/auto-renewal/enable", controllers.EnableHostingerAutoRenewal)
|
||||
protected.Delete("/hostinger/billing/:id/auto-renewal/disable", controllers.DisableHostingerAutoRenewal)
|
||||
|
||||
// ─── Cloudflare API ───────────────────────────────────────────────
|
||||
protected.Get("/cloudflare", middlewares.MenuMiddleware, controllers.CloudflareConfigPage)
|
||||
|
||||
Reference in New Issue
Block a user