541 lines
18 KiB
Python
541 lines
18 KiB
Python
from email.utils import parseaddr
|
|
from importlib.metadata import PackageNotFoundError, version
|
|
from pathlib import Path
|
|
|
|
from django import forms
|
|
from django.conf import settings
|
|
from django.contrib import messages
|
|
from django.contrib.admin.models import CHANGE, LogEntry
|
|
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
|
|
from django.db import transaction
|
|
from django.db.models import F
|
|
from django.http import Http404
|
|
from django.shortcuts import redirect
|
|
from django.urls import reverse, reverse_lazy
|
|
from django.utils.decorators import method_decorator
|
|
from django.views.decorators.cache import never_cache
|
|
from django.views.generic import FormView, TemplateView
|
|
|
|
from coulobre.local_feature_setup import LOCAL_FEATURES, PACKAGE_ASSETS
|
|
from coulobre.operator_node import SOCKET, OperatorRequest
|
|
from coulobre.tool_setup_request import (
|
|
HOSTING_TOOLS,
|
|
TOOL_SETUP_ACTION,
|
|
ToolSetupRequest,
|
|
)
|
|
|
|
from .access import is_tenant
|
|
from .installation_features import FEATURES, FeaturePolicy
|
|
from .models import (
|
|
InvitationMailSettings,
|
|
OperatorOperation,
|
|
PanelFeaturePolicy,
|
|
WebsiteDomain,
|
|
)
|
|
from .offsite_destinations import offsite_destinations
|
|
from .operator_tools import package_operation_pending, queue_operator_request
|
|
from .update_views import inspect_linked_nodes
|
|
|
|
TOOL_FEATURES = {
|
|
"phpmyadmin": (
|
|
"database",
|
|
"PHPMYADMIN_URL",
|
|
"LOCAL_DATABASE_PROVISIONING",
|
|
),
|
|
"roundcube": ("email", "ROUNDCUBE_URL", "MAILBOX_PASSWORD_CHANGES"),
|
|
"offsite": (
|
|
"backups",
|
|
"OFFSITE_BACKUP_DESTINATIONS",
|
|
"LOCAL_ACCOUNT_BACKUPS",
|
|
),
|
|
}
|
|
TOOL_SETTINGS = {
|
|
setting: tool for tool, (_, setting, _) in TOOL_FEATURES.items()
|
|
}
|
|
|
|
|
|
def managed_tool_available(tool):
|
|
_, setting, prerequisite = TOOL_FEATURES[tool]
|
|
configured = (
|
|
offsite_destinations()
|
|
if tool == "offsite"
|
|
else getattr(settings, setting)
|
|
)
|
|
return (
|
|
Path(SOCKET).is_socket()
|
|
and PACKAGE_ASSETS.is_dir()
|
|
and not configured
|
|
and getattr(settings, prerequisite)
|
|
)
|
|
|
|
|
|
@method_decorator(never_cache, name="dispatch")
|
|
class InstallationView(LoginRequiredMixin, TemplateView):
|
|
template_name = "hosting/installation.html"
|
|
|
|
def get_context_data(self, **kwargs):
|
|
try:
|
|
installed_version = version("coulobre-panel")
|
|
except PackageNotFoundError:
|
|
installed_version = "Unavailable"
|
|
policy = FeaturePolicy()
|
|
features = []
|
|
may_view = not is_tenant(
|
|
self.request.user
|
|
) and self.request.user.has_perm("hosting.view_servicehealth")
|
|
for feature in FEATURES if may_view else ():
|
|
configured = feature.configured
|
|
enabled = (
|
|
configured
|
|
and feature.setting not in policy.disabled
|
|
and (
|
|
feature.setting != "DEFAULT_DNS_ZONES"
|
|
or "LOCAL_DNS_PUBLISHING" not in policy.disabled
|
|
)
|
|
)
|
|
features.append((feature, configured, enabled))
|
|
return super().get_context_data(
|
|
installed_version=installed_version, features=features, **kwargs
|
|
)
|
|
|
|
|
|
OPERATOR_FEATURE_SECTIONS = {
|
|
"general": ("General", ()),
|
|
"server": (
|
|
"Server",
|
|
(
|
|
"LOCAL_WEB_ACTIVATION",
|
|
"WEB_FILE_MANAGER",
|
|
"WEBSITE_JOBS",
|
|
"LOCAL_WEB_SFTP",
|
|
"LOCAL_FOLDER_SFTP",
|
|
"LOCAL_DNS_PUBLISHING",
|
|
"DEFAULT_DNS_ZONES",
|
|
),
|
|
),
|
|
"security": ("Security", ("LOCAL_WEB_HTTPS",)),
|
|
"email": (
|
|
"Email",
|
|
(
|
|
"LOCAL_MAILBOX_PROVISIONING",
|
|
"MAILBOX_PASSWORD_CHANGES",
|
|
"MANAGE_MAIL_DNS",
|
|
"ROUNDCUBE_URL",
|
|
),
|
|
),
|
|
"database": (
|
|
"Database",
|
|
("LOCAL_DATABASE_PROVISIONING", "PHPMYADMIN_URL"),
|
|
),
|
|
"backups": (
|
|
"Backups",
|
|
("LOCAL_ACCOUNT_BACKUPS", "OFFSITE_BACKUP_DESTINATIONS"),
|
|
),
|
|
}
|
|
|
|
|
|
class FeatureConfigurationForm(forms.Form):
|
|
revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput)
|
|
|
|
def __init__(self, *args, policy, section=None, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.initial["revision"] = policy.saved.revision
|
|
features = [
|
|
feature
|
|
for feature in FEATURES
|
|
if (section is None or feature.setting in section)
|
|
]
|
|
self.configured_features = []
|
|
self.features_requiring_setup = []
|
|
for feature in features:
|
|
if feature.configured:
|
|
self.configured_features.append(feature)
|
|
else:
|
|
self.features_requiring_setup.append(feature)
|
|
for feature in self.configured_features:
|
|
self.fields[feature.setting] = forms.BooleanField(
|
|
required=False,
|
|
label=feature.label,
|
|
help_text=feature.prerequisite,
|
|
initial=feature.setting not in policy.disabled,
|
|
)
|
|
|
|
def changed_features(self):
|
|
return [
|
|
feature
|
|
for feature in self.configured_features
|
|
if feature.setting in self.changed_data
|
|
]
|
|
|
|
|
|
def check_features(form, changed):
|
|
new_enabled = [
|
|
feature for feature in changed if form.cleaned_data[feature.setting]
|
|
]
|
|
nodes = {}
|
|
if any(feature.linked for feature in new_enabled):
|
|
topology = inspect_linked_nodes()
|
|
nodes = {node["role"]: node for node in topology.get("nodes", [])}
|
|
for feature in new_enabled:
|
|
if not feature.socket_ready:
|
|
form.add_error(
|
|
feature.setting,
|
|
"Start the configured service before enabling this feature.",
|
|
)
|
|
elif feature.linked:
|
|
report = nodes.get(feature.role, {})
|
|
if report.get("state") != "configured" or report.get(
|
|
"release"
|
|
) != version("coulobre-panel"):
|
|
form.add_error(
|
|
feature.setting,
|
|
"The linked receiver must be ready and on the same "
|
|
"release.",
|
|
)
|
|
if (
|
|
feature.setting == "DEFAULT_DNS_ZONES"
|
|
and not form.cleaned_data.get(
|
|
"LOCAL_DNS_PUBLISHING",
|
|
settings.LOCAL_DNS_PUBLISHING
|
|
and "LOCAL_DNS_PUBLISHING" not in FeaturePolicy().disabled,
|
|
)
|
|
):
|
|
form.add_error(feature.setting, "Enable DNS publishing first.")
|
|
|
|
|
|
@method_decorator(never_cache, name="dispatch")
|
|
class FeatureConfigurationView(UserPassesTestMixin, FormView):
|
|
form_class = FeatureConfigurationForm
|
|
template_name = "hosting/feature_configuration.html"
|
|
success_url = reverse_lazy("panel:installation")
|
|
|
|
def test_func(self):
|
|
return (
|
|
self.request.user.is_superuser and self.request.user.is_verified()
|
|
)
|
|
|
|
def get_form_kwargs(self):
|
|
section = self.kwargs.get("section")
|
|
if section is not None and section not in OPERATOR_FEATURE_SECTIONS:
|
|
raise Http404
|
|
return super().get_form_kwargs() | {
|
|
"policy": FeaturePolicy(),
|
|
"section": (
|
|
OPERATOR_FEATURE_SECTIONS[section][1]
|
|
if section is not None
|
|
else None
|
|
),
|
|
}
|
|
|
|
def get_context_data(self, **kwargs):
|
|
section = self.kwargs.get("section")
|
|
form = kwargs.pop("form", None) or self.get_form()
|
|
targets = self.setup_targets(form)
|
|
section_settings = (
|
|
OPERATOR_FEATURE_SECTIONS[section][1] if section else None
|
|
)
|
|
jobs = OperatorOperation.objects.filter(
|
|
action="feature-enable",
|
|
target__in=[
|
|
key
|
|
for key, feature in LOCAL_FEATURES.items()
|
|
if section_settings is None
|
|
or feature.setting in section_settings
|
|
],
|
|
).order_by("-pk")
|
|
latest = {}
|
|
for job in jobs[:20]:
|
|
latest.setdefault(job.target, job)
|
|
setup = []
|
|
for feature in form.features_requiring_setup:
|
|
target = targets.get(feature.setting)
|
|
job = latest.get(target)
|
|
tool = TOOL_SETTINGS.get(feature.setting)
|
|
setup.append(
|
|
(
|
|
feature,
|
|
target,
|
|
package_operation_pending(job),
|
|
tool if tool and managed_tool_available(tool) else None,
|
|
)
|
|
)
|
|
labels = {feature.setting: feature.label for feature in FEATURES}
|
|
return super().get_context_data(
|
|
selected_section=section,
|
|
form=form,
|
|
setup_features=setup,
|
|
setup_jobs=[
|
|
(
|
|
job,
|
|
labels[LOCAL_FEATURES[job.target].setting],
|
|
package_operation_pending(job),
|
|
)
|
|
for job in jobs[:5]
|
|
],
|
|
settings_tabs=tuple(
|
|
(key, label)
|
|
for key, (label, _) in OPERATOR_FEATURE_SECTIONS.items()
|
|
)
|
|
if section
|
|
else (),
|
|
**kwargs,
|
|
)
|
|
|
|
def setup_targets(self, form):
|
|
if not (Path(SOCKET).is_socket() and PACKAGE_ASSETS.is_dir()):
|
|
return {}
|
|
settings_needing_setup = {
|
|
feature.setting for feature in form.features_requiring_setup
|
|
}
|
|
return {
|
|
feature.setting: key
|
|
for key, feature in LOCAL_FEATURES.items()
|
|
if feature.setting in settings_needing_setup
|
|
and (
|
|
settings.LOCAL_MAILBOX_PROVISIONING
|
|
if key == "mailbox-passwords"
|
|
else settings.LOCAL_WEB_ACTIVATION
|
|
)
|
|
and (
|
|
key != "account-backups"
|
|
or settings.LOCAL_DATABASE_PROVISIONING
|
|
)
|
|
and (key != "folder-sftp" or settings.LOCAL_WEB_SFTP)
|
|
}
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
if "setup_feature" not in request.POST:
|
|
return super().post(request, *args, **kwargs)
|
|
target = request.POST["setup_feature"]
|
|
if target not in self.setup_targets(self.get_form()).values():
|
|
raise Http404
|
|
with transaction.atomic():
|
|
PanelFeaturePolicy.objects.get_or_create(pk=1)
|
|
PanelFeaturePolicy.objects.select_for_update().get(pk=1)
|
|
previous = (
|
|
OperatorOperation.objects.filter(
|
|
action__in=("feature-enable", TOOL_SETUP_ACTION)
|
|
)
|
|
.order_by("-pk")
|
|
.first()
|
|
)
|
|
if package_operation_pending(previous):
|
|
messages.error(request, "Wait for the current feature setup.")
|
|
else:
|
|
queue_operator_request(
|
|
request.user,
|
|
OperatorRequest("feature-enable", target),
|
|
retryable=True,
|
|
)
|
|
messages.success(request, "Feature setup queued.")
|
|
return redirect(request.path)
|
|
|
|
def get_success_url(self):
|
|
if "section" in self.kwargs:
|
|
return reverse("panel:operator_settings", kwargs=self.kwargs)
|
|
return super().get_success_url()
|
|
|
|
def form_valid(self, form):
|
|
revision = form.cleaned_data["revision"]
|
|
policy = FeaturePolicy()
|
|
if revision != policy.saved.revision:
|
|
return self.stale_form(form)
|
|
changed = form.changed_features()
|
|
if not changed:
|
|
return super().form_valid(form)
|
|
check_features(form, changed)
|
|
if form.errors:
|
|
return self.form_invalid(form)
|
|
disabled = set(policy.disabled)
|
|
for feature in changed:
|
|
if form.cleaned_data[feature.setting]:
|
|
disabled.discard(feature.setting)
|
|
else:
|
|
disabled.add(feature.setting)
|
|
with transaction.atomic():
|
|
saved, _ = PanelFeaturePolicy.objects.get_or_create(pk=1)
|
|
updated = PanelFeaturePolicy.objects.filter(
|
|
pk=1, revision=revision
|
|
).update(disabled=sorted(disabled), revision=F("revision") + 1)
|
|
if not updated:
|
|
return self.stale_form(form)
|
|
LogEntry.objects.log_actions(
|
|
self.request.user.pk,
|
|
[saved],
|
|
CHANGE,
|
|
[
|
|
{
|
|
"changed": {
|
|
"fields": [feature.label for feature in changed]
|
|
}
|
|
}
|
|
],
|
|
)
|
|
messages.success(self.request, "Feature configuration saved.")
|
|
return super().form_valid(form)
|
|
|
|
def stale_form(self, form):
|
|
form.add_error(
|
|
None, "The configuration changed. Reopen this page and try again."
|
|
)
|
|
return self.render_to_response(
|
|
self.get_context_data(form=form), status=409
|
|
)
|
|
|
|
|
|
class ManagedToolForm(forms.Form):
|
|
endpoint = forms.CharField(max_length=253, label="HTTPS hostname")
|
|
|
|
def __init__(self, *args, tool, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.tool = tool
|
|
if tool == "offsite":
|
|
self.fields["endpoint"] = forms.CharField(
|
|
max_length=48, label="Destination ID"
|
|
)
|
|
|
|
def clean_endpoint(self):
|
|
try:
|
|
spec = ToolSetupRequest(self.tool, self.cleaned_data["endpoint"])
|
|
except ValueError as error:
|
|
raise forms.ValidationError(str(error)) from error
|
|
if self.tool == "offsite":
|
|
return spec.endpoint
|
|
if (
|
|
f"https://{spec.endpoint}" == settings.PASSWORD_RESET_ORIGIN
|
|
or WebsiteDomain.objects.filter(domain=spec.endpoint).exists()
|
|
):
|
|
raise forms.ValidationError("Use a separate, unused hostname.")
|
|
return spec.endpoint
|
|
|
|
|
|
@method_decorator(never_cache, name="dispatch")
|
|
class ManagedToolSetupView(UserPassesTestMixin, FormView):
|
|
form_class = ManagedToolForm
|
|
template_name = "hosting/managed_tool_setup.html"
|
|
|
|
def test_func(self):
|
|
return (
|
|
self.request.user.is_superuser and self.request.user.is_verified()
|
|
)
|
|
|
|
@property
|
|
def tool(self):
|
|
tool = self.kwargs["tool"]
|
|
if tool not in HOSTING_TOOLS:
|
|
raise Http404
|
|
return tool
|
|
|
|
def get_form_kwargs(self):
|
|
return super().get_form_kwargs() | {"tool": self.tool}
|
|
|
|
def get_context_data(self, **kwargs):
|
|
job = (
|
|
OperatorOperation.objects.filter(
|
|
action=TOOL_SETUP_ACTION, target=self.tool
|
|
)
|
|
.order_by("-pk")
|
|
.first()
|
|
)
|
|
return super().get_context_data(
|
|
tool_label=HOSTING_TOOLS[self.tool],
|
|
tool=self.tool,
|
|
section=TOOL_FEATURES[self.tool][0],
|
|
available=managed_tool_available(self.tool),
|
|
pending=package_operation_pending(job),
|
|
job=job,
|
|
**kwargs,
|
|
)
|
|
|
|
def get_success_url(self):
|
|
return self.request.path
|
|
|
|
@transaction.atomic
|
|
def form_valid(self, form):
|
|
PanelFeaturePolicy.objects.get_or_create(pk=1)
|
|
PanelFeaturePolicy.objects.select_for_update().get(pk=1)
|
|
if not managed_tool_available(self.tool):
|
|
form.add_error(
|
|
None, "This installation cannot queue this tool now."
|
|
)
|
|
return self.form_invalid(form)
|
|
previous = (
|
|
OperatorOperation.objects.filter(
|
|
action__in=(TOOL_SETUP_ACTION, "feature-enable")
|
|
)
|
|
.order_by("-pk")
|
|
.first()
|
|
)
|
|
if package_operation_pending(previous):
|
|
form.add_error(
|
|
None, "Wait for the current feature setup to finish."
|
|
)
|
|
return self.form_invalid(form)
|
|
spec = ToolSetupRequest(self.tool, form.cleaned_data["endpoint"])
|
|
queue_operator_request(
|
|
self.request.user,
|
|
spec,
|
|
retryable=True,
|
|
parameters={"endpoint": spec.endpoint},
|
|
)
|
|
messages.success(
|
|
self.request, f"{HOSTING_TOOLS[self.tool]} setup queued."
|
|
)
|
|
return super().form_valid(form)
|
|
|
|
|
|
class InvitationMailSettingsForm(forms.ModelForm):
|
|
class Meta:
|
|
model = InvitationMailSettings
|
|
fields = ("sender_name", "sender_address", "reply_to")
|
|
labels = {
|
|
"sender_name": "Sender display name",
|
|
"sender_address": "From address",
|
|
"reply_to": "Reply-to address",
|
|
}
|
|
help_texts = {
|
|
"sender_name": "Leave blank to use the installed sender name.",
|
|
"sender_address": "Use an address your SMTP server allows.",
|
|
"reply_to": "Leave blank to receive replies at the From address.",
|
|
}
|
|
|
|
|
|
@method_decorator(never_cache, name="dispatch")
|
|
class InvitationMailSettingsView(UserPassesTestMixin, FormView):
|
|
form_class = InvitationMailSettingsForm
|
|
template_name = "hosting/invitation_mail_settings.html"
|
|
success_url = reverse_lazy("panel:invitation_mail_settings")
|
|
|
|
def test_func(self):
|
|
return (
|
|
self.request.user.is_superuser and self.request.user.is_verified()
|
|
)
|
|
|
|
def get_form_kwargs(self):
|
|
return super().get_form_kwargs() | {
|
|
"instance": InvitationMailSettings.objects.filter(pk=1).first(),
|
|
}
|
|
|
|
def get_context_data(self, **kwargs):
|
|
from .panel_mail import default_sender
|
|
|
|
_, installed_address = parseaddr(default_sender())
|
|
return super().get_context_data(
|
|
installed_address=installed_address, **kwargs
|
|
)
|
|
|
|
@transaction.atomic
|
|
def form_valid(self, form):
|
|
saved, _ = InvitationMailSettings.objects.update_or_create(
|
|
pk=1, defaults=form.cleaned_data
|
|
)
|
|
if form.has_changed():
|
|
LogEntry.objects.log_actions(
|
|
self.request.user.pk,
|
|
[saved],
|
|
CHANGE,
|
|
"Updated welcome email sender.",
|
|
)
|
|
messages.success(self.request, "Welcome email sender saved.")
|
|
return super().form_valid(form)
|