60 lines
2.2 KiB
Python
60 lines
2.2 KiB
Python
from django.core.exceptions import ValidationError
|
|||
|
|
from django.db import connection, transaction
|
||
|
|
from django.db.models import F
|
||
|
|
|
||
|
|
from coulobre.mail_node import MailboxSpec
|
||
|
|
|
||
|
|
from .models import HostingAccount, HostingMailbox, HostingMailDomain
|
||
|
|
|
||
|
|
|
||
|
|
def lock_hosting_account(account_id):
|
||
|
|
accounts = HostingAccount.objects.filter(pk=account_id)
|
||
|
|
if connection.vendor == "sqlite":
|
||
|
|
# Acquire the write lock before reading the account and resource counts.
|
||
|
|
accounts.update(hosting_plan=F("hosting_plan"))
|
||
|
|
return accounts.select_for_update().get()
|
||
|
|
|
||
|
|
|
||
|
|
@transaction.atomic
|
||
|
|
def create_database_request(account_id, suffix):
|
||
|
|
account = lock_hosting_account(account_id)
|
||
|
|
databases = account.databases
|
||
|
|
if databases.filter(suffix=suffix).exists():
|
||
|
|
raise ValidationError(
|
||
|
|
{"suffix": "This account already has a database with that suffix."}
|
||
|
|
)
|
||
|
|
|
||
|
|
plan = account.hosting_plan
|
||
|
|
if (
|
||
|
|
plan
|
||
|
|
and plan.database_limit is not None
|
||
|
|
and databases.count() >= plan.database_limit
|
||
|
|
):
|
||
|
|
raise ValidationError("This hosting account has reached its database limit.")
|
||
|
|
return databases.create(suffix=suffix)
|
||
|
|
|
||
|
|
|
||
|
|
@transaction.atomic
|
||
|
|
def create_mailbox_request(account_id, local_part):
|
||
|
|
account = lock_hosting_account(account_id)
|
||
|
|
try:
|
||
|
|
spec = MailboxSpec(account.primary_domain, local_part)
|
||
|
|
except ValueError as error:
|
||
|
|
raise ValidationError({"local_part": str(error)}) from error
|
||
|
|
|
||
|
|
mail_domain, _ = HostingMailDomain.objects.get_or_create(
|
||
|
|
domain=spec.domain, defaults={"account": account}
|
||
|
|
)
|
||
|
|
if mail_domain.account_id != account.pk:
|
||
|
|
raise ValidationError("This mail domain belongs to another hosting account.")
|
||
|
|
if mail_domain.mailboxes.filter(local_part=spec.local_part).exists():
|
||
|
|
raise ValidationError(
|
||
|
|
{"local_part": "This mailbox has already been requested."}
|
||
|
|
)
|
||
|
|
|
||
|
|
plan = account.hosting_plan
|
||
|
|
if plan and plan.mailbox_limit is not None:
|
||
|
|
mailboxes = HostingMailbox.objects.filter(mail_domain__account=account)
|
||
|
|
if mailboxes.count() >= plan.mailbox_limit:
|
||
|
|
raise ValidationError("This hosting account has reached its mailbox limit.")
|
||
|
|
return mail_domain.mailboxes.create(local_part=spec.local_part)
|