509 lines
18 KiB
Python
509 lines
18 KiB
Python
from django.contrib.auth.mixins import PermissionRequiredMixin
|
|
from django.core.exceptions import ValidationError
|
|
from django.db import IntegrityError, transaction
|
|
from django.db.models import Q
|
|
from django.http import HttpResponse, JsonResponse
|
|
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, FormView, ListView, UpdateView
|
|
from django.views.generic.detail import SingleObjectMixin
|
|
|
|
from coulobre.dns_node import MAX_SOA_SERIAL
|
|
from coulobre.mail_node import INVALID_LOCAL_PART, MailboxSpec
|
|
|
|
from .access import (
|
|
OperatorOnlyMixin,
|
|
TenantScopeMixin,
|
|
customer_for_user,
|
|
reseller_for_user,
|
|
)
|
|
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
|
|
from .models import (
|
|
HostingAccount,
|
|
HostingDatabase,
|
|
HostingDnsZone,
|
|
HostingMailbox,
|
|
HostingMailDomain,
|
|
HostingPlan,
|
|
WebProvisioningPlan,
|
|
)
|
|
from .reseller_accounts import create_reseller_account
|
|
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
|
|
|
|
VIEW_ACCOUNTS = "hosting.view_hostingaccount"
|
|
CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
|
|
VIEW_PLANS = "hosting.view_webprovisioningplan"
|
|
VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
|
|
VIEW_RESELLERS = "hosting.view_reseller"
|
|
VIEW_CUSTOMERS = "hosting.view_customer"
|
|
VIEW_DATABASES = "hosting.view_hostingdatabase"
|
|
VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
|
|
VIEW_MAILBOXES = "hosting.view_hostingmailbox"
|
|
|
|
|
|
class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
|
|
queryset = HostingAccount.objects.select_related("hosting_plan").order_by(
|
|
"primary_domain"
|
|
)
|
|
permission_required = VIEW_ACCOUNTS
|
|
template_name = "hosting/account_list.html"
|
|
context_object_name = "accounts"
|
|
paginate_by = 20
|
|
customer_relation = "customer"
|
|
|
|
def get_queryset(self):
|
|
self.search = self.request.GET.get("q", "").strip()[:253]
|
|
accounts = super().get_queryset()
|
|
if self.search:
|
|
accounts = accounts.filter(
|
|
Q(name__icontains=self.search)
|
|
| Q(primary_domain__icontains=self.search)
|
|
)
|
|
return accounts
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super().get_context_data(search=self.search, **kwargs)
|
|
reseller = reseller_for_user(self.request.user)
|
|
if reseller is not None and reseller.may_create_accounts():
|
|
context["account_allowance"] = {
|
|
"used": reseller.hostingaccount_set.count(),
|
|
"limit": reseller.account_limit,
|
|
}
|
|
return context
|
|
|
|
|
|
class AccountEditor:
|
|
model = HostingAccount
|
|
template_name = "hosting/account_form.html"
|
|
|
|
def get_form_class(self):
|
|
self.fields = ("name", "primary_domain")
|
|
reseller = reseller_for_user(self.request.user)
|
|
if reseller is not None or self.request.user.has_perm(VIEW_HOSTING_PLANS):
|
|
self.fields += ("hosting_plan",)
|
|
if reseller is None and self.request.user.has_perm(VIEW_RESELLERS):
|
|
self.fields += ("reseller",)
|
|
if reseller is None and self.request.user.has_perm(VIEW_CUSTOMERS):
|
|
self.fields += ("customer",)
|
|
return super().get_form_class()
|
|
|
|
def get_form(self, form_class=None):
|
|
form = super().get_form(form_class)
|
|
if "hosting_plan" in form.fields:
|
|
field = form.fields["hosting_plan"]
|
|
reseller = reseller_for_user(self.request.user)
|
|
if reseller is None:
|
|
field.empty_label = "Unassigned"
|
|
else:
|
|
field.queryset = reseller.hosting_plans.all()
|
|
field.required = True
|
|
field.empty_label = "Select a hosting plan"
|
|
for name in ("reseller", "customer"):
|
|
if name in form.fields:
|
|
field = form.fields[name]
|
|
field.empty_label = "Unassigned"
|
|
field.queryset = field.queryset.select_related("user").order_by(
|
|
"user__username"
|
|
)
|
|
return form
|
|
|
|
|
|
class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
|
|
permission_required = (VIEW_ACCOUNTS, "hosting.add_hostingaccount")
|
|
extra_context = {"page_title": "Add hosting account", "submit_label": "Add account"}
|
|
|
|
def has_permission(self):
|
|
if customer_for_user(self.request.user) is not None:
|
|
return False
|
|
reseller = reseller_for_user(self.request.user)
|
|
if reseller is not None:
|
|
return reseller.may_create_accounts()
|
|
return super().has_permission()
|
|
|
|
def form_valid(self, form):
|
|
reseller = reseller_for_user(self.request.user)
|
|
if reseller is None:
|
|
return super().form_valid(form)
|
|
|
|
self.object = form.save(commit=False)
|
|
try:
|
|
create_reseller_account(reseller, self.object)
|
|
except ValidationError as error:
|
|
form.add_error(None, error)
|
|
return self.form_invalid(form)
|
|
except IntegrityError:
|
|
if not HostingAccount.objects.filter(
|
|
primary_domain=self.object.primary_domain
|
|
).exists():
|
|
raise
|
|
form.add_error("primary_domain", "This domain is unavailable.")
|
|
return self.form_invalid(form)
|
|
return redirect(self.object)
|
|
|
|
|
|
class AccountEdit(
|
|
OperatorOnlyMixin, PermissionRequiredMixin, AccountEditor, UpdateView
|
|
):
|
|
permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS)
|
|
context_object_name = "account"
|
|
extra_context = {
|
|
"page_title": "Edit hosting account",
|
|
"submit_label": "Save changes",
|
|
}
|
|
|
|
def form_valid(self, form):
|
|
self.object = form.save(commit=False)
|
|
self.object.save(update_fields=form.changed_data)
|
|
return redirect(self.object)
|
|
|
|
|
|
class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|
queryset = HostingAccount.objects.select_related(
|
|
"hosting_plan", "reseller__user", "customer__user"
|
|
)
|
|
permission_required = VIEW_ACCOUNTS
|
|
template_name = "hosting/account_detail.html"
|
|
context_object_name = "account"
|
|
customer_relation = "customer"
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super().get_context_data(**kwargs)
|
|
user = self.request.user
|
|
reseller = reseller_for_user(user)
|
|
customer = customer_for_user(user)
|
|
tenant = reseller is not None or customer is not None
|
|
if reseller is not None or (customer is None and user.has_perm(VIEW_PLANS)):
|
|
context["plans"] = self.object.webprovisioningplan_set.order_by(
|
|
"-requested_at", "-pk"
|
|
)[:10]
|
|
if tenant or user.has_perm(VIEW_DATABASES):
|
|
context["databases"] = self.object.databases.all()
|
|
if tenant 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
|
|
)
|
|
if tenant or user.has_perm(VIEW_MAILBOXES):
|
|
context["mailboxes"] = HostingMailbox.objects.filter(
|
|
mail_domain__account=self.object
|
|
).select_related("mail_domain")
|
|
return context
|
|
|
|
|
|
class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView):
|
|
model = HostingDatabase
|
|
fields = ("suffix",)
|
|
template_name = "hosting/database_form.html"
|
|
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase")
|
|
|
|
@cached_property
|
|
def account(self):
|
|
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
|
|
|
|
def get_context_data(self, **kwargs):
|
|
return super().get_context_data(account=self.account, **kwargs)
|
|
|
|
def form_valid(self, form):
|
|
self.object = form.save(commit=False)
|
|
self.object.account = self.account
|
|
try:
|
|
with transaction.atomic():
|
|
self.object.save()
|
|
except IntegrityError:
|
|
if not self.account.databases.filter(suffix=self.object.suffix).exists():
|
|
raise
|
|
form.add_error(
|
|
"suffix", "This account already has a database with that suffix."
|
|
)
|
|
return self.form_invalid(form)
|
|
return redirect(self.account)
|
|
|
|
|
|
class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES)
|
|
|
|
def get(self, request, pk):
|
|
database = get_object_or_404(HostingDatabase, pk=pk)
|
|
return JsonResponse(
|
|
database.spec.manifest(),
|
|
headers={
|
|
"Cache-Control": "private, no-store",
|
|
"Content-Disposition": f'attachment; filename="coulobre-database-{database.pk}.json"',
|
|
},
|
|
)
|
|
|
|
|
|
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
|
|
),
|
|
"mx_records": "\n".join(
|
|
f"{record['name']} {record['priority']} {record['exchange']}"
|
|
for record in self.zone.mx_records
|
|
),
|
|
"txt_records": "\n".join(
|
|
format_txt_record(record) for record in self.zone.txt_records
|
|
),
|
|
}
|
|
|
|
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 MailboxCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView):
|
|
model = HostingMailbox
|
|
fields = ("local_part",)
|
|
template_name = "hosting/mailbox_form.html"
|
|
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox")
|
|
|
|
@cached_property
|
|
def account(self):
|
|
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
|
|
|
|
def get_form(self, form_class=None):
|
|
form = super().get_form(form_class)
|
|
form.fields["local_part"].help_text = INVALID_LOCAL_PART
|
|
return form
|
|
|
|
def get_context_data(self, **kwargs):
|
|
return super().get_context_data(account=self.account, **kwargs)
|
|
|
|
def form_valid(self, form):
|
|
try:
|
|
spec = MailboxSpec(
|
|
self.account.primary_domain, form.cleaned_data["local_part"]
|
|
)
|
|
except ValueError as error:
|
|
form.add_error("local_part", str(error))
|
|
return self.form_invalid(form)
|
|
|
|
with transaction.atomic():
|
|
mail_domain, _ = HostingMailDomain.objects.get_or_create(
|
|
domain=spec.domain, defaults={"account": self.account}
|
|
)
|
|
if mail_domain.account_id != self.account.pk:
|
|
form.add_error(
|
|
None, "This mail domain belongs to another hosting account."
|
|
)
|
|
return self.form_invalid(form)
|
|
self.object, created = HostingMailbox.objects.get_or_create(
|
|
mail_domain=mail_domain, local_part=spec.local_part
|
|
)
|
|
if not created:
|
|
form.add_error("local_part", "This mailbox has already been requested.")
|
|
return self.form_invalid(form)
|
|
return redirect(self.account)
|
|
|
|
|
|
class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES)
|
|
|
|
def get(self, request, pk):
|
|
mailbox = get_object_or_404(
|
|
HostingMailbox.objects.select_related("mail_domain"), pk=pk
|
|
)
|
|
return JsonResponse(
|
|
mailbox.spec.manifest(),
|
|
headers={
|
|
"Cache-Control": "private, no-store",
|
|
"Content-Disposition": f'attachment; filename="coulobre-mailbox-{mailbox.pk}.json"',
|
|
},
|
|
)
|
|
|
|
|
|
class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
|
|
model = HostingPlan
|
|
permission_required = VIEW_HOSTING_PLANS
|
|
template_name = "hosting/hosting_plan_list.html"
|
|
context_object_name = "hosting_plans"
|
|
paginate_by = 20
|
|
|
|
|
|
class HostingPlanEditor:
|
|
model = HostingPlan
|
|
fields = ("name", "description")
|
|
template_name = "hosting/hosting_plan_form.html"
|
|
success_url = reverse_lazy("panel:hosting_plans")
|
|
|
|
|
|
class HostingPlanCreate(
|
|
OperatorOnlyMixin, PermissionRequiredMixin, HostingPlanEditor, CreateView
|
|
):
|
|
permission_required = (VIEW_HOSTING_PLANS, "hosting.add_hostingplan")
|
|
extra_context = {"page_title": "Add hosting plan", "submit_label": "Add plan"}
|
|
|
|
|
|
class HostingPlanEdit(
|
|
OperatorOnlyMixin, PermissionRequiredMixin, HostingPlanEditor, UpdateView
|
|
):
|
|
permission_required = (VIEW_HOSTING_PLANS, "hosting.change_hostingplan")
|
|
extra_context = {"page_title": "Edit hosting plan", "submit_label": "Save changes"}
|
|
|
|
|
|
class RequestWebPlan(
|
|
OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View
|
|
):
|
|
model = HostingAccount
|
|
permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS, VIEW_PLANS)
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
plan = WebProvisioningPlan.for_account(self.get_object())
|
|
plan.save()
|
|
return redirect("panel:plan", pk=plan.pk)
|
|
|
|
|
|
class PlanList(TenantScopeMixin, PermissionRequiredMixin, ListView):
|
|
queryset = WebProvisioningPlan.objects.select_related("account").order_by(
|
|
"-requested_at", "-pk"
|
|
)
|
|
permission_required = VIEW_PLANS
|
|
reseller_relation = "account__reseller"
|
|
template_name = "hosting/plan_list.html"
|
|
context_object_name = "plans"
|
|
paginate_by = 20
|
|
|
|
|
|
class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|
queryset = WebProvisioningPlan.objects.select_related("account")
|
|
permission_required = VIEW_PLANS
|
|
reseller_relation = "account__reseller"
|
|
template_name = "hosting/plan_detail.html"
|
|
context_object_name = "plan"
|
|
|
|
|
|
class DownloadWebPlan(OperatorOnlyMixin, PlanDetail):
|
|
manifest = False
|
|
|
|
def render_to_response(self, context, **response_kwargs):
|
|
plan = self.object
|
|
if not plan.can_export:
|
|
return HttpResponse(
|
|
"Request a completed Apache preview for the current account domain.",
|
|
status=409,
|
|
content_type="text/plain",
|
|
)
|
|
|
|
if self.manifest:
|
|
content = serialize_deployment_manifest(plan)
|
|
extension = "json"
|
|
content_type = "application/json"
|
|
else:
|
|
content = build_web_smoke_bundle(plan)
|
|
extension = "tar"
|
|
content_type = "application/x-tar"
|
|
return HttpResponse(
|
|
content,
|
|
content_type=content_type,
|
|
headers={
|
|
"Cache-Control": "private, no-store",
|
|
"Content-Disposition": (
|
|
f'attachment; filename="coulobre-web-plan-{plan.pk}.{extension}"'
|
|
),
|
|
},
|
|
)
|