Files
coulobre/src/coulobre/hosting/dns_forms.py
T

68 lines
2.3 KiB
Python

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
)