419 lines
14 KiB
Python
419 lines
14 KiB
Python
import uuid
|
|
from datetime import timedelta
|
|
from email.mime.image import MIMEImage
|
|
from email.mime.multipart import MIMEMultipart
|
|
from email.utils import parseaddr
|
|
from pathlib import Path
|
|
|
|
from django import forms
|
|
from django.conf import settings
|
|
from django.contrib.auth import get_user_model
|
|
from django.contrib.auth.forms import UsernameField
|
|
from django.contrib.auth.mixins import AccessMixin
|
|
from django.contrib.auth.views import (
|
|
INTERNAL_RESET_SESSION_TOKEN,
|
|
PasswordResetConfirmView,
|
|
)
|
|
from django.core.mail import EmailMultiAlternatives
|
|
from django.core.mail.message import sanitize_address
|
|
from django.core.signing import BadSignature, Signer
|
|
from django.db import transaction
|
|
from django.shortcuts import get_object_or_404, redirect
|
|
from django.template.loader import render_to_string
|
|
from django.urls import reverse, reverse_lazy
|
|
from django.utils import timezone
|
|
from django.utils.decorators import method_decorator
|
|
from django.utils.encoding import force_bytes
|
|
from django.utils.http import urlsafe_base64_encode
|
|
from django.views.decorators.cache import never_cache
|
|
from django.views.decorators.debug import sensitive_variables
|
|
from django.views.generic import FormView
|
|
from kombu.exceptions import OperationalError
|
|
|
|
from .access import customer_for_user, is_tenant, reseller_for_user
|
|
from .account_setup import website_records
|
|
from .mail_dns_setup import mail_client_alias
|
|
from .models import (
|
|
Customer,
|
|
HostingAccount,
|
|
InvitationMailSettings,
|
|
PanelInvitation,
|
|
Reseller,
|
|
)
|
|
from .panel_factors import lock_user
|
|
from .panel_mail import default_sender
|
|
from .password_reset import reset_enabled
|
|
|
|
INVITATION_AGE = timedelta(hours=48)
|
|
|
|
|
|
class InviteLoginForm(forms.ModelForm):
|
|
email = forms.EmailField(
|
|
help_text="Use an address the recipient can already access."
|
|
)
|
|
|
|
class Meta:
|
|
model = get_user_model()
|
|
fields = ("username", "email")
|
|
field_classes = {"username": UsernameField}
|
|
|
|
def clean_username(self):
|
|
username = self.cleaned_data["username"]
|
|
if self.Meta.model.objects.filter(username__iexact=username).exists():
|
|
raise forms.ValidationError(
|
|
self.instance.unique_error_message(
|
|
self.Meta.model, ["username"]
|
|
)
|
|
)
|
|
return username
|
|
|
|
def save(self, commit=True):
|
|
user = super().save(commit=False)
|
|
user.set_unusable_password()
|
|
if commit:
|
|
user.save()
|
|
return user
|
|
|
|
|
|
def may_accept_invitation(user):
|
|
return (
|
|
user.is_active
|
|
and bool(user.email)
|
|
and not user.is_staff
|
|
and not user.is_superuser
|
|
and not user.has_usable_password()
|
|
and (customer_for_user(user) or reseller_for_user(user))
|
|
)
|
|
|
|
|
|
class InvitationToken:
|
|
@staticmethod
|
|
def payload(user):
|
|
revision = user.panel_invitation.revision
|
|
return f"{user.pk}:{revision}:{user.password}:{user.email}"
|
|
|
|
def make_token(self, user):
|
|
return Signer(salt="coulobre.panel-invitation").signature(
|
|
self.payload(user)
|
|
)
|
|
|
|
def check_token(self, user, token):
|
|
if user is None or not token or not may_accept_invitation(user):
|
|
return False
|
|
invitation = getattr(user, "panel_invitation", None)
|
|
if (
|
|
invitation is None
|
|
or invitation.created_at + INVITATION_AGE <= timezone.now()
|
|
):
|
|
return False
|
|
signer = Signer(salt="coulobre.panel-invitation")
|
|
payload = self.payload(user)
|
|
try:
|
|
return signer.unsign(payload + signer.sep + token) == payload
|
|
except BadSignature:
|
|
return False
|
|
|
|
|
|
invitation_token = InvitationToken()
|
|
|
|
|
|
@transaction.atomic
|
|
def queue_invitation(user, *, welcome_message=None):
|
|
user = lock_user(user.pk)
|
|
if not may_accept_invitation(user):
|
|
return None
|
|
invitation, _ = PanelInvitation.objects.update_or_create(
|
|
user=user,
|
|
defaults={
|
|
"revision": uuid.uuid4(),
|
|
"created_at": timezone.now(),
|
|
"delivery": PanelInvitation.Delivery.PENDING,
|
|
**(
|
|
{"welcome_message": welcome_message}
|
|
if welcome_message is not None
|
|
else {}
|
|
),
|
|
},
|
|
)
|
|
if not reset_enabled():
|
|
invitation.delivery = PanelInvitation.Delivery.UNAVAILABLE
|
|
invitation.save(update_fields=["delivery"])
|
|
else:
|
|
transaction.on_commit(
|
|
lambda: enqueue_delivery(invitation.pk, invitation.revision)
|
|
)
|
|
return invitation
|
|
|
|
|
|
def enqueue_delivery(invitation_id, revision):
|
|
from .tasks import send_panel_invitation
|
|
|
|
try:
|
|
send_panel_invitation.apply_async(
|
|
args=[invitation_id, str(revision)], retry=False
|
|
)
|
|
except OperationalError:
|
|
PanelInvitation.objects.filter(
|
|
pk=invitation_id, revision=revision
|
|
).update(delivery=PanelInvitation.Delivery.FAILED)
|
|
|
|
|
|
@sensitive_variables("path", "context")
|
|
def deliver_invitation(invitation_id, revision):
|
|
pending = PanelInvitation.objects.filter(
|
|
pk=invitation_id,
|
|
revision=revision,
|
|
delivery=PanelInvitation.Delivery.PENDING,
|
|
)
|
|
invitation = pending.select_related("user").first()
|
|
if invitation is None or not reset_enabled():
|
|
return
|
|
user = invitation.user
|
|
user.panel_invitation = invitation
|
|
if not may_accept_invitation(user):
|
|
return
|
|
|
|
origin = settings.PASSWORD_RESET_ORIGIN.rstrip("/")
|
|
path = reverse(
|
|
"panel:accept_invitation",
|
|
kwargs={
|
|
"uidb64": urlsafe_base64_encode(force_bytes(user.pk)),
|
|
"token": invitation_token.make_token(user),
|
|
},
|
|
)
|
|
context = invitation_message_context(user, setup_url=origin + path)
|
|
try:
|
|
sent = invitation_email(user.email, context).send()
|
|
if sent != 1:
|
|
raise OSError("The email backend did not accept the invitation.")
|
|
except (OSError, ValueError):
|
|
pending.update(delivery=PanelInvitation.Delivery.FAILED)
|
|
else:
|
|
pending.update(delivery=PanelInvitation.Delivery.SENT)
|
|
|
|
|
|
class InvitationEmail(EmailMultiAlternatives):
|
|
def message(self):
|
|
message = super().message()
|
|
plain, html = message.get_payload()
|
|
logo_file = (
|
|
Path(__file__).parent / "static/hosting/coulobre-mail-mark.png"
|
|
)
|
|
logo = MIMEImage(logo_file.read_bytes(), _subtype="png")
|
|
logo.add_header("Content-ID", "<coulobre-welcome-logo>")
|
|
logo.add_header("Content-Disposition", "inline")
|
|
related = MIMEMultipart(
|
|
"related", _subparts=[html, logo], type="text/html"
|
|
)
|
|
message.set_payload([plain, related])
|
|
return message
|
|
|
|
|
|
@sensitive_variables("context")
|
|
def invitation_email(recipient, context):
|
|
mail_settings = (
|
|
InvitationMailSettings.objects.filter(pk=1).first()
|
|
or InvitationMailSettings()
|
|
)
|
|
sender = default_sender()
|
|
if mail_settings.sender_name or mail_settings.sender_address:
|
|
name, address = parseaddr(sender)
|
|
sender = sanitize_address(
|
|
(
|
|
mail_settings.sender_name or name,
|
|
mail_settings.sender_address or address,
|
|
),
|
|
settings.DEFAULT_CHARSET,
|
|
)
|
|
return InvitationEmail(
|
|
"Welcome to Coulobre Panel",
|
|
render_to_string("hosting/panel_invitation.txt", context),
|
|
sender,
|
|
[recipient],
|
|
reply_to=[mail_settings.reply_to] if mail_settings.reply_to else None,
|
|
alternatives=[
|
|
(
|
|
render_to_string(
|
|
"hosting/panel_invitation.html",
|
|
{"invitation_content": context},
|
|
),
|
|
"text/html",
|
|
)
|
|
],
|
|
)
|
|
|
|
|
|
def invitation_message_context(user, *, setup_url=""):
|
|
invitation = getattr(user, "panel_invitation", None)
|
|
account = (
|
|
HostingAccount.objects.filter(
|
|
customer__user=user, retired_at__isnull=True
|
|
)
|
|
.select_related("hosting_plan")
|
|
.order_by("pk")
|
|
.first()
|
|
)
|
|
zone = (
|
|
account.dns_zones.filter(domain=account.primary_domain).first()
|
|
if account
|
|
else None
|
|
)
|
|
return welcome_message_context(
|
|
username=user.get_username(),
|
|
welcome_message=invitation.welcome_message if invitation else "",
|
|
setup_url=setup_url,
|
|
account=account,
|
|
nameservers=zone.nameservers if zone else (),
|
|
mail_configured=bool(
|
|
account
|
|
and account.mail_domains.filter(
|
|
domain=account.primary_domain
|
|
).exists()
|
|
),
|
|
)
|
|
|
|
|
|
def welcome_message_context(
|
|
*,
|
|
username,
|
|
welcome_message,
|
|
setup_url,
|
|
account,
|
|
nameservers,
|
|
mail_configured,
|
|
):
|
|
alias = (
|
|
mail_client_alias(account.primary_domain)
|
|
if account and mail_configured
|
|
else None
|
|
)
|
|
return {
|
|
"username": username,
|
|
"welcome_message": welcome_message,
|
|
"setup_url": setup_url,
|
|
"panel_url": (
|
|
settings.PASSWORD_RESET_ORIGIN.rstrip("/") + "/"
|
|
if settings.PASSWORD_RESET_ORIGIN
|
|
else ""
|
|
),
|
|
"account": account,
|
|
"nameservers": nameservers,
|
|
"website_records": (
|
|
website_records(account.primary_domain, wildcard=False)
|
|
if account and not nameservers
|
|
else ()
|
|
),
|
|
"imap_host": settings.MAIL_IMAP_HOST,
|
|
"submission_host": settings.MAIL_SUBMISSION_HOST,
|
|
"mail_alias": alias.name if alias else "",
|
|
"mail_configured": mail_configured,
|
|
}
|
|
|
|
|
|
class AcceptInvitation(PasswordResetConfirmView):
|
|
template_name = "hosting/accept_invitation.html"
|
|
token_generator = invitation_token
|
|
success_url = reverse_lazy("panel:login")
|
|
title = "Set up your panel password"
|
|
extra_context = {"auth_screen": True}
|
|
|
|
@transaction.atomic
|
|
def form_valid(self, form):
|
|
user = lock_user(self.user.pk)
|
|
token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN)
|
|
if not self.token_generator.check_token(user, token):
|
|
self.validlink = False
|
|
self.request.session.pop(INTERNAL_RESET_SESSION_TOKEN, None)
|
|
return self.render_to_response(self.get_context_data())
|
|
form.user = user
|
|
response = super().form_valid(form)
|
|
PanelInvitation.objects.filter(user=user).delete()
|
|
return response
|
|
|
|
|
|
class InvitationEmailForm(forms.Form):
|
|
email = forms.EmailField(label="Contact email")
|
|
|
|
|
|
@method_decorator(never_cache, name="dispatch")
|
|
class ManageInvitation(AccessMixin, FormView):
|
|
form_class = InvitationEmailForm
|
|
template_name = "hosting/manage_invitation.html"
|
|
|
|
def dispatch(self, request, *args, **kwargs):
|
|
actor = request.user
|
|
manager = reseller_for_user(actor)
|
|
kind = kwargs["kind"]
|
|
model = {"customer": Customer, "manager": Reseller}.get(kind)
|
|
if model is None or not actor.is_authenticated:
|
|
return self.handle_no_permission()
|
|
queryset = model.objects.select_related(
|
|
"user", "user__panel_invitation"
|
|
)
|
|
queryset = queryset.filter(
|
|
user__is_superuser=False, user__is_staff=False
|
|
)
|
|
if model is Customer and manager is not None:
|
|
queryset = queryset.filter(
|
|
reseller=manager, user__hosting_reseller__isnull=True
|
|
)
|
|
else:
|
|
permission = f"hosting.change_{model._meta.model_name}"
|
|
if is_tenant(actor) or not actor.has_perm(permission):
|
|
return self.handle_no_permission()
|
|
self.record = get_object_or_404(queryset, pk=kwargs["pk"])
|
|
return super().dispatch(request, *args, **kwargs)
|
|
|
|
def get_initial(self):
|
|
return {"email": self.record.user.email}
|
|
|
|
def get_context_data(self, **kwargs):
|
|
user = self.record.user
|
|
eligible = user.is_active and not user.has_usable_password()
|
|
transport = reset_enabled()
|
|
operator = self.request.user.is_superuser
|
|
if eligible and not transport:
|
|
delivery_blocker = (
|
|
"Configure outgoing panel email first."
|
|
if operator
|
|
else "Ask your server administrator to set up outgoing email."
|
|
)
|
|
elif eligible and not user.email:
|
|
delivery_blocker = (
|
|
"Save a contact email before sending an invitation."
|
|
)
|
|
else:
|
|
delivery_blocker = ""
|
|
return super().get_context_data(
|
|
login_user=user,
|
|
invitation=getattr(user, "panel_invitation", None),
|
|
can_send=eligible and transport and bool(user.email),
|
|
delivery_blocker=delivery_blocker,
|
|
can_configure_delivery=operator and not transport,
|
|
welcome_preview=(
|
|
invitation_message_context(user) if eligible else None
|
|
),
|
|
**kwargs,
|
|
)
|
|
|
|
@transaction.atomic
|
|
def form_valid(self, form):
|
|
user = lock_user(self.record.user_id)
|
|
actor_manager = reseller_for_user(self.request.user)
|
|
if (
|
|
user.is_staff
|
|
or user.is_superuser
|
|
or (
|
|
actor_manager is not None
|
|
and not Customer.objects.select_for_update()
|
|
.filter(pk=self.record.pk, user=user, reseller=actor_manager)
|
|
.exists()
|
|
)
|
|
):
|
|
return self.handle_no_permission()
|
|
user.email = form.cleaned_data["email"]
|
|
user.save(update_fields=["email"])
|
|
if "invite" in self.request.POST and reset_enabled():
|
|
queue_invitation(user)
|
|
return redirect(self.request.path)
|