def account_auto_created(user): from modoboa.core.models import User from modoboa.extensions.admin.lib import check_if_domain_exists from modoboa.lib.permissions import grant_access_to_object if parameters.get_admin("AUTO_CREATE_DOMAIN_AND_MAILBOX") == "no": return localpart, domname = split_mailbox(user.username) if user.group != 'SimpleUsers' and domname is None: return sadmins = User.objects.filter(is_superuser=True) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: label = check_if_domain_exists( domname, [(DomainAlias, _('domain alias'))]) if label is not None: return domain = Domain(name=domname, enabled=True, quota=0) domain.save(creator=sadmins[0]) for su in sadmins[1:]: grant_access_to_object(su, domain) try: mb = Mailbox.objects.get(domain=domain, address=localpart) except Mailbox.DoesNotExist: mb = Mailbox( address=localpart, domain=domain, user=user, use_domain_quota=True ) mb.set_quota(override_rules=True) mb.save(creator=sadmins[0]) for su in sadmins[1:]: grant_access_to_object(su, mb)
def save(self, user, domain): if self.cleaned_data["create_dom_admin"] == "no": return username = "******" % (self.cleaned_data["dom_admin_username"], domain.name) try: da = User.objects.get(username=username) except User.DoesNotExist: pass else: raise AdminError(_("User '%s' already exists" % username)) da = User(username=username, email=username, is_active=True) da.set_password("password") da.save() da.set_role("DomainAdmins") da.post_create(user) mb = Mailbox(address=self.cleaned_data["dom_admin_username"], domain=domain, user=da, use_domain_quota=True) mb.set_quota(override_rules=user.has_perm("admin.change_domain")) mb.save(creator=user) if self.cleaned_data["create_aliases"] == "yes": al = Alias(address="postmaster", domain=domain, enabled=True) al.save(int_rcpts=[mb], creator=user) domain.add_admin(da)
def import_account_mailbox(user, account, row): """Handle extra fields when an account is imported. Expected fields: email address; quota; [domain; ...] :param User user: user importing the account :param User account: account being imported :param list rom: list of fields (strings) """ account.email = row[0].strip() if account.email: account.save() mailbox, domname = split_mailbox(account.email) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise BadRequest( _("Account import failed (%s): domain does not exist" % account.username) ) if not user.can_access(domain): raise PermDeniedException try: mb = Mailbox.objects.get(address=mailbox, domain=domain) except Mailbox.DoesNotExist: pass else: raise Conflict(_("Mailbox %s already exists" % account.email)) if len(row) == 1: quota = None else: try: quota = int(row[1].strip()) except ValueError: raise BadRequest( _("Account import failed (%s): wrong quota value" % account.username) ) use_domain_quota = True if not quota else False mb = Mailbox(address=mailbox, domain=domain, user=account, use_domain_quota=use_domain_quota) mb.set_quota(quota, override_rules=user.has_perm("admin.change_domain")) mb.save(creator=user) if account.group == "DomainAdmins": for domname in row[2:]: try: dom = Domain.objects.get(name=domname.strip()) except Domain.DoesNotExist: continue dom.add_admin(account)
def account_auto_created(user): from modoboa.core.models import User from modoboa.lib.permissions import grant_access_to_object localpart, domname = split_mailbox(user.username) if user.group != 'SimpleUsers' and domname is None: return sadmins = User.objects.filter(is_superuser=True) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: domain = Domain(name=domname, enabled=True, quota=0) domain.save(creator=sadmins[0]) for su in sadmins[1:]: grant_access_to_object(su, domain) try: mb = Mailbox.objects.get(domain=domain, address=localpart) except Mailbox.DoesNotExist: mb = Mailbox( address=localpart, domain=domain, user=user, use_domain_quota=True ) mb.set_quota(override_rules=True) mb.save(creator=sadmins[0]) for su in sadmins[1:]: grant_access_to_object(su, mb)
def account_auto_created(user): from modoboa.core.models import User from modoboa.extensions.admin.lib import check_if_domain_exists from modoboa.lib.permissions import grant_access_to_object if parameters.get_admin("AUTO_CREATE_DOMAIN_AND_MAILBOX") == "no": return localpart, domname = split_mailbox(user.username) if user.group != 'SimpleUsers' and domname is None: return sadmins = User.objects.filter(is_superuser=True) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: label = check_if_domain_exists(domname, [(DomainAlias, _('domain alias'))]) if label is not None: return domain = Domain(name=domname, enabled=True, quota=0) domain.save(creator=sadmins[0]) for su in sadmins[1:]: grant_access_to_object(su, domain) try: mb = Mailbox.objects.get(domain=domain, address=localpart) except Mailbox.DoesNotExist: mb = Mailbox(address=localpart, domain=domain, user=user, use_domain_quota=True) mb.set_quota(override_rules=True) mb.save(creator=sadmins[0]) for su in sadmins[1:]: grant_access_to_object(su, mb)
def save(self, user, domain): if not self.fields: return if self.cleaned_data["create_dom_admin"] == "no": return username = "******" % (self.cleaned_data["dom_admin_username"], domain.name) try: da = User.objects.get(username=username) except User.DoesNotExist: pass else: raise Conflict(_("User '%s' already exists" % username)) events.raiseEvent("CanCreate", user, "mailboxes") da = User(username=username, email=username, is_active=True) da.set_password("password") da.save() da.set_role("DomainAdmins") da.post_create(user) mb = Mailbox(address=self.cleaned_data["dom_admin_username"], domain=domain, user=da, use_domain_quota=True) mb.set_quota(override_rules=user.has_perm("admin.change_domain")) mb.save(creator=user) if self.cleaned_data["create_aliases"] == "yes": events.raiseEvent("CanCreate", user, "mailbox_aliases") alias = Alias(address="postmaster", domain=domain, enabled=True) alias.save(int_rcpts=[mb]) alias.post_create(user) domain.add_admin(da)
def import_account_mailbox(user, account, row): account.email = row[0].strip() if account.email != "": account.save() mailbox, domname = split_mailbox(account.email) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError( _("Account import failed (%s): domain does not exist" % account.username)) if not user.can_access(domain): raise PermDeniedException mb = Mailbox(address=mailbox, domain=domain, user=account, use_domain_quota=True) mb.set_quota(override_rules=user.has_perm("admin.change_domain")) mb.save(creator=user) if account.group == "DomainAdmins": for domname in row[1:]: try: dom = Domain.objects.get(name=domname.strip()) except Domain.DoesNotExist: continue dom.add_admin(account)
def create_mailbox(self, user, account): locpart, domname = split_mailbox(self.cleaned_data["email"]) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise NotFound(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException try: Mailbox.objects.get(address=locpart, domain=domain) except Mailbox.DoesNotExist: pass else: raise Conflict( _("Mailbox %s already exists" % self.cleaned_data["email"])) events.raiseEvent("CanCreate", user, "mailboxes") self.mb = Mailbox(address=locpart, domain=domain, user=account, use_domain_quota=self.cleaned_data["quota_act"]) self.mb.set_quota(self.cleaned_data["quota"], user.has_perm("admin.add_domain")) self.mb.save(creator=user)
def import_account_mailbox(user, account, row): account.email = row[0].strip() if account.email != "": account.save() mailbox, domname = split_mailbox(account.email) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError( _("Account import failed (%s): domain does not exist" % account.username) ) if not user.can_access(domain): raise PermDeniedException mb = Mailbox(address=mailbox, domain=domain, user=account, use_domain_quota=True) mb.set_quota(override_rules=user.has_perm("admin.change_domain")) mb.save(creator=user) if account.group == "DomainAdmins": for domname in row[1:]: try: dom = Domain.objects.get(name=domname.strip()) except Domain.DoesNotExist: continue dom.add_admin(account)
def import_account_mailbox(user, account, row): """Handle extra fields when an account is imported. Expected fields: email address; quota; [domain; ...] :param User user: user importing the account :param User account: account being imported :param list rom: list of fields (strings) """ account.email = row[0].strip() if account.email: account.save() mailbox, domname = split_mailbox(account.email) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise BadRequest( _("Account import failed (%s): domain does not exist" % account.username)) if not user.can_access(domain): raise PermDeniedException try: mb = Mailbox.objects.get(address=mailbox, domain=domain) except Mailbox.DoesNotExist: pass else: raise Conflict(_("Mailbox %s already exists" % account.email)) if len(row) == 1: quota = None else: try: quota = int(row[1].strip()) except ValueError: raise BadRequest( _("Account import failed (%s): wrong quota value" % account.username)) use_domain_quota = True if not quota else False mb = Mailbox(address=mailbox, domain=domain, user=account, use_domain_quota=use_domain_quota) mb.set_quota(quota, override_rules=user.has_perm("admin.change_domain")) mb.save(creator=user) if account.group == "DomainAdmins": for domname in row[2:]: try: dom = Domain.objects.get(name=domname.strip()) except Domain.DoesNotExist: continue dom.add_admin(account)
def create_mailbox(self, user, account): locpart, domname = split_mailbox(self.cleaned_data["email"]) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise NotFound(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException try: Mailbox.objects.get(address=locpart, domain=domain) except Mailbox.DoesNotExist: pass else: raise Conflict( _("Mailbox %s already exists" % self.cleaned_data["email"]) ) events.raiseEvent("CanCreate", user, "mailboxes") self.mb = Mailbox(address=locpart, domain=domain, user=account, use_domain_quota=self.cleaned_data["quota_act"]) self.mb.set_quota(self.cleaned_data["quota"], user.has_perm("admin.add_domain")) self.mb.save(creator=user)
def save(self, user, account): if self.cleaned_data["email"] == "": return None if self.cleaned_data["quota_act"]: self.cleaned_data["quota"] = None if not hasattr(self, "mb") or self.mb is None: locpart, domname = split_mailbox(self.cleaned_data["email"]) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException try: Mailbox.objects.get(address=locpart, domain=domain) except Mailbox.DoesNotExist: pass else: raise AdminError(_("Mailbox %s already exists" % self.cleaned_data["email"])) events.raiseEvent("CanCreate", user, "mailboxes") self.mb = Mailbox(address=locpart, domain=domain, user=account, use_domain_quota=self.cleaned_data["quota_act"]) self.mb.set_quota(self.cleaned_data["quota"], user.has_perm("admin.add_domain")) self.mb.save(creator=user) else: newaddress = None if self.cleaned_data["email"] != self.mb.full_address: newaddress = self.cleaned_data["email"] elif account.group == "SimpleUsers" and account.username != self.mb.full_address: newaddress = account.username if newaddress is not None: local_part, domname = split_mailbox(newaddress) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException self.mb.rename(local_part, domain) self.mb.use_domain_quota = self.cleaned_data["quota_act"] override_rules = True \ if not self.mb.quota or user.has_perm("admin.add_domain") \ else False self.mb.set_quota(self.cleaned_data["quota"], override_rules) self.mb.save() account.email = self.cleaned_data["email"] account.save() for name, value in self.cleaned_data.iteritems(): if not name.startswith("aliases"): continue if value == "": continue local_part, domname = split_mailbox(value) try: self.mb.alias_set.get(address=local_part, domain__name=domname) except Alias.DoesNotExist: pass else: continue events.raiseEvent("CanCreate", user, "mailbox_aliases") al = Alias(address=local_part, enabled=account.is_active) al.domain = Domain.objects.get(name=domname) al.save(int_rcpts=[self.mb], creator=user) for alias in self.mb.alias_set.all(): if len(alias.get_recipients()) >= 2: continue if not len(filter(lambda name: self.cleaned_data[name] == alias.full_address, self.cleaned_data.keys())): alias.delete() return self.mb
class AccountFormMail(forms.Form, DynamicForm): email = forms.EmailField(label=ugettext_lazy("E-mail"), required=False) quota = forms.IntegerField( label=ugettext_lazy("Quota"), required=False, help_text=_("Quota in MB for this mailbox. Define a custom value or " "use domain's default one. Leave empty to define an " "unlimited value (not allowed for domain " "administrators)."), widget=forms.widgets.TextInput(attrs={"class": "span1"}) ) quota_act = forms.BooleanField(required=False) aliases = forms.EmailField( label=ugettext_lazy("Alias(es)"), required=False, help_text=ugettext_lazy( "Alias(es) of this mailbox. Indicate only one address per input, " "press ENTER to add a new input. Use the '*' character to create " "a 'catchall' alias (ex: *@domain.tld)." ) ) def __init__(self, *args, **kwargs): if "instance" in kwargs: self.mb = kwargs["instance"] del kwargs["instance"] else: self.mb = None super(AccountFormMail, self).__init__(*args, **kwargs) self.extra_fields = [] for fname, field in events.raiseQueryEvent('ExtraFormFields', 'mailform', self.mb): self.fields[fname] = field self.extra_fields.append(fname) if self.mb is not None: self.fields["email"].required = True cpt = 1 for alias in self.mb.alias_set.all(): if len(alias.get_recipients()) >= 2: continue name = "aliases_%d" % cpt self._create_field(forms.EmailField, name, alias.full_address) cpt += 1 self.fields["email"].initial = self.mb.full_address self.fields["quota_act"].initial = self.mb.use_domain_quota if not self.mb.use_domain_quota and self.mb.quota: self.fields["quota"].initial = self.mb.quota else: self.fields["quota_act"].initial = True if len(args) and isinstance(args[0], QueryDict): self._load_from_qdict(args[0], "aliases", forms.EmailField) def clean_email(self): """Ensure lower case emails""" return self.cleaned_data["email"].lower() def clean(self): """Custom fields validation. Check if quota is >= 0 only when the domain value is not used. """ super(AccountFormMail, self).clean() if self._errors: raise forms.ValidationError(self._errors) if not self.cleaned_data["quota_act"] \ and self.cleaned_data['quota'] is not None: if self.cleaned_data["quota"] < 0: self._errors["quota"] = self.error_class( [_("Must be a positive integer")]) del self.cleaned_data["quota"] return self.cleaned_data def create_mailbox(self, user, account): locpart, domname = split_mailbox(self.cleaned_data["email"]) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise NotFound(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException try: Mailbox.objects.get(address=locpart, domain=domain) except Mailbox.DoesNotExist: pass else: raise Conflict( _("Mailbox %s already exists" % self.cleaned_data["email"]) ) events.raiseEvent("CanCreate", user, "mailboxes") self.mb = Mailbox(address=locpart, domain=domain, user=account, use_domain_quota=self.cleaned_data["quota_act"]) self.mb.set_quota(self.cleaned_data["quota"], user.has_perm("admin.add_domain")) self.mb.save(creator=user) def update_mailbox(self, user, account): newaddress = None if self.cleaned_data["email"] != self.mb.full_address: newaddress = self.cleaned_data["email"] elif account.group == "SimpleUsers" and account.username != self.mb.full_address: newaddress = account.username if newaddress is not None: self.mb.old_full_address = self.mb.full_address local_part, domname = split_mailbox(newaddress) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise NotFound(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException self.mb.rename(local_part, domain) self.mb.use_domain_quota = self.cleaned_data["quota_act"] override_rules = True \ if not self.mb.quota or user.has_perm("admin.add_domain") \ else False self.mb.set_quota(self.cleaned_data["quota"], override_rules) self.mb.save() events.raiseEvent('MailboxModified', self.mb) def save(self, user, account): if self.cleaned_data["email"] == "": return None if self.cleaned_data["quota_act"]: self.cleaned_data["quota"] = None if not hasattr(self, "mb") or self.mb is None: self.create_mailbox(user, account) else: self.update_mailbox(user, account) events.raiseEvent( 'SaveExtraFormFields', 'mailform', self.mb, self.cleaned_data ) account.email = self.cleaned_data["email"] account.save() aliases = [] for name, value in self.cleaned_data.iteritems(): if not name.startswith("aliases"): continue if value == "": continue aliases.append(value) for alias in self.mb.alias_set.all(): if not alias.full_address in aliases: if len(alias.get_recipients()) >= 2: continue alias.delete() else: aliases.remove(alias.full_address) if aliases: events.raiseEvent( "CanCreate", user, "mailbox_aliases", len(aliases) ) for alias in aliases: local_part, domname = split_mailbox(alias) try: self.mb.alias_set.get(address=local_part, domain__name=domname) except Alias.DoesNotExist: pass else: continue al = Alias(address=local_part, enabled=account.is_active) al.domain = Domain.objects.get(name=domname) al.save(int_rcpts=[self.mb], creator=user) return self.mb
class AccountFormMail(forms.Form, DynamicForm): email = forms.EmailField(label=ugettext_lazy("E-mail"), required=False) quota = forms.IntegerField( label=ugettext_lazy("Quota"), required=False, help_text= _("Quota in MB for this mailbox. Define a custom value or use domain's default one. Leave empty to define an unlimited value (not allowed for domain administrators)." ), widget=forms.widgets.TextInput(attrs={"class": "span1"})) quota_act = forms.BooleanField(required=False) aliases = forms.EmailField( label=ugettext_lazy("Alias(es)"), required=False, help_text=ugettext_lazy( "Alias(es) of this mailbox. Indicate only one address per input, press ENTER to add a new input. Use the '*' character to create a 'catchall' alias (ex: *@domain.tld)." )) def __init__(self, *args, **kwargs): if "instance" in kwargs: self.mb = kwargs["instance"] del kwargs["instance"] super(AccountFormMail, self).__init__(*args, **kwargs) if hasattr(self, "mb") and self.mb is not None: self.fields["email"].required = True cpt = 1 for alias in self.mb.alias_set.all(): if len(alias.get_recipients()) >= 2: continue name = "aliases_%d" % cpt self._create_field(forms.EmailField, name, alias.full_address) cpt += 1 self.fields["email"].initial = self.mb.full_address self.fields["quota_act"].initial = self.mb.use_domain_quota if not self.mb.use_domain_quota and self.mb.quota: self.fields["quota"].initial = self.mb.quota else: self.fields["quota_act"].initial = True if len(args) and isinstance(args[0], QueryDict): self._load_from_qdict(args[0], "aliases", forms.EmailField) def clean_email(self): """Ensure lower case emails""" return self.cleaned_data["email"].lower() def save(self, user, account): if self.cleaned_data["email"] == "": return None if self.cleaned_data["quota_act"]: self.cleaned_data["quota"] = None if not hasattr(self, "mb") or self.mb is None: locpart, domname = split_mailbox(self.cleaned_data["email"]) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException try: Mailbox.objects.get(address=locpart, domain=domain) except Mailbox.DoesNotExist: pass else: raise AdminError( _("Mailbox %s already exists" % self.cleaned_data["email"])) events.raiseEvent("CanCreate", user, "mailboxes") self.mb = Mailbox(address=locpart, domain=domain, user=account, use_domain_quota=self.cleaned_data["quota_act"]) self.mb.set_quota(self.cleaned_data["quota"], user.has_perm("admin.add_domain")) self.mb.save(creator=user) else: newaddress = None if self.cleaned_data["email"] != self.mb.full_address: newaddress = self.cleaned_data["email"] elif account.group == "SimpleUsers" and account.username != self.mb.full_address: newaddress = account.username if newaddress is not None: local_part, domname = split_mailbox(newaddress) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException self.mb.rename(local_part, domain) self.mb.use_domain_quota = self.cleaned_data["quota_act"] override_rules = True \ if not self.mb.quota or user.has_perm("admin.add_domain") \ else False self.mb.set_quota(self.cleaned_data["quota"], override_rules) self.mb.save() account.email = self.cleaned_data["email"] account.save() for name, value in self.cleaned_data.iteritems(): if not name.startswith("aliases"): continue if value == "": continue local_part, domname = split_mailbox(value) try: self.mb.alias_set.get(address=local_part, domain__name=domname) except Alias.DoesNotExist: pass else: continue events.raiseEvent("CanCreate", user, "mailbox_aliases") al = Alias(address=local_part, enabled=account.is_active) al.domain = Domain.objects.get(name=domname) al.save(int_rcpts=[self.mb], creator=user) for alias in self.mb.alias_set.all(): if len(alias.get_recipients()) >= 2: continue if not len( filter( lambda name: self.cleaned_data[name] == alias. full_address, self.cleaned_data.keys())): alias.delete() return self.mb
def save(self, user, account): if self.cleaned_data["email"] == "": return None if self.cleaned_data["quota_act"]: self.cleaned_data["quota"] = None if not hasattr(self, "mb") or self.mb is None: locpart, domname = split_mailbox(self.cleaned_data["email"]) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException try: Mailbox.objects.get(address=locpart, domain=domain) except Mailbox.DoesNotExist: pass else: raise AdminError( _("Mailbox %s already exists" % self.cleaned_data["email"])) events.raiseEvent("CanCreate", user, "mailboxes") self.mb = Mailbox(address=locpart, domain=domain, user=account, use_domain_quota=self.cleaned_data["quota_act"]) self.mb.set_quota(self.cleaned_data["quota"], user.has_perm("admin.add_domain")) self.mb.save(creator=user) else: newaddress = None if self.cleaned_data["email"] != self.mb.full_address: newaddress = self.cleaned_data["email"] elif account.group == "SimpleUsers" and account.username != self.mb.full_address: newaddress = account.username if newaddress is not None: local_part, domname = split_mailbox(newaddress) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException self.mb.rename(local_part, domain) self.mb.use_domain_quota = self.cleaned_data["quota_act"] override_rules = True \ if not self.mb.quota or user.has_perm("admin.add_domain") \ else False self.mb.set_quota(self.cleaned_data["quota"], override_rules) self.mb.save() account.email = self.cleaned_data["email"] account.save() for name, value in self.cleaned_data.iteritems(): if not name.startswith("aliases"): continue if value == "": continue local_part, domname = split_mailbox(value) try: self.mb.alias_set.get(address=local_part, domain__name=domname) except Alias.DoesNotExist: pass else: continue events.raiseEvent("CanCreate", user, "mailbox_aliases") al = Alias(address=local_part, enabled=account.is_active) al.domain = Domain.objects.get(name=domname) al.save(int_rcpts=[self.mb], creator=user) for alias in self.mb.alias_set.all(): if len(alias.get_recipients()) >= 2: continue if not len( filter( lambda name: self.cleaned_data[name] == alias. full_address, self.cleaned_data.keys())): alias.delete() return self.mb
class AccountFormMail(forms.Form, DynamicForm): email = forms.EmailField(label=ugettext_lazy("E-mail"), required=False) quota = forms.IntegerField( label=ugettext_lazy("Quota"), required=False, help_text=_("Quota in MB for this mailbox. Define a custom value or use domain's default one. Leave empty to define an unlimited value (not allowed for domain administrators)."), widget=forms.widgets.TextInput(attrs={"class": "span1"}) ) quota_act = forms.BooleanField(required=False) aliases = forms.EmailField( label=ugettext_lazy("Alias(es)"), required=False, help_text=ugettext_lazy("Alias(es) of this mailbox. Indicate only one address per input, press ENTER to add a new input. Use the '*' character to create a 'catchall' alias (ex: *@domain.tld).") ) def __init__(self, *args, **kwargs): if "instance" in kwargs: self.mb = kwargs["instance"] del kwargs["instance"] super(AccountFormMail, self).__init__(*args, **kwargs) if hasattr(self, "mb") and self.mb is not None: self.fields["email"].required = True cpt = 1 for alias in self.mb.alias_set.all(): if len(alias.get_recipients()) >= 2: continue name = "aliases_%d" % cpt self._create_field(forms.EmailField, name, alias.full_address) cpt += 1 self.fields["email"].initial = self.mb.full_address self.fields["quota_act"].initial = self.mb.use_domain_quota if not self.mb.use_domain_quota and self.mb.quota: self.fields["quota"].initial = self.mb.quota else: self.fields["quota_act"].initial = True if len(args) and isinstance(args[0], QueryDict): self._load_from_qdict(args[0], "aliases", forms.EmailField) def clean_email(self): """Ensure lower case emails""" return self.cleaned_data["email"].lower() def save(self, user, account): if self.cleaned_data["email"] == "": return None if self.cleaned_data["quota_act"]: self.cleaned_data["quota"] = None if not hasattr(self, "mb") or self.mb is None: locpart, domname = split_mailbox(self.cleaned_data["email"]) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException try: Mailbox.objects.get(address=locpart, domain=domain) except Mailbox.DoesNotExist: pass else: raise AdminError(_("Mailbox %s already exists" % self.cleaned_data["email"])) events.raiseEvent("CanCreate", user, "mailboxes") self.mb = Mailbox(address=locpart, domain=domain, user=account, use_domain_quota=self.cleaned_data["quota_act"]) self.mb.set_quota(self.cleaned_data["quota"], user.has_perm("admin.add_domain")) self.mb.save(creator=user) else: newaddress = None if self.cleaned_data["email"] != self.mb.full_address: newaddress = self.cleaned_data["email"] elif account.group == "SimpleUsers" and account.username != self.mb.full_address: newaddress = account.username if newaddress is not None: local_part, domname = split_mailbox(newaddress) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise AdminError(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException self.mb.rename(local_part, domain) self.mb.use_domain_quota = self.cleaned_data["quota_act"] override_rules = True \ if not self.mb.quota or user.has_perm("admin.add_domain") \ else False self.mb.set_quota(self.cleaned_data["quota"], override_rules) self.mb.save() account.email = self.cleaned_data["email"] account.save() for name, value in self.cleaned_data.iteritems(): if not name.startswith("aliases"): continue if value == "": continue local_part, domname = split_mailbox(value) try: self.mb.alias_set.get(address=local_part, domain__name=domname) except Alias.DoesNotExist: pass else: continue events.raiseEvent("CanCreate", user, "mailbox_aliases") al = Alias(address=local_part, enabled=account.is_active) al.domain = Domain.objects.get(name=domname) al.save(int_rcpts=[self.mb], creator=user) for alias in self.mb.alias_set.all(): if len(alias.get_recipients()) >= 2: continue if not len(filter(lambda name: self.cleaned_data[name] == alias.full_address, self.cleaned_data.keys())): alias.delete() return self.mb
class AccountFormMail(forms.Form, DynamicForm): """Form to handle mail part.""" email = forms.EmailField(label=ugettext_lazy("E-mail"), required=False) quota = forms.IntegerField( label=ugettext_lazy("Quota"), required=False, help_text=_("Quota in MB for this mailbox. Define a custom value or " "use domain's default one. Leave empty to define an " "unlimited value (not allowed for domain " "administrators)."), widget=forms.widgets.TextInput(attrs={"class": "form-control"})) quota_act = forms.BooleanField(required=False) aliases = forms.EmailField( label=ugettext_lazy("Alias(es)"), required=False, help_text=ugettext_lazy( "Alias(es) of this mailbox. Indicate only one address per input, " "press ENTER to add a new input. Use the '*' character to create " "a 'catchall' alias (ex: *@domain.tld).")) def __init__(self, *args, **kwargs): if "instance" in kwargs: self.mb = kwargs["instance"] del kwargs["instance"] else: self.mb = None super(AccountFormMail, self).__init__(*args, **kwargs) self.field_widths = {"quota": 3} self.extra_fields = [] for fname, field in events.raiseQueryEvent('ExtraFormFields', 'mailform', self.mb): self.fields[fname] = field self.extra_fields.append(fname) if self.mb is not None: self.fields["email"].required = True cpt = 1 for alias in self.mb.alias_set.all(): if len(alias.get_recipients()) >= 2: continue name = "aliases_%d" % cpt self._create_field(forms.EmailField, name, alias.full_address) cpt += 1 self.fields["email"].initial = self.mb.full_address self.fields["quota_act"].initial = self.mb.use_domain_quota if not self.mb.use_domain_quota and self.mb.quota: self.fields["quota"].initial = self.mb.quota else: self.fields["quota_act"].initial = True if len(args) and isinstance(args[0], QueryDict): self._load_from_qdict(args[0], "aliases", forms.EmailField) def clean_email(self): """Ensure lower case emails""" return self.cleaned_data["email"].lower() def clean(self): """Custom fields validation. Check if quota is >= 0 only when the domain value is not used. """ super(AccountFormMail, self).clean() if self._errors: raise forms.ValidationError(self._errors) if not self.cleaned_data["quota_act"] \ and self.cleaned_data['quota'] is not None: if self.cleaned_data["quota"] < 0: self._errors["quota"] = self.error_class( [_("Must be a positive integer")]) del self.cleaned_data["quota"] return self.cleaned_data def create_mailbox(self, user, account): """Create a mailbox associated to :kw:`account`.""" locpart, domname = split_mailbox(self.cleaned_data["email"]) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise NotFound(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException try: Mailbox.objects.get(address=locpart, domain=domain) except Mailbox.DoesNotExist: pass else: raise Conflict( _("Mailbox %s already exists" % self.cleaned_data["email"])) events.raiseEvent("CanCreate", user, "mailboxes") self.mb = Mailbox(address=locpart, domain=domain, user=account, use_domain_quota=self.cleaned_data["quota_act"]) self.mb.set_quota(self.cleaned_data["quota"], user.has_perm("admin.add_domain")) self.mb.save(creator=user) def update_mailbox(self, user, account): newaddress = None if self.cleaned_data["email"] != self.mb.full_address: newaddress = self.cleaned_data["email"] elif account.group == "SimpleUsers" and account.username != self.mb.full_address: newaddress = account.username if newaddress is not None: self.mb.old_full_address = self.mb.full_address local_part, domname = split_mailbox(newaddress) try: domain = Domain.objects.get(name=domname) except Domain.DoesNotExist: raise NotFound(_("Domain does not exist")) if not user.can_access(domain): raise PermDeniedException self.mb.rename(local_part, domain) self.mb.use_domain_quota = self.cleaned_data["quota_act"] override_rules = True \ if not self.mb.quota or user.has_perm("admin.add_domain") \ else False self.mb.set_quota(self.cleaned_data["quota"], override_rules) self.mb.save() events.raiseEvent('MailboxModified', self.mb) def _update_aliases(self, user, account): """Update mailbox aliases.""" aliases = [] for name, value in self.cleaned_data.iteritems(): if not name.startswith("aliases"): continue if value == "": continue aliases.append(value) for alias in self.mb.alias_set.all(): if not alias.full_address in aliases: if len(alias.get_recipients()) >= 2: continue alias.delete() else: aliases.remove(alias.full_address) if not aliases: return events.raiseEvent("CanCreate", user, "mailbox_aliases", len(aliases)) for alias in aliases: local_part, domname = split_mailbox(alias) try: self.mb.alias_set.get(address=local_part, domain__name=domname) except Alias.DoesNotExist: pass else: continue al = Alias(address=local_part, enabled=account.is_active) al.domain = Domain.objects.get(name=domname) al.save(int_rcpts=[self.mb]) al.post_create(user) def save(self, user, account): """Save or update account mailbox.""" if self.cleaned_data["email"] == "": return None if self.cleaned_data["quota_act"]: self.cleaned_data["quota"] = None if not hasattr(self, "mb") or self.mb is None: self.create_mailbox(user, account) else: self.update_mailbox(user, account) events.raiseEvent('SaveExtraFormFields', 'mailform', self.mb, self.cleaned_data) account.email = self.cleaned_data["email"] account.save() self._update_aliases(user, account) return self.mb