Manage DNS zones and export BIND9 manifests from hosting accounts
This commit is contained in:
1 parent
74b7dcedbe
commit
4fcbf723de
11 files changed
+595
-9
No files matched your search
@@ -9,6 +9,7 @@ from .domain_names import canonical_domain
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
MANIFEST_KIND = "bind9_zone"
|
||||
MAX_SOA_SERIAL = 2**32 - 1
|
||||
|
||||
|
||||
def dns_name(value):
|
||||
@@ -60,7 +61,7 @@ class DnsZone:
|
||||
def __post_init__(self):
|
||||
object.__setattr__(self, "domain", dns_name(self.domain))
|
||||
object.__setattr__(self, "responsible_name", dns_name(self.responsible_name))
|
||||
if type(self.serial) is not int or not 0 <= self.serial < 2**32:
|
||||
if type(self.serial) is not int or not 0 <= self.serial <= MAX_SOA_SERIAL:
|
||||
raise ValueError("The SOA serial must be an unsigned 32-bit integer.")
|
||||
nameservers = tuple(dns_name(name) for name in self.nameservers)
|
||||
if not nameservers or len(set(nameservers)) != len(nameservers):
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
from django import forms
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL, AddressRecord, DnsZone
|
||||
|
||||
|
||||
class DnsZoneForm(forms.Form):
|
||||
nameservers = forms.CharField(
|
||||
widget=forms.Textarea(attrs={"rows": 3, "spellcheck": "false"}),
|
||||
help_text="Enter one hostname per line. The first is the SOA primary.",
|
||||
)
|
||||
responsible_name = forms.CharField(
|
||||
label="SOA mailbox",
|
||||
max_length=253,
|
||||
help_text="Use DNS mailbox notation, such as hostmaster.example.net.",
|
||||
)
|
||||
addresses = forms.CharField(
|
||||
required=False,
|
||||
widget=forms.Textarea(attrs={"rows": 5, "spellcheck": "false"}),
|
||||
help_text="Enter a fully qualified name and an IPv4 or IPv6 address on each line.",
|
||||
)
|
||||
|
||||
def __init__(self, *args, domain, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.domain = domain
|
||||
|
||||
def clean_addresses(self):
|
||||
records = []
|
||||
for number, line in enumerate(self.cleaned_data["addresses"].splitlines(), 1):
|
||||
if not line.strip():
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) != 2:
|
||||
raise forms.ValidationError(
|
||||
f"Enter a name and an IP address on line {number}."
|
||||
)
|
||||
try:
|
||||
records.append(AddressRecord(*parts))
|
||||
except ValueError as error:
|
||||
raise forms.ValidationError(f"Line {number}. {error}") from error
|
||||
return tuple(records)
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
if self.errors:
|
||||
return data
|
||||
try:
|
||||
spec = DnsZone(
|
||||
domain=self.domain,
|
||||
serial=data.get("serial", 1),
|
||||
nameservers=tuple(data["nameservers"].split()),
|
||||
responsible_name=data["responsible_name"],
|
||||
addresses=data["addresses"],
|
||||
)
|
||||
except ValueError as error:
|
||||
raise forms.ValidationError(str(error)) from error
|
||||
data.update(
|
||||
nameservers=list(spec.nameservers),
|
||||
responsible_name=spec.responsible_name,
|
||||
addresses=spec.manifest()["addresses"],
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
class DnsZoneEditForm(DnsZoneForm):
|
||||
serial = forms.IntegerField(
|
||||
min_value=0, max_value=MAX_SOA_SERIAL, widget=forms.HiddenInput
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-19 22:08
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
import coulobre.hosting.fields
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0006_hostingdatabase"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="HostingDnsZone",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
(
|
||||
"domain",
|
||||
coulobre.hosting.fields.DomainNameField(
|
||||
max_length=253, unique=True
|
||||
),
|
||||
),
|
||||
("serial", models.PositiveBigIntegerField(default=1)),
|
||||
("nameservers", models.JSONField()),
|
||||
(
|
||||
"responsible_name",
|
||||
coulobre.hosting.fields.DomainNameField(max_length=253),
|
||||
),
|
||||
("addresses", models.JSONField(default=list)),
|
||||
(
|
||||
"account",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.PROTECT,
|
||||
related_name="dns_zones",
|
||||
to="hosting.hostingaccount",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ("domain",),
|
||||
"constraints": [
|
||||
models.CheckConstraint(
|
||||
condition=models.Q(("serial__lte", 4294967295)),
|
||||
name="hosting_dns_zone_valid_serial",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -4,6 +4,7 @@ from django.db import models
|
||||
from django.urls import reverse
|
||||
|
||||
from coulobre.database_node import DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, DatabaseSpec
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL, AddressRecord, DnsZone
|
||||
|
||||
from .fields import DomainNameField
|
||||
|
||||
@@ -82,6 +83,41 @@ class HostingDatabase(models.Model):
|
||||
return self.spec.name
|
||||
|
||||
|
||||
class HostingDnsZone(models.Model):
|
||||
account = models.ForeignKey(
|
||||
HostingAccount, on_delete=models.PROTECT, related_name="dns_zones"
|
||||
)
|
||||
domain = DomainNameField(max_length=253, unique=True)
|
||||
serial = models.PositiveBigIntegerField(default=1)
|
||||
nameservers = models.JSONField()
|
||||
responsible_name = DomainNameField(max_length=253)
|
||||
addresses = models.JSONField(default=list)
|
||||
|
||||
class Meta:
|
||||
ordering = ("domain",)
|
||||
constraints = [
|
||||
models.CheckConstraint(
|
||||
condition=models.Q(serial__lte=MAX_SOA_SERIAL),
|
||||
name="hosting_dns_zone_valid_serial",
|
||||
)
|
||||
]
|
||||
|
||||
@property
|
||||
def spec(self):
|
||||
return DnsZone(
|
||||
domain=self.domain,
|
||||
serial=self.serial,
|
||||
nameservers=tuple(self.nameservers),
|
||||
responsible_name=self.responsible_name,
|
||||
addresses=tuple(
|
||||
AddressRecord.from_manifest(item) for item in self.addresses
|
||||
),
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return str(self.domain)
|
||||
|
||||
|
||||
class WebProvisioningPlan(models.Model):
|
||||
account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE)
|
||||
primary_domain = DomainNameField(max_length=253)
|
||||
|
||||
@@ -29,7 +29,7 @@ a {
|
||||
text-underline-offset: 0.2em;
|
||||
}
|
||||
|
||||
button, input, select {
|
||||
button, input, select, textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
@@ -296,9 +296,8 @@ h2 {
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
input:not([type="hidden"]), select {
|
||||
input:not([type="hidden"]), select, textarea {
|
||||
min-width: 0;
|
||||
height: 2.55rem;
|
||||
padding: 0.48rem 0.68rem;
|
||||
border: 1px solid #bbcbbf;
|
||||
border-radius: 7px;
|
||||
@@ -306,6 +305,14 @@ input:not([type="hidden"]), select {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
input:not([type="hidden"]), select {
|
||||
height: 2.55rem;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
color: var(--muted);
|
||||
}
|
||||
@@ -471,7 +478,7 @@ dd {
|
||||
font-weight: 680;
|
||||
}
|
||||
|
||||
.editor input:not([type="hidden"]), .editor select {
|
||||
.editor input:not([type="hidden"]), .editor select, .editor textarea {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
|
||||
@@ -64,4 +64,46 @@
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if is_reseller or perms.hosting.view_hostingdnszone %}
|
||||
<section class="surface" aria-labelledby="dns-zones-heading">
|
||||
<header class="section-heading">
|
||||
<h2 id="dns-zones-heading">DNS zones</h2>
|
||||
{% if not is_reseller and perms.hosting.add_hostingdnszone and not has_primary_zone %}
|
||||
<a class="button primary" href="{% url 'panel:dns_zone_create' account.pk %}">Add DNS zone</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if dns_zones %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Domain</th>
|
||||
<th scope="col">SOA serial</th>
|
||||
{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for zone in dns_zones %}
|
||||
<tr>
|
||||
<td class="domain">
|
||||
{% if not is_reseller and perms.hosting.change_hostingdnszone %}
|
||||
<a class="record-link" href="{% url 'panel:dns_zone_edit' zone.pk %}" aria-label="Edit DNS zone for {{ zone.domain }}">{{ zone.domain }}</a>
|
||||
{% else %}
|
||||
{{ zone.domain }}
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ zone.serial }}</td>
|
||||
{% if not is_reseller %}
|
||||
<td><a class="record-link" href="{% url 'panel:dns_zone_manifest' zone.pk %}" aria-label="Download DNS manifest for {{ zone.domain }}">Download manifest</a></td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty">No DNS zones configured.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}{{ page_title }} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>{{ page_title }}</h1>
|
||||
<p class="heading-meta domain">{{ domain }}</p>
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Save zone</button>
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,201 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL, DnsZone
|
||||
|
||||
from .models import HostingAccount, HostingDnsZone, Reseller
|
||||
|
||||
|
||||
class DnsZonePanelTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
users = get_user_model().objects
|
||||
cls.operator = users.create_superuser("operator")
|
||||
cls.reseller_user = users.create_user("reseller")
|
||||
cls.reader = users.create_user("reader")
|
||||
cls.reader.user_permissions.set(
|
||||
Permission.objects.filter(
|
||||
content_type__app_label="hosting",
|
||||
codename__in=("view_hostingaccount", "view_hostingdnszone"),
|
||||
)
|
||||
)
|
||||
reseller = Reseller.objects.create(user=cls.reseller_user)
|
||||
cls.account = HostingAccount.objects.create(
|
||||
name="Account A", primary_domain="account-a.example", reseller=reseller
|
||||
)
|
||||
cls.other = HostingAccount.objects.create(
|
||||
name="Account B", primary_domain="account-b.example"
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.client.force_login(self.operator)
|
||||
self.add_url = reverse("panel:dns_zone_create", args=[self.account.pk])
|
||||
self.zone_data = {
|
||||
"nameservers": "NS1.Account-A.Example.\nns2.provider.example",
|
||||
"responsible_name": "Hostmaster.Account-A.Example.",
|
||||
"addresses": (
|
||||
"account-a.example 192.0.2.20\n"
|
||||
"ns1.account-a.example 192.0.2.53\n"
|
||||
"www.account-a.example 2001:0db8::20"
|
||||
),
|
||||
}
|
||||
|
||||
def create_zone(self):
|
||||
self.assertRedirects(
|
||||
self.client.post(self.add_url, self.zone_data),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
return self.account.dns_zones.get()
|
||||
|
||||
def test_operator_can_create_a_zone_and_download_its_renderable_manifest(self):
|
||||
self.assertContains(self.client.get(self.add_url), "Add DNS zone")
|
||||
zone = self.create_zone()
|
||||
self.assertEqual(zone.domain, self.account.primary_domain)
|
||||
self.assertEqual(zone.serial, 1)
|
||||
self.assertEqual(zone.responsible_name, "hostmaster.account-a.example")
|
||||
self.assertEqual(
|
||||
zone.nameservers, ["ns1.account-a.example", "ns2.provider.example"]
|
||||
)
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, f"Edit DNS zone for {zone.domain}")
|
||||
self.assertNotContains(account, self.add_url)
|
||||
|
||||
manifest = self.client.get(reverse("panel:dns_zone_manifest", args=[zone.pk]))
|
||||
self.assertEqual(manifest["Cache-Control"], "private, no-store")
|
||||
self.assertIn("attachment", manifest["Content-Disposition"])
|
||||
spec = DnsZone.from_manifest(manifest.json())
|
||||
self.assertEqual(spec, zone.spec)
|
||||
self.assertIn("www.account-a.example. IN AAAA 2001:db8::20\n", spec.render())
|
||||
|
||||
def test_duplicate_and_invalid_zones_leave_the_current_zone_unchanged(self):
|
||||
invalid = self.client.post(self.add_url, self.zone_data | {"addresses": ""})
|
||||
self.assertContains(invalid, "Each in-zone nameserver needs an address record.")
|
||||
invalid = self.client.post(
|
||||
self.add_url, self.zone_data | {"addresses": "ns1.account-a.example"}
|
||||
)
|
||||
self.assertContains(invalid, "Enter a name and an IP address on line 1.")
|
||||
self.assertFalse(HostingDnsZone.objects.exists())
|
||||
|
||||
zone = self.create_zone()
|
||||
duplicate = self.client.post(self.add_url, self.zone_data)
|
||||
self.assertContains(duplicate, "A DNS zone already exists for this domain.")
|
||||
self.assertEqual(self.account.dns_zones.get().pk, zone.pk)
|
||||
|
||||
def test_edit_increments_serial_only_when_data_changes_and_rejects_stale_edits(
|
||||
self,
|
||||
):
|
||||
zone = self.create_zone()
|
||||
edit = reverse("panel:dns_zone_edit", args=[zone.pk])
|
||||
initial = self.client.get(edit)
|
||||
self.assertContains(initial, "Edit DNS zone")
|
||||
self.assertEqual(initial.context["form"].initial["serial"], 1)
|
||||
|
||||
self.assertRedirects(
|
||||
self.client.post(edit, self.zone_data | {"serial": 1}),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
zone.refresh_from_db()
|
||||
self.assertEqual(zone.serial, 1)
|
||||
|
||||
updated = self.zone_data | {
|
||||
"addresses": self.zone_data["addresses"].replace("192.0.2.20", "192.0.2.21")
|
||||
}
|
||||
self.assertRedirects(
|
||||
self.client.post(edit, updated | {"serial": 1}),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
stale = self.client.post(edit, self.zone_data | {"serial": 1})
|
||||
self.assertContains(stale, "This DNS zone changed while you were editing it.")
|
||||
manifest = self.client.get(
|
||||
reverse("panel:dns_zone_manifest", args=[zone.pk])
|
||||
).json()
|
||||
self.assertEqual(manifest["serial"], 2)
|
||||
self.assertEqual(manifest["addresses"][0]["address"], "192.0.2.21")
|
||||
|
||||
def test_serial_wraps_at_the_dns_boundary(self):
|
||||
zone = self.create_zone()
|
||||
HostingDnsZone.objects.filter(pk=zone.pk).update(serial=MAX_SOA_SERIAL)
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
reverse("panel:dns_zone_edit", args=[zone.pk]),
|
||||
self.zone_data
|
||||
| {
|
||||
"serial": MAX_SOA_SERIAL,
|
||||
"responsible_name": "dns.provider.example",
|
||||
},
|
||||
),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
zone.refresh_from_db()
|
||||
self.assertEqual(zone.serial, 0)
|
||||
|
||||
def test_renaming_account_keeps_its_existing_zone_and_allows_a_new_primary_zone(
|
||||
self,
|
||||
):
|
||||
zone = self.create_zone()
|
||||
response = self.client.post(
|
||||
reverse("panel:account_edit", args=[self.account.pk]),
|
||||
{"name": self.account.name, "primary_domain": "new.example"},
|
||||
)
|
||||
self.assertRedirects(response, self.account.get_absolute_url())
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, self.add_url)
|
||||
self.assertContains(account, f"Edit DNS zone for {zone.domain}")
|
||||
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
self.add_url,
|
||||
self.zone_data
|
||||
| {"nameservers": "ns2.provider.example", "addresses": ""},
|
||||
),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
self.assertEqual(
|
||||
list(self.account.dns_zones.values_list("domain", flat=True)),
|
||||
["account-a.example", "new.example"],
|
||||
)
|
||||
|
||||
def test_reseller_cannot_edit_or_download_even_with_django_permissions(self):
|
||||
zone = self.create_zone()
|
||||
self.reseller_user.user_permissions.set(
|
||||
Permission.objects.filter(content_type__app_label="hosting")
|
||||
)
|
||||
self.client.force_login(self.reseller_user)
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, "DNS zones")
|
||||
self.assertNotContains(account, "Edit DNS zone")
|
||||
self.assertNotContains(account, "Download DNS manifest")
|
||||
self.assertEqual(
|
||||
self.client.get(self.other.get_absolute_url()).status_code, 404
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.post(self.add_url, self.zone_data).status_code, 403
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.get(reverse("panel:dns_zone_edit", args=[zone.pk])).status_code,
|
||||
403,
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.get(
|
||||
reverse("panel:dns_zone_manifest", args=[zone.pk])
|
||||
).status_code,
|
||||
403,
|
||||
)
|
||||
|
||||
def test_operator_with_view_permissions_can_download_but_cannot_edit(self):
|
||||
zone = self.create_zone()
|
||||
self.client.force_login(self.reader)
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, "Download DNS manifest")
|
||||
self.assertNotContains(account, "Edit DNS zone")
|
||||
self.assertContains(
|
||||
self.client.get(reverse("panel:dns_zone_manifest", args=[zone.pk])),
|
||||
zone.domain,
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.get(reverse("panel:dns_zone_edit", args=[zone.pk])).status_code,
|
||||
403,
|
||||
)
|
||||
self.assertEqual(self.client.get(self.add_url).status_code, 403)
|
||||
@@ -29,6 +29,17 @@ urlpatterns = [
|
||||
views.DownloadDatabaseManifest.as_view(),
|
||||
name="database_manifest",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/dns-zones/new/",
|
||||
views.DnsZoneCreate.as_view(),
|
||||
name="dns_zone_create",
|
||||
),
|
||||
path("dns-zones/<int:pk>/edit/", views.DnsZoneEdit.as_view(), name="dns_zone_edit"),
|
||||
path(
|
||||
"dns-zones/<int:pk>/manifest/",
|
||||
views.DownloadDnsZoneManifest.as_view(),
|
||||
name="dns_zone_manifest",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan"
|
||||
),
|
||||
|
||||
@@ -7,11 +7,20 @@ from django.shortcuts import get_object_or_404, redirect
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.functional import cached_property
|
||||
from django.views import View
|
||||
from django.views.generic import CreateView, DetailView, ListView, UpdateView
|
||||
from django.views.generic import CreateView, DetailView, FormView, ListView, UpdateView
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL
|
||||
|
||||
from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user
|
||||
from .models import HostingAccount, HostingDatabase, HostingPlan, WebProvisioningPlan
|
||||
from .dns_forms import DnsZoneEditForm, DnsZoneForm
|
||||
from .models import (
|
||||
HostingAccount,
|
||||
HostingDatabase,
|
||||
HostingDnsZone,
|
||||
HostingPlan,
|
||||
WebProvisioningPlan,
|
||||
)
|
||||
from .reseller_accounts import create_reseller_account
|
||||
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
|
||||
|
||||
@@ -21,6 +30,7 @@ VIEW_PLANS = "hosting.view_webprovisioningplan"
|
||||
VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
|
||||
VIEW_RESELLERS = "hosting.view_reseller"
|
||||
VIEW_DATABASES = "hosting.view_hostingdatabase"
|
||||
VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
|
||||
|
||||
|
||||
class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
|
||||
@@ -150,6 +160,12 @@ class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
)[:10]
|
||||
if reseller is not None or user.has_perm(VIEW_DATABASES):
|
||||
context["databases"] = self.object.databases.all()
|
||||
if reseller is not None or user.has_perm(VIEW_DNS_ZONES):
|
||||
zones = list(self.object.dns_zones.all())
|
||||
context["dns_zones"] = zones
|
||||
context["has_primary_zone"] = any(
|
||||
zone.domain == self.object.primary_domain for zone in zones
|
||||
)
|
||||
return context
|
||||
|
||||
|
||||
@@ -196,6 +212,118 @@ class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View)
|
||||
)
|
||||
|
||||
|
||||
class DnsZoneEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
|
||||
template_name = "hosting/dns_zone_form.html"
|
||||
|
||||
def get_form_kwargs(self):
|
||||
return {**super().get_form_kwargs(), "domain": self.domain}
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(
|
||||
account=self.account, domain=self.domain, **kwargs
|
||||
)
|
||||
|
||||
def get_success_url(self):
|
||||
return self.account.get_absolute_url()
|
||||
|
||||
|
||||
class DnsZoneCreate(DnsZoneEditor):
|
||||
form_class = DnsZoneForm
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_DNS_ZONES, "hosting.add_hostingdnszone")
|
||||
extra_context = {"page_title": "Add DNS zone"}
|
||||
|
||||
@cached_property
|
||||
def account(self):
|
||||
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
|
||||
|
||||
@property
|
||||
def domain(self):
|
||||
return self.account.primary_domain
|
||||
|
||||
def get_initial(self):
|
||||
return {"responsible_name": f"hostmaster.{self.domain}"}
|
||||
|
||||
def form_valid(self, form):
|
||||
try:
|
||||
with transaction.atomic():
|
||||
HostingDnsZone.objects.create(
|
||||
account=self.account, domain=self.domain, **form.cleaned_data
|
||||
)
|
||||
except IntegrityError:
|
||||
if not HostingDnsZone.objects.filter(domain=self.domain).exists():
|
||||
raise
|
||||
form.add_error(None, "A DNS zone already exists for this domain.")
|
||||
return self.form_invalid(form)
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
class DnsZoneEdit(DnsZoneEditor):
|
||||
form_class = DnsZoneEditForm
|
||||
permission_required = (
|
||||
VIEW_ACCOUNTS,
|
||||
VIEW_DNS_ZONES,
|
||||
"hosting.change_hostingdnszone",
|
||||
)
|
||||
extra_context = {"page_title": "Edit DNS zone"}
|
||||
|
||||
@cached_property
|
||||
def zone(self):
|
||||
return get_object_or_404(
|
||||
HostingDnsZone.objects.select_related("account"), pk=self.kwargs["pk"]
|
||||
)
|
||||
|
||||
@property
|
||||
def account(self):
|
||||
return self.zone.account
|
||||
|
||||
@property
|
||||
def domain(self):
|
||||
return self.zone.domain
|
||||
|
||||
def get_initial(self):
|
||||
return {
|
||||
"serial": self.zone.serial,
|
||||
"nameservers": "\n".join(self.zone.nameservers),
|
||||
"responsible_name": self.zone.responsible_name,
|
||||
"addresses": "\n".join(
|
||||
f"{record['name']} {record['address']}"
|
||||
for record in self.zone.addresses
|
||||
),
|
||||
}
|
||||
|
||||
def form_valid(self, form):
|
||||
values = form.cleaned_data
|
||||
serial = values["serial"]
|
||||
if all(getattr(self.zone, field) == value for field, value in values.items()):
|
||||
return super().form_valid(form)
|
||||
|
||||
next_serial = (serial + 1) % (MAX_SOA_SERIAL + 1)
|
||||
updated = HostingDnsZone.objects.filter(pk=self.zone.pk, serial=serial).update(
|
||||
**(values | {"serial": next_serial})
|
||||
)
|
||||
if not updated:
|
||||
form.add_error(
|
||||
None,
|
||||
"This DNS zone changed while you were editing it. Reopen the form and try again.",
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
class DownloadDnsZoneManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_DNS_ZONES)
|
||||
|
||||
def get(self, request, pk):
|
||||
zone = get_object_or_404(HostingDnsZone, pk=pk)
|
||||
return JsonResponse(
|
||||
zone.spec.manifest(),
|
||||
headers={
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Disposition": f'attachment; filename="coulobre-zone-{zone.pk}.json"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
|
||||
model = HostingPlan
|
||||
permission_required = VIEW_HOSTING_PLANS
|
||||
|
||||
Reference in new issue
Block a user