Making Modoboa a standard django application.

see #245
This commit is contained in:
Antoine Nguyen
2012-06-20 09:21:10 +02:00
parent 06268041c1
commit 0503c684ea
280 changed files with 260 additions and 10 deletions
View File
+72
View File
@@ -0,0 +1,72 @@
# -*- coding: utf-8 -*-
from modoboa.lib import parameters, events
from django.utils.translation import ugettext as _, ugettext_lazy
from django.db.utils import DatabaseError
from models import Extension
parameters.register_admin("AUTHENTICATION_TYPE", type="list", deflt="local",
values=[('local', ugettext_lazy("Local")),
('ldap', "LDAP")],
help=ugettext_lazy("The backend used for authentication"))
parameters.register_admin("CREATE_DIRECTORIES", type="list_yesno", deflt="yes",
help=ugettext_lazy("Modoboa will handle mailbox creation on filesystem"))
parameters.register_admin("STORAGE_PATH", type="string", deflt="/var/vmail",
help=ugettext_lazy("Path to the root directory where messages are stored"))
parameters.register_admin("VIRTUAL_UID", type="string", deflt="vmail",
help=ugettext_lazy("UID of the virtual user which owns domains/mailboxes/messages on the filesystem"))
parameters.register_admin("VIRTUAL_GID", type="string", deflt="vmail",
help=ugettext_lazy("GID of the virtual user which owns domains/mailboxes/messages on the filesystem"))
parameters.register_admin("MAILBOX_TYPE", type="list", deflt="maildir",
values=[("maildir", "maildir"), ("mbox", "mbox")],
help=ugettext_lazy("Mailboxes storage format"))
parameters.register_admin("MAILDIR_ROOT", type="string", deflt=".maildir",
help=ugettext_lazy("Sub-directory (inside the mailbox) where messages are stored when using the maildir format"))
parameters.register_admin(
"PASSWORD_SCHEME", type="list", deflt="crypt",
values=[("crypt", "crypt"), ("md5", "md5"), ("sha256", "sha256"), ("plain", "plain")],
help=ugettext_lazy("Scheme used to crypt mailbox passwords")
)
parameters.register_admin("ITEMS_PER_PAGE", type="int", deflt=30,
help=ugettext_lazy("Number of displayed items per page"))
def enabled_applications():
"""Return the list of currently enabled extensions
We check if the table exists before trying to fetch activated
extensions because the admin module is always imported by Django,
even before the database exists (example: the first ``syncdb``).
:return: a list
"""
from modoboa.lib.dbutils import db_table_exists
result = [("admin", "admin"), ("userprefs", "userprefs")]
if db_table_exists("admin_extension"):
exts = Extension.objects.filter(enabled=True)
result += [(ext.name, ext.name) for ext in exts]
return sorted(result, key=lambda e: e[0])
parameters.register_admin("DEFAULT_TOP_REDIRECTION", type="list", deflt="admin",
app="general",
values=enabled_applications(),
help=ugettext_lazy("The default redirection used when no application is specified"))
@events.observe("ExtDisabled")
def unset_default_topredirection(extension):
"""
Simple callback to change the default redirection if the
corresponding extension is being disabled.
"""
topredirection = parameters.get_admin("DEFAULT_TOP_REDIRECTION", app="general")
if topredirection == extension.name:
parameters.save_admin("DEFAULT_TOP_REDIRECTION", "userprefs", app="general")
@events.observe("ExtDisabled", "ExtEnabled")
def update_available_applications(extension):
"""Simple callback to update the list of available applications
Must be called each time an extension is disabled/enabled.
"""
parameters.update_admin("DEFAULT_TOP_REDIRECTION", app="general",
values=enabled_applications())
+15
View File
@@ -0,0 +1,15 @@
# coding: utf-8
"""
:mod:`exceptions` --- Custom exceptions of the admin. application
-----------------------------------------------------------------
"""
from modoboa.lib.exceptions import ModoboaException
class AdminError(ModoboaException):
"""
Just a Custom exception to identify errors coming from the admin
application.
"""
pass
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
[{"pk": 1, "model": "auth.group", "fields": {"name": "DomainAdmins", "permissions": [["add_user", "auth", "user"], ["change_user", "auth", "user"], ["delete_user", "auth", "user"], ["add_mailbox", "admin", "mailbox"], ["change_mailbox", "admin", "mailbox"], ["delete_mailbox", "admin", "mailbox"], ["add_alias", "admin", "alias"], ["change_alias", "admin", "alias"], ["delete_alias", "admin", "alias"], ["view_mailboxes", "admin", "mailbox"], ["view_aliases", "admin", "alias"], ["view_domaliases", "admin", "domainalias"], ["add_domainalias", "admin", "domainalias"], ["change_domainalias", "admin", "domainalias"], ["delete_domainalias", "admin", "domainalias"]]}},{"pk": 2, "model": "auth.group", "fields": {"name": "SimpleUsers", "permissions": []}},{"pk": 1, "model": "auth.user", "fields": {"username": "admin", "first_name": "", "last_name": "", "is_active": true, "is_superuser": true, "is_staff": false, "last_login": "2012-01-26 15:19:25", "groups": [], "user_permissions": [], "password": "{CRYPT}dTTsGDkA5ZHKg", "email": "", "date_joined": "2012-01-26 15:19:25"}},{"pk": 1, "model": "admin.objectaccess", "fields": {"is_owner": false, "user": 1, "content_type": ["admin", "user"], "object_id": 1}}]
+1
View File
@@ -0,0 +1 @@
[{"pk": 2, "model": "admin.user", "fields": {"username": "user@test.com", "is_active": "True", "is_superuser": "False", "password": "{PLAIN}toto", "groups": [2]}},{"pk": 3, "model": "admin.user", "fields": {"username": "admin@test.com", "is_active": "True", "is_superuser": "False", "password": "{PLAIN}toto", "groups": [1]}},{"pk": 1, "model": "admin.ObjectDates", "fields": {"creation": "2011-09-07 09:27:07.579603"}}, {"pk": 2, "model": "admin.ObjectDates", "fields": {"creation": "2011-09-07 09:27:07.579603"}}, {"pk": 1, "model": "admin.Domain", "fields": {"name" : "test.com", "quota" : "100", "dates": "1"}}, {"pk": 1, "model": "admin.Mailbox", "fields": {"address": "user", "domain": "1", "dates": "1", "uid": "1001", "gid": "1001", "path": "user", "quota": "10", "user": "2"}}, {"pk": 2, "model": "admin.Mailbox", "fields": {"address": "admin", "domain": "1", "dates": "2", "uid": "1001", "gid": "1001", "path": "admin", "quota": "10", "user": "3"}}]
+635
View File
@@ -0,0 +1,635 @@
# coding: utf-8
from django import forms
from django.contrib.auth.models import Group
from modoboa.admin.models import *
from django.utils.translation import ugettext as _, ugettext_lazy
from django.http import QueryDict
from modoboa.admin.templatetags.admin_extras import gender
from modoboa.lib.emailutils import split_mailbox
from modoboa.lib.permissions import get_account_roles
from modoboa.lib.formutils import *
from modoboa.lib.permissions import *
class DomainFormGeneral(forms.ModelForm, DynamicForm):
aliases = DomainNameField(
label=ugettext_lazy("Alias(es)"),
required=False,
help_text=ugettext_lazy("Alias(es) of this domain")
)
class Meta:
model = Domain
fields = ("name", "quota", "aliases", "enabled")
def __init__(self, *args, **kwargs):
self.oldname = None
if kwargs.has_key("instance"):
self.oldname = kwargs["instance"].name
super(DomainFormGeneral, self).__init__(*args, **kwargs)
if len(args) and isinstance(args[0], QueryDict):
self._load_from_qdict(args[0], "aliases", DomainNameField)
elif kwargs.has_key("instance"):
d = kwargs["instance"]
for pos, dalias in enumerate(d.domainalias_set.all()):
name = "aliases_%d" % (pos + 1)
self._create_field(forms.CharField, name, dalias.name, 3)
def clean(self):
super(DomainFormGeneral, self).clean()
if len(self._errors):
raise forms.ValidationError(self._errors)
cleaned_data = self.cleaned_data
name = cleaned_data["name"]
try:
DomainAlias.objects.get(name=name)
except DomainAlias.DoesNotExist:
pass
else:
self._errors["name"] = self.error_class([_("An alias with this name already exists")])
del cleaned_data["name"]
errors = []
for k in cleaned_data.keys():
if not k.startswith("aliases"):
continue
if cleaned_data[k] == "":
del cleaned_data[k]
continue
try:
Domain.objects.get(name=cleaned_data[k])
except Domain.DoesNotExist:
pass
else:
self._errors[k] = self.error_class([_("A domain with this name already exists")])
del cleaned_data[k]
return cleaned_data
def save(self, user, commit=True):
d = super(DomainFormGeneral, self).save(commit=False)
if commit:
if self.oldname is not None and d.name != self.oldname:
if not d.rename_dir(self.oldname):
raise AdminError(_("Failed to rename domain, check permissions"))
d.save()
for k, v in self.cleaned_data.iteritems():
if not k.startswith("aliases"):
continue
if v in ["", None]:
continue
try:
d.domainalias_set.get(name=v)
except DomainAlias.DoesNotExist:
pass
else:
continue
events.raiseEvent("CanCreate", user, "domain_aliases")
al = DomainAlias(name=v, target=d, enabled=d.enabled)
al.save()
grant_access_to_object(user, al, is_owner=True)
events.raiseEvent("DomainAliasCreated", user, al)
for dalias in d.domainalias_set.all():
if not len(filter(lambda name: self.cleaned_data[name] == dalias.name,
self.cleaned_data.keys())):
dalias.delete()
return d
class DomainForm(TabForms):
def __init__(self, user, *args, **kwargs):
self.user = user
self.forms = [
dict(id="general", title=_("General"), formtpl="admin/domain_general_form.html",
cls=DomainFormGeneral, mandatory=True),
]
cbargs = [user]
if kwargs.has_key("instances"):
cbargs += [kwargs["instances"]["general"]]
self.forms += events.raiseQueryEvent("ExtraDomainForm", *cbargs)
super(DomainForm, self).__init__(*args, **kwargs)
def save(self, user):
"""Custom save method
As forms interact with each other, it is simpler to make
custom code to save them.
"""
self.forms[0]["instance"].save(user)
if len(self.forms) <= 1:
return
for f in self.forms[1:]:
f["instance"].save()
class DlistForm(forms.ModelForm, DynamicForm):
email = forms.EmailField(
label=ugettext_lazy("Email address"),
help_text=ugettext_lazy("The distribution list address")
)
recipients = forms.EmailField(
label=ugettext_lazy("Recipients"), required=False,
help_text=ugettext_lazy("Mailbox(es) this alias will point to")
)
class Meta:
model = Alias
fields = ("enabled",)
def __init__(self, user, *args, **kwargs):
self.user = user
super(DlistForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['email', 'recipients', 'enabled']
if len(args) and isinstance(args[0], QueryDict):
self._load_from_qdict(args[0], "recipients", forms.EmailField)
elif kwargs.has_key("instance"):
dlist = kwargs["instance"]
self.fields["email"].initial = dlist.full_address
cpt = 1
for mb in dlist.mboxes.all():
name = "recipients_%d" % (cpt)
self._create_field(forms.EmailField, name, mb.full_address, 2)
cpt += 1
for addr in dlist.extmboxes.split(','):
if addr == "":
continue
name = "recipients_%d" % (cpt)
self._create_field(forms.EmailField, name, addr, 2)
cpt += 1
def clean_email(self):
localpart, domname = split_mailbox(self.cleaned_data["email"])
try:
domain = Domain.objects.get(name=domname)
except Domain.DoesNotExist:
raise forms.ValidationError(_("Domain does not exist"))
if not self.user.can_access(domain):
raise forms.ValidationError(_("You don't have access to this domain"))
return self.cleaned_data["email"]
def set_recipients(self):
"""Recipients dispatching
We make a difference between 'local' recipients (the ones hosted
by Modoboa) and 'external' recipients.
"""
self.ext_rcpts = []
self.int_rcpts = []
total = 0
for k, v in self.cleaned_data.iteritems():
if not k.startswith("recipients"):
continue
if v == "":
continue
local_part, domname = split_mailbox(v)
if domname is None:
raise AdminError("%s %s" % (_("Invalid mailbox"), v))
try:
domain = Domain.objects.get(name=domname)
except Domain.DoesNotExist:
domain = None
if domain:
if not self.user.can_access(domain):
raise PermDeniedException(v)
try:
mb = Mailbox.objects.get(domain=domain, address=local_part)
except Mailbox.DoesNotExist:
raise AdminError(_("Mailbox %s does not exist" % v))
self.int_rcpts += [mb]
total += 1
continue
self.ext_rcpts += [v]
total += 1
if total == 0:
raise AdminError(_("No recipient defined"))
if total < 2:
raise AdminError(_("A distribution list must contain at least two recipients"))
def save(self, commit=True):
dlist = super(DlistForm, self).save(commit=False)
localpart, domname = split_mailbox(self.cleaned_data["email"])
dlist.address = localpart
dlist.domain = Domain.objects.get(name=domname)
if commit:
dlist.save(self.int_rcpts, self.ext_rcpts)
self.save_m2m()
return dlist
class GenericAliasForm(forms.ModelForm):
email = forms.EmailField(
label=ugettext_lazy("Address"),
help_text=ugettext_lazy("A valid e-mail address")
)
class Meta:
model = Alias
fields = ("enabled",)
def __init__(self, user, *args, **kwargs):
self.user = user
super(GenericAliasForm, self).__init__(*args, **kwargs)
if kwargs.has_key("instance"):
alias = kwargs["instance"]
self.fields["email"].initial = alias.full_address
def clean_email(self):
localpart, domname = split_mailbox(self.cleaned_data["email"])
try:
domain = Domain.objects.get(name=domname)
except Domain.DoesNotExist:
raise forms.ValidationError(_("Domain does not exist"))
if not self.user.can_access(domain):
raise forms.ValidationError(_("You don't have access to this domain"))
return self.cleaned_data["email"]
def set_recipients(self):
pass
def _save(self):
alias = super(GenericAliasForm, self).save(commit=False)
localpart, domname = split_mailbox(self.cleaned_data["email"])
alias.address = localpart
alias.domain = Domain.objects.get(name=domname)
return alias
class AliasForm(GenericAliasForm):
int_recipient = forms.EmailField(
label=ugettext_lazy("Recipient"),
help_text=ugettext_lazy("A local recipient address")
)
def __init__(self, *args, **kwargs):
super(AliasForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['email', 'int_recipient', 'enabled']
if kwargs.has_key("instance"):
alias = kwargs["instance"]
self.fields["int_recipient"].initial = alias.mboxes.all()[0].full_address
def clean_int_recipient(self):
localpart, domname = split_mailbox(self.cleaned_data["int_recipient"])
try:
self.rcpt_mb = Mailbox.objects.get(address=localpart, domain__name=domname)
except Mailbox.DoesNotExist:
raise forms.ValidationError(_("Mailbox does not exist"))
if not self.user.can_access(self.rcpt_mb):
raise forms.ValidationError(_("You can't access this mailbox"))
return self.cleaned_data["int_recipient"]
def save(self, commit=True):
alias = self._save()
if commit:
alias.save([self.rcpt_mb], [])
return alias
class ForwardForm(GenericAliasForm):
ext_recipient = forms.EmailField(
label=ugettext_lazy("Recipient"),
help_text=ugettext_lazy("An external recipient address")
)
def __init__(self, *args, **kwargs):
super(ForwardForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['email', 'ext_recipient', 'enabled']
if kwargs.has_key("instance"):
alias = kwargs["instance"]
self.fields["ext_recipient"].initial = alias.extmboxes
def clean_ext_recipient(self):
local_part, domname = split_mailbox(self.cleaned_data["ext_recipient"])
try:
domain = Domain.objects.get(name=domname)
except Domain.DoesNotExist:
pass
else:
raise forms.ValidationError(_("Local recipients are forbidden"))
return self.cleaned_data["ext_recipient"]
def save(self, commit=True):
alias = self._save()
if commit:
alias.save([], [self.cleaned_data["ext_recipient"]])
return alias
class ImportDataForm(forms.Form):
sourcefile = forms.FileField(label=ugettext_lazy("Select a file"))
sepcar = forms.CharField(label=ugettext_lazy("Separator"), max_length=1, required=False)
def __init__(self, *args, **kwargs):
super(ImportDataForm, self).__init__(*args, **kwargs)
self.fields["sepcar"].widget.attrs = {"class" : "span1"}
def clean_sepcar(self):
if self.cleaned_data["sepcar"] == "":
return ";"
return str(self.cleaned_data["sepcar"])
class AccountFormGeneral(forms.ModelForm):
username = forms.CharField(label=ugettext_lazy("Username"), max_length=254)
role = forms.ChoiceField(
label=ugettext_lazy("Role"),
choices=[('', ugettext_lazy("Choose"))],
help_text=ugettext_lazy("What level of permission this user will have")
)
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(
label=ugettext_lazy("Confirmation"),
widget=forms.PasswordInput,
help_text=ugettext_lazy("Enter the same password as above, for verification.")
)
class Meta:
model = User
fields = ("username", "first_name", "last_name", "role", "is_active")
def __init__(self, user, *args, **kwargs):
super(AccountFormGeneral, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['role', 'username', 'first_name', 'last_name',
'password1', 'password2', 'is_active']
self.fields["is_active"].label = _("Enabled")
self.user = user
if user.group == "DomainAdmins":
del self.fields["role"]
else:
self.fields["role"].choices = \
[('', ugettext_lazy("Choose"))] + get_account_roles(user)
if kwargs.has_key("instance"):
if len(args) \
and (args[0].get("password1", "") == "" \
and args[0].get("password2", "") == ""):
self.fields["password1"].required = False
self.fields["password2"].required = False
if user.group != "DomainAdmins":
u = kwargs["instance"]
if u.is_superuser:
role = "SuperAdmins"
else:
try:
role = u.groups.all()[0].name
except IndexError:
pass
self.fields["role"].initial = role
def clean_username(self):
from django.core.validators import validate_email
if not self.cleaned_data.has_key("role"):
return self.cleaned_data["username"]
if self.cleaned_data["role"] != "SimpleUsers":
return self.cleaned_data["username"]
validate_email(self.cleaned_data["username"])
return self.cleaned_data["username"]
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def give_all_accesses(self, account):
"""Give access to all objects defined in the database
Must be used when an account is promoted as a super user.
:param account: a ``User`` instance
"""
grant_access_to_objects(account, User.objects.all(), get_content_type(User))
grant_access_to_objects(account, Domain.objects.all(), get_content_type(Domain))
grant_access_to_objects(account, DomainAlias.objects.all(), get_content_type(DomainAlias))
grant_access_to_objects(account, Mailbox.objects.all(), get_content_type(Mailbox))
grant_access_to_objects(account, Alias.objects.all(), get_content_type(Alias))
def save(self, commit=True):
account = super(AccountFormGeneral, self).save(commit=False)
if commit:
if self.cleaned_data["password1"] != "":
account.set_password(self.cleaned_data["password1"])
account.save()
role = None
if self.cleaned_data.has_key("role"):
role = self.cleaned_data["role"]
elif self.user.group == "DomainAdmins" and self.user != account:
role = "SimpleUsers"
if role is not None:
account.groups.clear()
if role == "SuperAdmins":
account.is_superuser = True
self.give_all_accesses(account)
else:
if account.is_superuser:
ObjectAccess.objects.filter(user=account).delete()
account.is_superuser = False
account.groups.add(Group.objects.get(name=role))
account.save()
return account
class AccountFormMail(forms.Form, DynamicForm):
email = forms.EmailField(label=ugettext_lazy("E-mail"), required=False)
quota = forms.IntegerField(label=ugettext_lazy("Quota"), required=False)
aliases = forms.EmailField(
label=ugettext_lazy("Alias(es)"),
required=False,
help_text=ugettext_lazy("Alias(es) of this mailbox")
)
def __init__(self, *args, **kwargs):
if kwargs.has_key("instance"):
self.mb = kwargs["instance"]
del kwargs["instance"]
super(AccountFormMail, self).__init__(*args, **kwargs)
if not hasattr(self, "mb") or self.mb is None:
return
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"].initial = self.mb.quota
if len(args) and isinstance(args[0], QueryDict):
self._load_from_qdict(args[0], "aliases", forms.EmailField)
def save(self, user, account):
if self.cleaned_data["email"] == "":
return 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
if not hasattr(self, "mb") or self.mb is None:
try:
self.mb = Mailbox.objects.get(address=locpart, domain=domain)
except Mailbox.DoesNotExist:
events.raiseEvent("CanCreate", user, "mailboxes")
self.mb = Mailbox()
self.mb.save_from_user(locpart, domain, account,
self.cleaned_data["quota"])
grant_access_to_object(user, self.mb, is_owner=True)
events.raiseEvent("CreateMailbox", user, self.mb)
if user.is_superuser:
for admin in self.mb.domain.admins:
grant_access_to_object(admin, self.mb)
grant_access_to_object(admin, self.mb.user)
else:
if self.cleaned_data["email"] != self.mb.full_address:
if self.mb.rename_dir(domname, locpart):
self.mb.domain = domain
self.mb.address = locpart
else:
raise AdminError(_("Failed to rename mailbox, check permissions"))
self.mb.save(quota=self.cleaned_data["quota"])
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([self.mb], [])
grant_access_to_object(user, al, is_owner=True)
events.raiseEvent("MailboxAliasCreated", user, al)
if user.is_superuser:
for admin in al.domain.admins:
grant_access_to_object(admin, al)
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())):
events.raiseEvent("MailboxAliasDeleted", alias)
ungrant_access_to_object(alias)
alias.delete()
return self.mb
class AccountPermissionsForm(forms.Form, DynamicForm):
domains = DomainNameField(
label=ugettext_lazy("Domain(s)"),
required=False,
help_text=ugettext_lazy("Domain(s) that user administrates")
)
def __init__(self, *args, **kwargs):
if kwargs.has_key("instance"):
self.account = kwargs["instance"]
del kwargs["instance"]
super(AccountPermissionsForm, self).__init__(*args, **kwargs)
if not hasattr(self, "account") or self.account is None:
return
for pos, domain in enumerate(self.account.get_domains()):
name = "domains_%d" % (pos + 1)
self._create_field(DomainNameField, name, domain.name)
if len(args) and isinstance(args[0], QueryDict):
self._load_from_qdict(args[0], "domains", DomainNameField)
def save(self):
current_domains = map(lambda dom: dom.name, self.account.get_domains())
for name, value in self.cleaned_data.iteritems():
if not name.startswith("domains"):
continue
if value in ["", None]:
continue
if not value in current_domains:
domain = Domain.objects.get(name=value)
grant_access_to_object(self.account, domain)
for mb in domain.mailbox_set.all():
grant_access_to_object(self.account, mb)
grant_access_to_object(self.account, mb.user)
for al in Alias.objects.filter(domain=domain):
grant_access_to_object(self.account, al)
for domain in self.account.get_domains():
if not len(filter(lambda name: self.cleaned_data[name] == domain.name,
self.cleaned_data.keys())):
ungrant_access_to_object(domain, self.account)
for mb in domain.mailbox_set.all():
ungrant_access_to_object(mb, self.account)
ungrant_access_to_object(mb.user, self.account)
for al in Alias.objects.filter(domain=domain):
ungrant_access_to_object(al, self.account)
class AccountForm(TabForms):
def __init__(self, user, *args, **kwargs):
self.user = user
self.forms = [
dict(id="general", title=_("General"), cls=AccountFormGeneral,
new_args=[user], mandatory=True),
dict(id="mail", title=_("Mail"), formtpl="admin/mailform.html",
cls=AccountFormMail),
dict(id="perms", title=_("Permissions"), formtpl="admin/permsform.html",
cls=AccountPermissionsForm)
]
cbargs = [user]
if kwargs.has_key("instances"):
cbargs += [kwargs["instances"]["general"]]
self.forms += events.raiseQueryEvent("ExtraAccountForm", *cbargs)
super(AccountForm, self).__init__(*args, **kwargs)
def check_perms(self, account):
if account.is_superuser:
return False
return self.user.has_perm("admin.add_domain") \
and account.has_perm("auth.add_user")
def _before_is_valid(self, form):
if form["id"] == "general":
return True
if hasattr(self, "check_%s" % form["id"]):
if not getattr(self, "check_%s" % form["id"])(self.account):
return False
return True
if False in events.raiseQueryEvent("CheckExtraAccountForm", self.account, form):
return False
return True
def save_general_form(self):
self.account = self.forms[0]["instance"].save()
def save(self):
"""Custom save method
As forms interact with each other, it is simpler to make
custom code to save them.
"""
self.forms[1]["instance"].save(self.user, self.account)
if len(self.forms) <= 2:
return
for f in self.forms[2:]:
f["instance"].save()
+43
View File
@@ -0,0 +1,43 @@
# coding: utf-8
from django.utils.translation import ugettext as _
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from modoboa.lib.webutils import _render
from modoboa.lib import parameters
from modoboa.admin.tables import *
from exceptions import *
def render_listing(request, objtype, tplname="admin/listing.html",
**kwargs):
"""Common function to render a listing
All listing pages available into the admin application use the
same layout, rendered by this function.
:param request: a ``Request`` object
:param objtype: the object type's name (lowercase)
:param tplname: the template used to render the HTML
"""
tblclass = "%sTable" % objtype.capitalize()
if not globals().has_key(tblclass):
raise AdminError(_("Unknown object type"))
tblclass = globals()[tblclass]
if request.GET.has_key("domid"):
kwargs["domid"] = request.GET["domid"]
else:
kwargs["domid"] = ""
kwargs["selection"] = objtype
paginator = Paginator(kwargs["objects"],
int(parameters.get_admin("ITEMS_PER_PAGE")))
try:
page = request.GET.get("page", "1")
except ValueError:
page = 1
try:
kwargs["page"] = paginator.page(page)
except (EmptyPage, PageNotAnInteger):
kwargs["page"] = paginator.page(paginator.num_pages)
kwargs["table"] = tblclass(request, kwargs["page"].object_list)
kwargs["selection"] = objtype
return _render(request, tplname, kwargs)
+127
View File
@@ -0,0 +1,127 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Domain'
db.create_table('admin_domain', (
('quota', self.gf('django.db.models.fields.IntegerField')()),
('enabled', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
))
db.send_create_signal('admin', ['Domain'])
# Adding model 'Mailbox'
db.create_table('admin_mailbox', (
('domain', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['admin.Domain'])),
('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('quota', self.gf('django.db.models.fields.IntegerField')()),
('full_address', self.gf('django.db.models.fields.CharField')(max_length=150)),
('gid', self.gf('django.db.models.fields.IntegerField')()),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('address', self.gf('django.db.models.fields.CharField')(max_length=100)),
('path', self.gf('django.db.models.fields.CharField')(max_length=255)),
('password', self.gf('django.db.models.fields.CharField')(max_length=100)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('uid', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('admin', ['Mailbox'])
# Adding model 'Alias'
db.create_table('admin_alias', (
('enabled', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True)),
('mbox', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['admin.Mailbox'])),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('full_address', self.gf('django.db.models.fields.CharField')(max_length=150)),
('address', self.gf('django.db.models.fields.CharField')(max_length=100)),
))
db.send_create_signal('admin', ['Alias'])
def backwards(self, orm):
# Deleting model 'Domain'
db.delete_table('admin_domain')
# Deleting model 'Mailbox'
db.delete_table('admin_mailbox')
# Deleting model 'Alias'
db.delete_table('admin_alias')
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mbox': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Mailbox']"})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,104 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
no_dry_run = True
def forwards(self, orm):
# Adding M2M table for field mboxes on 'Alias'
db.create_table('admin_alias_mboxes', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('alias', models.ForeignKey(orm['admin.alias'], null=False)),
('mailbox', models.ForeignKey(orm['admin.mailbox'], null=False))
))
db.create_unique('admin_alias_mboxes', ['alias_id', 'mailbox_id'])
for alias in orm.Alias.objects.all():
alias.mboxes.add(alias.mbox_id)
alias.save()
# Deleting field 'Alias.mbox'
db.delete_column('admin_alias', 'mbox_id')
def backwards(self, orm):
# Adding field 'Alias.mbox'
db.add_column('admin_alias', 'mbox', self.gf('django.db.models.fields.related.ForeignKey')(default=-1, to=orm['admin.Mailbox']), keep_default=False)
# Removing M2M table for field mboxes on 'Alias'
db.delete_table('admin_alias_mboxes')
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']"})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,100 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Extension'
db.create_table('admin_extension', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=150)),
('enabled', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True)),
))
db.send_create_signal('admin', ['Extension'])
def backwards(self, orm):
# Deleting model 'Extension'
db.delete_table('admin_extension')
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,96 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
class Migration(DataMigration):
def forwards(self, orm):
perm_ct = ContentType.objects.get(app_label="auth", model="permission")
view_perms = Permission(name="View permissions", codename="view_permissions",
content_type=perm_ct)
view_perms.save()
def backwards(self, orm):
p = orm.Permission.objects.get(codename="view_permissions")
p.delete()
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin', 'contenttypes']
@@ -0,0 +1,90 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.alter_column("auth_user", "username", models.CharField(unique=True, max_length=254))
db.alter_column("auth_user", "email", models.CharField(max_length=254))
def backwards(self, orm):
raise RuntimeError("Cannot revert this migration")
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,112 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'DomainAlias'
db.create_table('admin_domainalias', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=100)),
('target', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['admin.Domain'])),
('enabled', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal('admin', ['DomainAlias'])
def backwards(self, orm):
# Deleting model 'DomainAlias'
db.delete_table('admin_domainalias')
grp = orm["auth.Group"].objects.get(name="DomainAdmins")
for pcode in ["view_domaliases", "add_domainalias", "change_domainalias",
"delete_domainalias"]:
grp.permissions.remove(orm["auth.Permissions"].objects.get(codename=pcode))
grp.save()
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,112 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Alias.full_address'
db.delete_column('admin_alias', 'full_address')
# Changing field 'Alias.address'
db.alter_column('admin_alias', 'address', self.gf('django.db.models.fields.CharField')(max_length=254))
# Deleting field 'Mailbox.full_address'
db.delete_column('admin_mailbox', 'full_address')
def backwards(self, orm):
# User chose to not deal with backwards NULL issues for 'Alias.full_address'
raise RuntimeError("Cannot reverse this migration. 'Alias.full_address' and its values cannot be restored.")
# Changing field 'Alias.address'
db.alter_column('admin_alias', 'address', self.gf('django.db.models.fields.CharField')(max_length=100))
# User chose to not deal with backwards NULL issues for 'Mailbox.full_address'
raise RuntimeError("Cannot reverse this migration. 'Mailbox.full_address' and its values cannot be restored.")
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,97 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
for mb in orm.Mailbox.objects.all():
mb.path = mb.path.replace(mb.domain.name + "/", "", 1)
mb.save()
def backwards(self, orm):
raise RuntimeError("Cannot revert this migration")
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,103 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Alias.extmboxes'
db.add_column('admin_alias', 'extmboxes', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False)
db.add_column('admin_alias', 'domain', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['admin.Domain'], default=-1))
def backwards(self, orm):
# Deleting field 'Alias.extmboxes'
db.delete_column('admin_alias', 'extmboxes')
db.delete_column('admin_alias', 'domain')
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,100 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for alias in orm.Alias.objects.all():
alias.domain = alias.mboxes.all()[0].domain
alias.save()
def backwards(self, orm):
"Write your backwards methods here."
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,141 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ObjectDates'
db.create_table('admin_objectdates', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('creation', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('last_modification', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
))
db.send_create_signal('admin', ['ObjectDates'])
# Adding field 'Domain.dates'
db.add_column('admin_domain', 'dates', self.gf('django.db.models.fields.related.ForeignKey')(default=-1, to=orm['admin.ObjectDates']), keep_default=False)
# Adding field 'DomainAlias.dates'
db.add_column('admin_domainalias', 'dates', self.gf('django.db.models.fields.related.ForeignKey')(default=-1, to=orm['admin.ObjectDates']), keep_default=False)
# Adding field 'Alias.dates'
db.add_column('admin_alias', 'dates', self.gf('django.db.models.fields.related.ForeignKey')(default=-1, to=orm['admin.ObjectDates']), keep_default=False)
# Adding field 'Mailbox.dates'
db.add_column('admin_mailbox', 'dates', self.gf('django.db.models.fields.related.ForeignKey')(default=-1, to=orm['admin.ObjectDates']), keep_default=False)
def backwards(self, orm):
# Deleting model 'ObjectDates'
db.delete_table('admin_objectdates')
# Deleting field 'Domain.dates'
db.delete_column('admin_domain', 'dates_id')
# Deleting field 'DomainAlias.dates'
db.delete_column('admin_domainalias', 'dates_id')
# Deleting field 'Alias.dates'
db.delete_column('admin_alias', 'dates_id')
# Deleting field 'Mailbox.dates'
db.delete_column('admin_mailbox', 'dates_id')
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,121 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
def create_od(orm, obj):
od = orm.ObjectDates()
od.save()
obj.dates = od
obj.save()
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for domain in orm.Domain.objects.all():
create_od(orm, domain)
for domalias in orm.DomainAlias.objects.all():
create_od(orm, domainalias)
for mbox in orm.Mailbox.objects.all():
create_od(orm, mbox)
for mbalias in orm.Alias.objects.all():
create_od(orm, mbalias)
def backwards(self, orm):
"Write your backwards methods here."
orm.ObjectDates.objects.all().delete()
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['admin.ObjectDates']", 'unique': 'True'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['admin.ObjectDates']", 'unique': 'True'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['admin.ObjectDates']", 'unique': 'True'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['admin.ObjectDates']", 'unique': 'True'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,110 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for mb in orm.Mailbox.objects.all():
mb.path = "%s/" % mb.address
mb.save()
def backwards(self, orm):
"Write your backwards methods here."
raise RuntimeError("Cannot reverse this migration.")
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,112 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'Domain', fields ['name']
db.create_unique('admin_domain', ['name'])
def backwards(self, orm):
# Removing unique constraint on 'Domain', fields ['name']
db.delete_unique('admin_domain', ['name'])
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,116 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from modoboa.lib.models import Parameter
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
try:
s = Parameter.objects.get(name='admin.PASSWORD_SCHEME').value
except Parameter.DoesNotExist:
s = "crypt"
for mb in orm.Mailbox.objects.all():
mb.user.password = '{%s}%s' % (s.upper(), mb.password)
mb.user.save()
def backwards(self, orm):
"Write your backwards methods here."
raise RuntimeError("Cannot reverse this migration.")
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin', 'auth']
@@ -0,0 +1,133 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ObjectAccess'
db.create_table('admin_objectaccess', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
('object_id', self.gf('django.db.models.fields.PositiveIntegerField')()),
('is_owner', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal('admin', ['ObjectAccess'])
# Adding unique constraint on 'ObjectAccess', fields ['user', 'content_type', 'object_id']
db.create_unique('admin_objectaccess', ['user_id', 'content_type_id', 'object_id'])
# Deleting field 'Mailbox.password'
db.delete_column('admin_mailbox', 'password')
# Deleting field 'Mailbox.name'
db.delete_column('admin_mailbox', 'name')
def backwards(self, orm):
raise RuntimeError("Cannot reverse this migration.")
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectaccess': {
'Meta': {'unique_together': "(('user', 'content_type', 'object_id'),)", 'object_name': 'ObjectAccess'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_owner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'admin.user': {
'Meta': {'object_name': 'User', 'db_table': "'auth_user'", '_ormbases': ['auth.User'], 'proxy': 'True'}
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,177 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
class Migration(DataMigration):
def grant_access(self, orm, user, ct, obj, is_owner=False):
objaccess = orm["admin.ObjectAccess"](
user=user, content_type=ct, object_id=obj.id
)
objaccess.is_owner = is_owner
objaccess.save()
def forwards(self, orm):
superusers = orm["auth.User"].objects.filter(is_superuser=True)
if not len(superusers):
# Empty db, nothing to do
return
# 1: all superadmins must be able to access every defined
# object. (user, domain, domain alias, mailbox, alias)
try:
uct = orm['contenttypes.ContentType'].objects.get(
app_label='admin', model='user'
)
except ObjectDoesNotExist:
uct = orm['contenttypes.ContentType'](
name='user', app_label='admin', model='user'
)
uct.save()
for account in orm["admin.User"].objects.all():
for i, su in enumerate(superusers):
self.grant_access(orm, su, uct, account, i == 0)
domct = orm['contenttypes.ContentType'].objects.get(
app_label='admin', model='domain'
)
for dom in orm["admin.Domain"].objects.all():
for i, su in enumerate(superusers):
self.grant_access(orm, su, domct, dom, i == 0)
dalct = orm['contenttypes.ContentType'].objects.get(
app_label='admin', model='domainalias'
)
for domalias in orm["admin.DomainAlias"].objects.all():
for i, su in enumerate(superusers):
self.grant_access(orm, su, dalct, domalias, i == 0)
mbct = orm['contenttypes.ContentType'].objects.get(
app_label='admin', model='mailbox'
)
for mb in orm["admin.Mailbox"].objects.all():
for i, su in enumerate(superusers):
self.grant_access(orm, su, mbct, mb, i == 0)
alct = orm['contenttypes.ContentType'].objects.get(
app_label='admin', model='alias'
)
for alias in orm["admin.Alias"].objects.all():
for i, su in enumerate(superusers):
self.grant_access(orm, su, alct, alias, i == 0)
# 2: domain admins must have access to their domain's content
for da in orm["admin.User"].objects.filter(groups__name='DomainAdmins'):
dom = da.mailbox_set.all()[0].domain
self.grant_access(orm, da, domct, dom)
for mb in dom.mailbox_set.all():
self.grant_access(orm, da, mbct, mb)
self.grant_access(orm, da, uct, mb.user)
for al in dom.alias_set.all():
self.grant_access(orm, da, alct, al)
def backwards(self, orm):
"Write your backwards methods here."
raise RuntimeError("Cannot revert this migration")
models = {
'admin.alias': {
'Meta': {'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectaccess': {
'Meta': {'unique_together': "(('user', 'content_type', 'object_id'),)", 'object_name': 'ObjectAccess'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_owner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'admin.user': {
'Meta': {'object_name': 'User', 'db_table': "'auth_user'", '_ormbases': ['auth.User'], 'proxy': 'True'}
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['contenttypes', 'admin']
@@ -0,0 +1,121 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'Alias', fields ['domain', 'address']
db.create_unique('admin_alias', ['domain_id', 'address'])
def backwards(self, orm):
# Removing unique constraint on 'Alias', fields ['domain', 'address']
db.delete_unique('admin_alias', ['domain_id', 'address'])
models = {
'admin.alias': {
'Meta': {'unique_together': "(('address', 'domain'),)", 'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectaccess': {
'Meta': {'unique_together': "(('user', 'content_type', 'object_id'),)", 'object_name': 'ObjectAccess'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_owner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'admin.user': {
'Meta': {'object_name': 'User', 'db_table': "'auth_user'", '_ormbases': ['auth.User'], 'proxy': 'True'}
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
@@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
try:
sugroup = orm["auth.Group"].objects.get(name="SimpleUsers")
except orm["auth.Group"].DoesNotExist:
sugroup = orm["auth.Group"](name="SimpleUsers")
sugroup.save()
for account in orm["auth.User"].objects.all():
if not len(account.groups.all()):
account.groups.add(sugroup)
account.save()
def backwards(self, orm):
"Write your backwards methods here."
raise RuntimeError("Cannot reverse this migration")
models = {
'admin.alias': {
'Meta': {'unique_together': "(('address', 'domain'),)", 'object_name': 'Alias'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extmboxes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mboxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['admin.Mailbox']", 'symmetrical': 'False'})
},
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.domainalias': {
'Meta': {'object_name': 'DomainAlias'},
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"})
},
'admin.extension': {
'Meta': {'object_name': 'Extension'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'dates': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.ObjectDates']"}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectaccess': {
'Meta': {'unique_together': "(('user', 'content_type', 'object_id'),)", 'object_name': 'ObjectAccess'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_owner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'admin.objectdates': {
'Meta': {'object_name': 'ObjectDates'},
'creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['admin']
symmetrical = True
+900
View File
@@ -0,0 +1,900 @@
# coding: utf-8
from django.db import models, IntegrityError
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User as DUser, UserManager, Group
from django.utils.translation import ugettext as _, ugettext_lazy
from django.utils.crypto import constant_time_compare
from django.conf import settings
from modoboa.lib import parameters, events
from modoboa.lib.exceptions import PermDeniedException
from modoboa.lib.sysutils import exec_cmd, exec_as_vuser
from modoboa.lib.emailutils import split_mailbox
from modoboa.extensions import exts_pool
from exceptions import *
import os, sys
import pwd
import re
import crypt, hashlib, string, base64
from random import Random
try:
from modoboa.lib.ldaputils import *
ldap_available = True
except ImportError:
ldap_available = False
class User(DUser):
"""Proxy for the ``User`` model.
It overloads the way passwords are stored into the database. The
main reason to change this mechanism is to ensure the
compatibility with the way Dovecot stores passwords.
It also adds new attributes and methods.
"""
class Meta:
proxy = True
ordering = ["username"]
password_expr = re.compile(r'\{(\w+)\}(.+)')
def __init__(self, *args, **kwargs):
"""Constructor
A little hack to increase the maximum length for the username
field.
"""
max_length = 254
DUser._meta.get_field('username').max_length = max_length
DUser._meta.get_field('username').validators[0].limit_value = 254
super(User, self).__init__(*args, **kwargs)
def __unicode__(self):
return u"%s %s" % (self.first_name, self.last_name)
def delete(self, fromuser, keep_mb_dir, *args, **kwargs):
"""Custom delete method
To check permissions properly, we need to make a distinction
between 2 cases:
* If the user owns a mailbox, the check is made on that object
(useful for domain admins)
* Otherwise, the check is made on the user
"""
from modoboa.lib.permissions import \
get_object_owner, grant_access_to_object, ungrant_access_to_object
if fromuser == self:
raise AdminError(_("You can't delete your own account"))
if not fromuser.can_access(self):
raise PermDeniedException
if self.has_mailbox:
mb = self.mailbox_set.all()[0]
if not fromuser.can_access(mb):
raise PermDeniedException
mb.delete(keepdir=keep_mb_dir)
owner = get_object_owner(self)
for ooentry in self.objectaccess_set.filter(is_owner=True):
if ooentry.content_object is not None:
grant_access_to_object(owner, ooentry.content_object, True)
events.raiseEvent("AccountDeleted", self)
ungrant_access_to_object(self)
super(User, self).delete(*args, **kwargs)
@staticmethod
def get_content_type():
"""An uggly hack to retrieve the appropriate content_type!
The explanation is available here:
https://code.djangoproject.com/ticket/11154
Quickly, the content_types framework does not retrieve the
appropriate content type for proxy models, it retrieves the
one of the first parent that is not a proxy.
"""
if not hasattr(User, "ct"):
User.ct = ContentType.objects.get(app_label="admin", model="user")
return User.ct
def _crypt_password(self, raw_value):
scheme = parameters.get_admin("PASSWORD_SCHEME")
if scheme == "crypt":
salt = ''.join(Random().sample(string.letters + string.digits, 2))
result = crypt.crypt(raw_value, salt)
elif scheme == "md5":
obj = hashlib.md5(raw_value)
result = obj.hexdigest()
elif scheme == "sha256":
obj = hashlib.sha256(raw_value)
result = base64.b64encode(obj.digest())
else:
scheme = "plain"
result = raw_value
return "{%s}%s" % (scheme.upper(), result)
def set_password(self, raw_value, curvalue=None):
"""Password update
Update the current mailbox's password with the given clear
value. This value is encrypted according to the defined method
before it is saved.
:param raw_value: the new password's value
:param curvalue: the current password (for LDAP authentication)
"""
if parameters.get_admin("AUTHENTICATION_TYPE") == "local":
self.password = self._crypt_password(raw_value)
return
if not ldap_available:
raise AdminError(_("Failed to update password: LDAP module not installed"))
ab = LDAPAuthBackend()
try:
ab.update_user_password(self.username, curvalue, raw_value)
except LDAPException, e:
raise AdminError(_("Failed to update password: %s" % str(e)))
def check_password(self, raw_value):
m = self.password_expr.match(self.password)
if m is None:
return False
scheme = m.group(1).lower()
val2 = m.group(2)
if scheme == "crypt":
val1 = crypt.crypt(raw_value, m.group(2))
elif scheme == "md5":
val1 = hashlib.md5(raw_value).hexdigest()
elif scheme == "sha256":
val1 = base64.b64encode(hashlib.sha256(raw_value).digest())
else:
val1 = raw_value
return constant_time_compare(val1, val2)
@property
def has_mailbox(self):
return len(self.mailbox_set.all()) != 0
@property
def fullname(self):
if self.first_name != "":
return "%s %s" % (self.first_name, self.last_name)
return self.username
@property
def identity(self):
return self.username
@property
def name_or_rcpt(self):
if self.first_name != "":
return "%s %s" % (self.first_name, self.last_name)
return "----"
@property
def group(self):
if self.is_superuser:
return "SuperAdmins"
try:
return self.groups.all()[0].name
except IndexError:
return "?"
def belongs_to_group(self, name):
"""Simple shortcut to check if this user is a member of a
specific group.
:param name: the group's name
:return: a boolean
"""
try:
self.groups.get(name=name)
except Group.DoesNotExist:
return False
return True
def get_identities(self):
from modoboa.lib.permissions import get_content_type
userct = get_content_type(self)
alct = get_content_type(Alias)
return self.objectaccess_set.filter(content_type__in=[userct, alct])
def get_domains(self):
"""Return the domains belonging to this user
The result is a ``QuerySet`` object, so this function can be used
to fill ``ModelChoiceField`` objects.
"""
if self.is_superuser:
return Domain.objects.all()
return Domain.objects.filter(owners__user=self)
def get_domaliases(self):
"""Return the domain aliases that belong to this user
The result will contain the domain aliases defined for each domain
that user can see.
:return: a list of ``DomainAlias`` objects
"""
if self.is_superuser:
return DomainAlias.objects.all()
domains = self.get_domains()
domaliases = []
for dom in domains:
domaliases += dom.domainalias_set.all()
return domaliases
def get_mailboxes(self):
"""Return the mailboxes that belong to this user
The result will contain the mailboxes defined for each domain that
user can see.
:return: a list of ``Mailbox`` objects
"""
if self.is_superuser:
return Mailbox.objects.all()
mboxes = []
domains = self.get_domains()
for dom in domains:
mboxes += dom.mailbox_set.all()
return mboxes
def get_mbaliases(self):
"""Return the mailbox aliases that belong to this user
The result will contain the mailbox aliases defined for each
domain that user can see.
:return: a list of ``Alias`` objects
"""
if self.is_superuser:
return Alias.objects.all()
domains = self.get_domains()
mbaliases = []
for dom in domains:
mbaliases += dom.alias_set.all()
return mbaliases
def is_owner(self, obj):
"""Tell is the user is the unique owner of this object
:param obj: an object inheriting from ``models.Model``
:return: a boolean
"""
from modoboa.lib.permissions import get_content_type
ct = get_content_type(obj)
try:
ooentry = self.objectaccess_set.get(content_type=ct, object_id=obj.id)
except ObjectAccess.DoesNotExist:
return False
return ooentry.is_owner
def can_access(self, obj):
"""Check if the user can access a specific object
This function is recursive : if the given user hasn't got direct
access to this object and if he has got access other ``User``
objects, we check if one of those users owns the object.
:param obj: a admin object
:return: a boolean
"""
from modoboa.lib.permissions import get_content_type
if self.is_superuser:
return True
ct = get_content_type(obj)
try:
ooentry = self.objectaccess_set.get(content_type=ct, object_id=obj.id)
except ObjectAccess.DoesNotExist:
pass
else:
return True
if ct.model == "user":
return False
ct = self.get_content_type()
qs = self.objectaccess_set.filter(content_type=ct)
for ooentry in qs.all():
if ooentry.content_object.is_owner(obj):
return True
return False
class ObjectAccess(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
is_owner = models.BooleanField(default=False)
class Meta:
unique_together = (("user", "content_type", "object_id"),)
def __unicode__(self):
return "%s => %s (%s)" % (self.user, self.content_object, self.content_type)
class ObjectDates(models.Model):
"""Dates recording for admin objects
This table keeps creation and last modification dates for Domains,
domain aliases, mailboxes and aliases objects.
"""
creation = models.DateTimeField(auto_now_add=True)
last_modification = models.DateTimeField(auto_now=True)
@staticmethod
def set_for_object(obj):
"""Initialize or update dates for a given object.
:param obj: an admin object (Domain, Mailbox, etc)
"""
try:
dates = getattr(obj, "dates")
except ObjectDates.DoesNotExist:
dates = ObjectDates()
dates.save()
obj.dates = dates
class DatesAware(models.Model):
"""Abstract model to support dates
Inherit from this model to automatically add the "dates" feature
to another model. It defines the appropriate field and handles
saves.
"""
dates = models.ForeignKey(ObjectDates)
class Meta:
abstract = True
def save(self, *args, **kwargs):
ObjectDates.set_for_object(self)
super(DatesAware, self).save(*args, **kwargs)
@property
def creation(self):
return self.dates.creation
@property
def last_modification(self):
return self.dates.last_modification
class Domain(DatesAware):
name = models.CharField(ugettext_lazy('name'), max_length=100, unique=True,
help_text=ugettext_lazy("The domain name"))
quota = models.IntegerField(help_text=ugettext_lazy("Default quota in MB applied to mailboxes"))
enabled = models.BooleanField(ugettext_lazy('enabled'),
help_text=ugettext_lazy("Check to activate this domain"))
owners = generic.GenericRelation(ObjectAccess)
class Meta:
permissions = (
("view_domain", "View domain"),
("view_domains", "View domains"),
)
ordering = ["name"]
@property
def domainalias_count(self):
return len(self.domainalias_set.all())
@property
def mailbox_count(self):
return len(self.mailbox_set.all())
@property
def mbalias_count(self):
return len(self.alias_set.all())
@property
def admins(self):
return [oa.user for oa in self.owners.filter(user__is_superuser=False)]
def create_dir(self):
if parameters.get_admin("CREATE_DIRECTORIES") == "yes":
path = "%s/%s" % (parameters.get_admin("STORAGE_PATH"), self.name)
return exec_as_vuser("mkdir -p %s" % path)
return True
def rename_dir(self, oldname):
if parameters.get_admin("CREATE_DIRECTORIES") == "yes":
stpath = parameters.get_admin("STORAGE_PATH")
return exec_as_vuser("mv %s/%s %s/%s" \
% (stpath, oldname, stpath, self.name))
return True
def delete_dir(self):
if parameters.get_admin("CREATE_DIRECTORIES") == "yes":
return exec_as_vuser("rm -r %s/%s" \
% (parameters.get_admin("STORAGE_PATH"),
self.name))
return True
def delete(self, keepdir=False):
from modoboa.lib.permissions import ungrant_access_to_object, ungrant_access_to_objects
if len(self.domainalias_set.all()):
events.raiseEvent("DomainAliasDeleted", self.domainalias_set.all())
ungrant_access_to_objects(self.domainalias_set.all())
if len(self.mailbox_set.all()):
events.raiseEvent("DeleteMailbox", self.mailbox_set.all())
ungrant_access_to_objects(self.mailbox_set.all())
if len(self.alias_set.all()):
events.raiseEvent("MailboxAliasDelete", self.alias_set.all())
ungrant_access_to_objects(self.alias_set.all())
events.raiseEvent("DeleteDomain", self)
ungrant_access_to_object(self)
super(Domain, self).delete()
if not keepdir:
self.delete_dir()
def save(self, *args, **kwargs):
if not self.create_dir():
raise AdminError(_("Failed to initialise domain, check permissions"))
super(Domain, self).save(*args, **kwargs)
def __str__(self):
return self.name
def create_from_csv(self, user, row):
if len(row) < 3:
raise AdminError(_("Invalid line"))
self.name = row[1].strip()
self.quota = int(row[2].strip())
self.enabled = True
self.save()
class DomainAlias(DatesAware):
name = models.CharField(ugettext_lazy("name"), max_length=100, unique=True,
help_text=ugettext_lazy("The alias name"))
target = models.ForeignKey(Domain, verbose_name=ugettext_lazy('target'),
help_text=ugettext_lazy("The domain this alias points to"))
enabled = models.BooleanField(
ugettext_lazy('enabled'),
help_text=ugettext_lazy("Check to activate this alias")
)
class Meta:
permissions = (
("view_domaliases", "View domain aliases"),
)
def __unicode__(self):
return self.name
def delete(self):
from modoboa.lib.permissions import ungrant_access_to_object
events.raiseEvent("DomainAliasDeleted", self)
ungrant_access_to_object(self)
super(DomainAlias, self).delete()
class Mailbox(DatesAware):
address = models.CharField(
ugettext_lazy('address'), max_length=100,
help_text=ugettext_lazy("Mailbox address (without the @domain.tld part)")
)
quota = models.IntegerField()
uid = models.IntegerField()
gid = models.IntegerField()
path = models.CharField(max_length=255)
domain = models.ForeignKey(Domain)
user = models.ForeignKey(User)
class Meta:
permissions = (
("view_mailboxes", "View mailboxes"),
)
def __init__(self, *args, **kwargs):
super(Mailbox, self).__init__(*args, **kwargs)
self.mbtype = parameters.get_admin("MAILBOX_TYPE")
self.mdirroot = parameters.get_admin("MAILDIR_ROOT")
if not self.mdirroot.endswith('/'):
self.mdirroot += '/'
def __str__(self):
return self.full_address
@property
def full_address(self):
return "%s@%s" % (self.address, self.domain.name)
@property
def enabled(self):
return self.user.is_active
@property
def full_path(self):
path = os.path.join(parameters.get_admin("STORAGE_PATH"),
self.domain.name, self.address)
return os.path.abspath(path)
@property
def alias_count(self):
return len(self.alias_set.all())
def create_dir(self):
if self.mbtype == "mbox":
self.path = "%s/Inbox" % self.address
else:
self.path = "%s/" % self.address
if parameters.get_admin("CREATE_DIRECTORIES") == "yes":
relpath = "%s/%s" % (self.domain.name, self.address)
abspath = os.path.join(parameters.get_admin("STORAGE_PATH"), relpath)
if os.path.exists(abspath):
return True
if not exec_as_vuser("mkdir -p %s" % abspath):
return False
if self.mbtype == "mbox":
template = ["Inbox", "Drafts", "Sent", "Trash", "Junk"]
for f in template:
exec_as_vuser("touch %s/%s" % (abspath, f))
else:
template = [".Drafts/", ".Sent/", ".Trash/", ".Junk/"]
for dir in template:
for sdir in ["cur", "new", "tmp"]:
exec_as_vuser("mkdir -p %s/%s/%s/%s" \
% (abspath, self.mdirroot, dir, sdir))
return True
def rename_dir(self, newdomain, newaddress):
if parameters.get_admin("CREATE_DIRECTORIES") == "yes":
if self.domain.name == newdomain and newaddress == self.address:
return True
oldpath = "%s/%s" % (parameters.get_admin("STORAGE_PATH"), self.domain.name)
newpath = "%s/%s" % (parameters.get_admin("STORAGE_PATH"), newdomain)
oldpath = os.path.join(oldpath, self.address)
newpath = os.path.join(newpath, newaddress)
code = exec_as_vuser("mv %s %s" % (oldpath, newpath))
if code:
self.path = "%s/" % newaddress
return code
else:
self.path ="%s/" % newaddress
return True
def delete_dir(self):
if parameters.get_admin("CREATE_DIRECTORIES") == "yes":
return exec_as_vuser("rm -r %s/%s/%s" \
% (parameters.get_admin("STORAGE_PATH"),
self.domain.name, self.address))
return True
def set_ownership(self):
# If we ever had numerical uid, don't resolve it
v_uid = parameters.get_admin("VIRTUAL_UID");
if v_uid.isdigit():
self.uid = v_uid
else:
try:
self.uid = pwd.getpwnam(v_uid).pw_uid
except KeyError:
raise AdminError(_("%s is not a valid uid/username" % v_uid))
# Just the same for gid
v_gid = parameters.get_admin("VIRTUAL_GID")
if v_gid.isdigit():
self.gid = v_gid
else:
try:
self.gid = pwd.getpwnam(v_gid).pw_gid
except KeyError:
raise AdminError(_("%s is not a valid gid/groupname" % v_gid))
def save(self, *args, **kwargs):
if not self.create_dir():
raise AdminError(_("Failed to initialise mailbox, check permissions"))
try:
user = getattr(self, "user")
except User.DoesNotExist:
user = User()
user.email = "%s@%s" % (self.address, self.domain.name)
if kwargs.has_key("username"):
user.username = kwargs["username"]
else:
user.username = user.email
if kwargs.has_key("enabled"):
user.is_active = kwargs["enabled"]
if kwargs.has_key("name"):
try:
fname, lname = kwargs["name"].split()
except ValueError:
fname = kwargs["name"]
lname = ""
user.first_name = fname
user.last_name = lname
if kwargs.has_key("password"):
user.set_password(kwargs["password"])
try:
user.save()
except IntegrityError, e:
raise AdminError(_("Account '%s' already exists" % user.username))
self.user = user
if len(user.groups.all()) == 0:
user.groups.add(Group.objects.get(name="SimpleUsers"))
user.save()
self.set_ownership()
if kwargs.has_key("quota") and kwargs["quota"] is not None \
and int(kwargs["quota"]) < self.domain.quota:
self.quota = kwargs["quota"]
else:
self.quota = self.domain.quota
for kw in ["username", "name", "enabled", "password", "quota"]:
try:
del kwargs[kw]
except KeyError:
pass
super(Mailbox, self).save(*args, **kwargs)
def save_from_user(self, localpart, domain, user, quota=None):
"""Simple save method called for automatic creations
:param localpart: the mailbox
:param domain: the associated Domain object
:param user: the associated User object
"""
self.address = localpart
self.domain = domain
self.user = user
if not self.create_dir():
raise AdminError(_("Failed to initialise mailbox, check permissions"))
self.set_ownership()
self.quota = self.domain.quota if quota is None else quota
super(Mailbox, self).save()
def create_from_csv(self, user, line):
"""Create a new mailbox from a CSV file entry
The expected order is the following::
[loginname, password, first name, last name, address]
:param line: a list containing the expected information
"""
if len(line) < 6:
raise AdminError(_("Invalid line"))
mailbox, domname = split_mailbox(line[5].strip())
self.address = mailbox
try:
self.domain = Domain.objects.get(name=domname)
except Domain.DoesNotExist:
raise AdminError(_("Cannot import this mailbox because the associated domain does not exist"))
if not user.can_access(self.domain):
raise PermDeniedException
name = "%s %s" % (line[3].strip(), line[4].strip())
self.save(username=line[1].strip(), name=name,
password=line[2].strip(), enabled=True)
def delete(self, keepdir=False):
from modoboa.lib.permissions import ungrant_access_to_object
events.raiseEvent("DeleteMailbox", self)
ungrant_access_to_object(self)
for alias in self.alias_set.all():
alias.mboxes.remove(self)
if len(alias.mboxes.all()) == 0:
alias.delete()
super(Mailbox, self).delete()
if not keepdir:
self.delete_dir()
class Alias(DatesAware):
address = models.CharField(
ugettext_lazy('address'), max_length=254,
help_text=ugettext_lazy("The alias address (without the domain part). For a 'catch-all' address, just enter an * character.")
)
domain = models.ForeignKey(Domain)
mboxes = models.ManyToManyField(
Mailbox, verbose_name=ugettext_lazy('mailboxes'),
help_text=ugettext_lazy("The mailboxes this alias points to")
)
extmboxes = models.TextField(blank=True)
enabled = models.BooleanField(ugettext_lazy('enabled'),
help_text=ugettext_lazy("Check to activate this alias"))
class Meta:
permissions = (
("view_aliases", "View aliases"),
)
unique_together = (("address", "domain"),)
ordering = ["domain__name", "address"]
@property
def full_address(self):
return "%s@%s" % (self.address, self.domain.name)
@property
def identity(self):
return self.full_address
@property
def name_or_rcpt(self):
rcpts = self.get_recipients()
if len(rcpts) > 1:
return "%s, ..." % rcpts[0]
return rcpts[0]
def save(self, int_rcpts, ext_rcpts, *args, **kwargs):
if len(ext_rcpts):
self.extmboxes = ",".join(ext_rcpts)
else:
self.extmboxes = ""
super(Alias, self).save(*args, **kwargs)
curmboxes = self.mboxes.all()
for t in int_rcpts:
if not t in curmboxes:
self.mboxes.add(t)
for t in curmboxes:
if not t in int_rcpts:
self.mboxes.remove(t)
def delete(self):
from modoboa.lib.permissions import ungrant_access_to_object
events.raiseEvent("MailboxAliasDeleted", self)
ungrant_access_to_object(self)
super(Alias, self).delete()
def get_recipients(self):
"""Return the recipients list
Internal and external addresses are mixed into a single list.
"""
result = map(lambda mb: mb.full_address, self.mboxes.all())
if self.extmboxes != "":
result += self.extmboxes.split(',')
return result
def ui_disabled(self, user):
if user.is_superuser:
return False
for mb in self.mboxes.all():
if not user.is_owner(mb.domain):
return True
return False
def create_from_csv(self, user, row):
if len(row) < 4:
raise AdminError(_("Invalid line"))
localpart, domname = split_mailbox(row[1].strip())
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.address = localpart
self.domain = domain
self.enabled = True
int_rcpts = []
ext_rcpts = []
for rcpt in row[2:]:
rcpt = rcpt.strip()
localpart, domname = split_mailbox(rcpt)
try:
Domain.objects.get(name=domname)
except Domain.DoesNotExist:
ext_rcpts += [rcpt]
continue
try:
int_rcpts += [Mailbox.objects.get(address=localpart,
domain__name=domname)]
except Mailbox.DoesNotExist:
raise AdminError(_("Mailbox %s does not exist" % rcpt))
self.save(int_rcpts, ext_rcpts)
class Extension(models.Model):
name = models.CharField(max_length=150)
enabled = models.BooleanField(
ugettext_lazy('enabled'),
help_text=ugettext_lazy("Check to enable this extension")
)
def __init__(self, *args, **kwargs):
super(Extension, self).__init__(*args, **kwargs)
def __get_ext_instance(self):
if not self.name:
return None
if hasattr(self, "instance") and self.instance:
return
self.instance = exts_pool.get_extension(self.name)
if self.instance:
self.__get_ext_dir()
def __get_ext_dir(self):
modname = self.instance.__module__
path = os.path.realpath(sys.modules[modname].__file__)
self.extdir = os.path.dirname(path)
def on(self):
self.enabled = True
self.save()
self.__get_ext_instance()
self.instance.load()
self.instance.init()
if self.instance.needs_media:
path = os.path.join(settings.MEDIA_ROOT, self.name)
exec_cmd("mkdir %s" % path)
scriptdir = "%s/%s" % (self.extdir, "scripts")
if os.path.exists(scriptdir):
targetdir = os.path.join(settings.MODOBOA_DIR, "scripts")
exec_cmd("ln -s %s %s/%s" % (scriptdir, targetdir, self.name))
events.raiseEvent("ExtEnabled", self)
def off(self):
self.__get_ext_instance()
self.instance.destroy()
self.enabled = False
self.save()
if self.instance.needs_media:
path = os.path.join(settings.MEDIA_ROOT, self.name)
exec_cmd("rm -r %s" % path)
scriptdir = "%s/%s" % (self.extdir, "scripts")
if os.path.exists(scriptdir):
target = "%s/scripts/%s" % (settings.MODOBOA_DIR, self.name)
exec_cmd("rm %s" % target)
events.raiseEvent("ExtDisabled", self)
def populate_callback(sender, user=None, **kwargs):
"""Populate signal callback
If the LDAP authentication backend is in use, this callback will
be called each time a new user authenticates succesfuly to
Modoboa. This function is in charge of creating the mailbox
associated to the provided ``User`` object.
:param sender: ??
:param user: a ``User`` instance
"""
if parameters.get_admin("AUTHENTICATION_TYPE") != "ldap":
return
if user is None:
return
localpart, domname = split_mailbox(user.username)
try:
domain = Domain.objects.get(name=domname)
except Domain.DoesNotExist:
domain = Domain()
domain.name = domname
domain.enabled = True
domain.quota = 0
domain.save()
try:
mb = Mailbox.objects.get(domain=domain, address=localpart)
except Mailbox.DoesNotExist:
mb = Mailbox()
mb.save_from_user(localpart, domain, user)
try:
from django_auth_ldap.backend import populate_user
except ImportError, inst:
pass
else:
populate_user.connect(populate_callback, dispatch_uid="myuid")
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python
# coding: utf-8
"""
Simple script to remove useless records from the database (like orphan
User records).
"""
from django.contrib.auth.models import User
from modoboa.admin.models import Mailbox
def dbcleanup():
print "Starting database cleanup"
for user in User.objects.all():
if user.id != 1 and not len(user.mailbox_set.all()):
print "Removing orphan user %s" % user.username
user.delete()
print "Done"
if __name__ == "__main__":
dbcleanup()
+75
View File
@@ -0,0 +1,75 @@
# coding: utf-8
from django.utils.translation import ugettext as _, ugettext_lazy
from modoboa.lib import tables
from templatetags.admin_extras import *
class DomainsTable(tables.Table):
tableid = "objects_table"
idkey = "id"
styles = "table"
name = tables.LinkColumn(
"name", label=ugettext_lazy("Name"),
urlpattern="modoboa.admin.views.editdomain",
title=_("Edit domain"), modal=True, modalcb="domainform_cb"
)
domaliases = tables.Column("domainalias_set",
label=ugettext_lazy("Alias(es)"), safe=True)
actions = tables.ActionColumn("actions", label=ugettext_lazy("Actions"),
defvalue=domain_actions)
cols_order = ["name", "domaliases", "actions"]
def __init__(self, request, doms):
super(DomainsTable, self).__init__(request)
self.populate(self._rows_from_model(doms))
def parse_domainalias_set(self, aliases):
if not len(aliases.all()):
return "---"
res = ""
for da in aliases.all():
res += "%s<br/>" % da.name
return res
def row_class(self, request, domain):
if not domain.enabled:
return "muted"
return ""
class ExtensionsTable(tables.Table):
idkey = "id"
selection = tables.SelectionColumn("selection", width="4%", header=False)
label = tables.Column("label", label=ugettext_lazy("Name"), width="15%")
version = tables.Column("version", label=ugettext_lazy("Version"), width="6%")
descr = tables.Column("description", label=ugettext_lazy("Description"))
cols_order = ["selection", "label", "version", "descr"]
class IdentitiesTable(tables.Table):
idkey = "id"
styles = "table"
identity = tables.LinkColumn(
"identity", label=ugettext_lazy("Email/Username"),
modal=True,
urlpattern={"User" : "modoboa.admin.views.editaccount",
"Alias" : "modoboa.admin.views.editalias_dispatcher"},
modalcb={"User" : "editaccount_cb", "Alias" : "aliasform_cb"}
)
name_or_rcpt = tables.Column("name_or_rcpt", label=ugettext_lazy("Fullname/Recipient"))
actions = tables.ActionColumn("actions", label=ugettext_lazy("Actions"),
defvalue=identity_actions)
cols_order = ["identity", "name_or_rcpt", "actions"]
def __init__(self, request, identities):
super(IdentitiesTable, self).__init__(request)
self.populate(self._rows_from_model(identities, True))
def row_class(self, request, obj):
if obj.__class__.__name__ == "User" and not obj.is_active:
return "muted"
if not obj.enabled:
return "muted"
return ""
@@ -0,0 +1,7 @@
{% extends "common/generic_modal_form.html" %}
{% load libextras %}
{% block formbody %}
{% render_field form.email %}
{% render_fields_group form "recipients" %}
{% render_field form.enabled %}
{% endblock %}
@@ -0,0 +1,5 @@
{% load libextras %}
{% render_field form.name %}
{% render_field form.quota %}
{% render_fields_group form "aliases" %}
{% render_field form.enabled %}
@@ -0,0 +1,23 @@
{% extends "admin/listing.html" %}{% load i18n admin_extras libextras %}
{% block pagetitle %}{% trans "Domains" %}{% endblock %}
{% block html_head %}
{{ block.super }}
<script type="text/javascript">
$(document).ready(function() {
$("a[name=deldomain]").confirm({
question: gettext("Delete this domain?"),
checkboxes: {keepdir: gettext("Do not delete domain directory")}
});
$("#searchquery").focus(function() {
$(this).attr("value", "");
}).blur(function() {
var $this = $(this);
if ($this.attr("value") == "") {
$this.attr("value", gettext("Search"));
}
});
});
</script>
{% endblock %}
{% block leftcol %}<div class="well sidebar-nav">{% include "admin/searchform.html" %}
{% domains_menu "domains" user %}</div>{{ block.super }}{% endblock %}
@@ -0,0 +1,22 @@
{% extends "common/tabforms.html" %}{% load i18n libextras admin_extras %}
{% block extratabs %}
<li><a href="#admins" data-toggle="tab">{% trans "Administrators" %}</a></li>
<li><a href="#misc" data-toggle="tab">{% trans "Miscellaneous" %}</a></li>
{% endblock %}
{% block extratabs_content %}
<div class="tab-pane" id="admins">{% if domadmins %}
<table id="domadmins" class="table table-condensed">
<tr><th>{% trans "Username" %}</th><th>{% trans "Name" %}</th><th></th></tr>
{% for da in domadmins %}<tr>
<td>{{ da.username }}</td><td>{{ da.fullname }}</td><td name="actions">{% domadmin_actions da.id domain.id %}</td>
</tr>{% endfor %}
</table>{% else %}<div class="alert alert-info">{% trans "No domain administrator defined" %}</div>{% endif %}
</div>
<div class="tab-pane" id="misc">
<div class="row"><span class="title">{% trans "Creation date" %}</span><span>{{ domain.creation }}</span></div>
<div class="row"><span class="title">{% trans "Last modification date" %}</span><span>{{ domain.last_modification }}</span></div>
<div class="row"><span class="title">{% trans "Domain aliases" %}</span><span>{{ domain.domainalias_count }}</span></div>
<div class="row"><span class="title">{% trans "Mailboxes" %}</span><span>{{ domain.mailbox_count }}</span></div>
<div class="row"><span class="title">{% trans "Mailbox aliases" %}</span><span>{{ domain.mbalias_count }}</span></div>
</div>
{% endblock %}
@@ -0,0 +1,8 @@
{% extends "admin/settings_header.html" %}{% load i18n %}
{% block pagetitle %}{% trans "Extensions" %}{% endblock %}
{% block apparea %}
<form method="POST" action="{% url modoboa.admin.views.saveextensions %}">
{{ extensions|safe }}
</form>
<a href="#" class="btn btn-primary" id="update" name="update">{% trans 'Save' %}</a>
{% endblock %}
@@ -0,0 +1,5 @@
{% extends "twocols.html" %}
{% block html_head %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/admin.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/admin.js"></script>
{% endblock %}
@@ -0,0 +1,47 @@
{% extends "admin/listing.html" %}{% load admin_extras libextras i18n %}
{% block pagetitle %}{% trans "Identities" %}{% endblock %}
{% block html_head %}
{{ block.super }}
<script type="text/javascript" src="{{ STATIC_URL }}js/creation_wizard.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/autocompleter.js"></script>
<script type="text/javascript">
function get_domains_list(container) {
$.getJSON("{% url modoboa.admin.views.domains_list %}", function(data) {
container.value = data;
});
}
function get_account_list(container) {
$.getJSON("{% url modoboa.admin.views.accounts_list %}", function(data) {
container.value = data;
});
}
function get_mboxes_list(container) {
$.getJSON("{% url modoboa.admin.views.mboxes_list %}", function(data) {
container.value = data;
});
}
$(document).ready(function() {
$("a[name=delaccount]").confirm({
question: gettext("Delete this account?"),
checkboxes: {keepdir: gettext("Do not delete mailbox directory")}
});
$("a[name=deldlist]").confirm({
question: gettext("Delete this list?")
});
$("a[name=delforward]").confirm({
question: gettext("Delete this forward?")
});
$("a[name=delalias]").confirm({
question: gettext("Delete this alias?")
});
$("#pagination_bar").find(".disabled").click(function(e) {
e.preventDefault();
});
});
</script>
{% endblock %}
{% block leftcol %}<div class="well sidebar-nav">{% include "admin/searchform.html" %}
{% identities_menu user %}</div>{{ block.super }}{% endblock %}
@@ -0,0 +1,11 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://www.w3.org/2005/10/profile">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
parent.importdone("{{ status }}", "{{ msg }}");
</script>
</head>
<body></body>
</html>
@@ -0,0 +1,15 @@
{% extends "common/generic_modal_form.html" %}
{% load libextras i18n %}
{% block formbody %}
<div class="alert alert-info">
<h4>{% trans "Help" %}</h4>
{{ helptext|safe }}
</div>
{% render_form form %}
<iframe id="import_target" name="import_target" src="#"
style="width:0;height:0;border:0px solid #fff;"></iframe>
<div id="import_status" style="text-align: center;display:none">
<img src="{{STATIC_URL}}css/spinner.gif" /> {% trans "Importing..." %}
</div>
<div id="import_result"></div>
{% endblock %}
@@ -0,0 +1,22 @@
{% extends "admin/header.html" %}{% load i18n admin_extras libextras %}
{% block html_head %}
{{ block.super }}
<script type="text/javascript" src="{{ STATIC_URL }}js/dynamic_input.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#searchquery").focus(function() {
$(this).attr("value", "");
}).blur(function() {
var $this = $(this);
if ($this.attr("value") == "") {
$this.attr("value", {% if squery %}"{{ squery }}"{% else %}"{% trans 'Search' %}"{% endif %});
}
});
});
</script>
{% endblock %}
{% block leftcol %}{% get_extra_admin_content user "leftcol" selection %}{% endblock %}
{% block apparea %}
{{ table|safe }}
{% endblock %}
{% block footerright %}{% pagination_bar page %}{% endblock %}
@@ -0,0 +1,11 @@
{% load i18n %}
{% if target == "permissions" %}
<option value="">{% trans "Choose a value" %}</option>
{% endif %}
{% for mb in mailboxes %}
{% if target == "permissions" %}
<option value='{{ mb.id }}'>{{ mb.name }}</option>
{% else %}
<option value='{{ mb.id }}'>{{ mb.full_address }}</option>
{% endif %}
{% endfor %}
@@ -0,0 +1,4 @@
{% load libextras %}
{% render_field form.email %}
{% render_field form.quota %}
{% render_fields_group form "aliases" %}
@@ -0,0 +1,33 @@
{% load i18n libextras %}
<div class="modal-header">
<a class="close" data-dismiss="modal">x</a>
<h3>{{ title }} / <small>{{ subtitle }}</small></h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="{{ action }}" enctype="{{ enctype }}"
method="POST" id="{{ formid }}" name="{{ formid }}">
<div id="wizard" class="carousel">
<div class="carousel-inner">
{% for step in steps %}
<div id="step{{ forloop.counter }}"
class="item{% if forloop.first %} active{% endif %}">
{% render_form step.form %}
</div>
{% endfor %}
</div>
</div>
</form>
</div>
<div class="modal-footer">
<div class="buttons_list">
{% for step in steps %}
<div id="step{{ forloop.counter }}_buttons"
class="bset{% if forloop.first %} active{% endif %}">
{% for button in step.buttons %}
<a href="#" class="btn {{ button.classes }}">{{ button.label }}</a>
{% endfor %}
</div>
{% endfor %}
<a class="btn" data-dismiss="modal">{% trans "Close" %}</a>
</div>
</div>
@@ -0,0 +1,6 @@
{% extends "common/generic_modal_form.html" %}{% load libextras %}{% block formbody %}
{% render_field form.name %}
{% render_field form.quota %}
{% render_fields_group form "aliases" %}
{% render_field form.enabled %}
{% endblock %}
@@ -0,0 +1,10 @@
{% extends "admin/settings_header.html" %}{% load i18n %}
{% block pagetitle %}{% trans "Parameters" %}{% endblock %}
{% block apparea %}
{% url modoboa.admin.views.saveparameters as action %}
<form method="POST" action="{{ action }}" id="params_form" class="form-horizontal">
{% include "common/parameters.html" %}
</form>
<hr>
<a href="#" class="btn btn-primary" id="update" name="update">{% trans 'Save' %}</a>
{% endblock %}
@@ -0,0 +1,2 @@
{% load libextras %}
{% render_fields_group form "domains" %}
@@ -0,0 +1,6 @@
{% load i18n %}
<form id="searchform" class="form-horizontal">
<input class="search" type="text"
value={% if squery %}"{{ squery }}"{% else %}"{% trans 'Search' %}"{% endif %}
id="searchquery" name="searchquery" />
</form>
@@ -0,0 +1,22 @@
{% extends "twocols.html" %}
{% load i18n libextras admin_extras %}
{% block html_head %}
<script type="text/javascript">
$(document).ready(function() {
$("#update").click(function(evt) {
evt.preventDefault();
var $form = $("form");
$.post($form.attr("action"), $form.serialize(), function(data) {
if (data.status == "ok") {
if (data.reload) {
window.location.reload();
}
$("body").notify("success", data.message, 2000);
}
});
});
});
</script>
{% endblock %}
{% block leftcol %}<div class="well sidebar-nav">{% settings_menu left_selection user %}</div>{% endblock %}
+247
View File
@@ -0,0 +1,247 @@
from django import template
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _, ugettext_lazy
from django.core.urlresolvers import reverse
from modoboa import admin
from modoboa.lib import events
from modoboa.lib.webutils import static_url, render_actions
register = template.Library()
genders = {
"Enabled" : (ugettext_lazy("enabled_m"), ugettext_lazy("enabled_f"))
}
@register.simple_tag
def admin_menu(selection, user):
entries = []
if user.has_perm("admin.view_domains"):
entries += [
{"name" : "domains",
"url" : reverse(admin.views.domains),
"label" : _("Domains")}
]
entries += \
events.raiseQueryEvent("AdminMenuDisplay", "top_menu", user)
if user.has_perm("auth.add_user") or user.has_perm("admin.add_alias"):
entries += [
{"name" : "identities",
"url" : reverse(admin.views.identities),
"label" : _("Identities")},
]
if user.is_superuser:
entries += [
{"name" : "settings",
"label" : _("Modoboa"),
"url" : reverse(admin.views.viewparameters)}
]
if not len(entries):
return ""
return render_to_string("common/menulist.html",
{"entries" : entries, "selection" : selection, "user" : user})
@register.simple_tag
def settings_menu(selection, user):
entries = [
{"name" : "extensions",
"url" : reverse(admin.views.viewextensions),
"label" : _("Extensions"),
"img" : static_url("pics/extensions.png")},
{"name" : "parameters",
"url" : reverse(admin.views.viewparameters),
"img" : static_url("pics/domains.png"),
"label" : _("Parameters")},
]
return render_to_string('common/menu.html', {
"entries" : entries,
"css" : "nav nav-list",
"selection" : selection,
"user" : user
})
@register.simple_tag
def domains_menu(selection, user):
entries = [
{"name" : "newdomain",
"label" : _("Add domain"),
"img" : "icon-plus",
"modal" : True,
"modalcb" : "domainform_cb",
"url" : reverse("modoboa.admin.views.newdomain")},
{"name" : "import",
"label" : _("Import"),
"img" : "icon-folder-open",
"url" : reverse(admin.views.import_domains),
"modal" : True,
"modalcb" : "importform_cb"}
]
return render_to_string('common/menu.html', {
"entries" : entries,
"css" : "nav nav-list",
"selection" : selection,
"user" : user
})
@register.simple_tag
def identities_menu(user):
entries = [
{"name" : "newaccount",
"label" : _("Add account"),
"img" : "icon-plus",
"modal" : True,
"modalcb" : "newaccount_cb",
"url" : reverse(admin.views.newaccount)},
{"name" : "newalias",
"label" : _("Add alias"),
"img" : "icon-plus",
"modal" : True,
"modalcb" : "aliasform_cb",
"url" : reverse(admin.views.newalias)},
{"name" : "newforward",
"label" : _("Add forward"),
"img" : "icon-plus",
"modal" : True,
"modalcb" : "aliasform_cb",
"url" : reverse(admin.views.newforward)},
{"name" : "newdlist",
"label" : _("Add distribution list"),
"img" : "icon-plus",
"modal" : True,
"modalcb" : "aliasform_cb",
"url" : reverse(admin.views.newdlist)},
{"name" : "import",
"label" : _("Import"),
"img" : "icon-folder-open",
"url" : reverse(admin.views.import_identities),
"modal" : True,
"modalcb" : "importform_cb"}
]
return render_to_string('common/menu.html', {
"entries" : entries,
"css" : "nav nav-list",
"user" : user
})
@register.simple_tag
def domain_actions(user, domid):
actions = [
{"name" : "deldomain",
"url" : reverse(admin.views.deldomain) + "?selection=%s" % domid,
"img" : "icon-trash"},
]
return render_actions(actions)
@register.simple_tag
def identity_actions(user, iid):
name, objid = iid.split(':')
if name == "User":
actions = [
{"name" : "delaccount",
"url" : reverse(admin.views.delaccount) + "?selection=%s" % objid,
"img" : "icon-trash",
"title" : _("Delete this account")},
]
else:
from modoboa.admin.models import Alias
alias = Alias.objects.get(pk=objid)
if len(alias.get_recipients()) >= 2:
actions = [
{"name" : "deldlist",
"url" : reverse(admin.views.deldlist) + "?selection=%s" % objid,
"img" : "icon-trash",
"title" : _("Delete this distribution list")},
]
elif alias.extmboxes != "":
actions = [
{"name" : "delforward",
"url" : reverse(admin.views.delforward) + "?selection=%s" % objid,
"img" : "icon-trash",
"title" : _("Delete this forward")},
]
else:
actions = [
{"name" : "delalias",
"url" : reverse(admin.views.delalias) + "?selection=%s" % objid,
"img" : "icon-trash",
"title" : _("Delete this alias")},
]
return render_actions(actions)
@register.simple_tag
def domadmin_actions(daid, domid):
actions = [dict(
name="removeperm",
url=reverse(admin.views.remove_permission) + "?domid=%s&daid=%s" % (domid, daid),
img="icon-trash",
title=_("Remove this permission")
)]
return render_actions(actions)
@register.simple_tag
def loadadminextmenu(user):
menu = events.raiseQueryEvent("AdminMenuDisplay", "admin_menu_box", user)
return render_to_string('common/menulist.html',
{"entries" : menu, "user" : user})
@register.simple_tag
def param(app, definition):
name = "%s.%s" % (app, definition["name"])
value = definition.has_key("value") \
and definition["value"] or definition["deflt"]
result = """<div class='control-group'>
<label class="param-label" for="%s">%s</label>
<div class="param-controls">""" \
% (name, definition.has_key("label") and _(definition["label"])
or definition["name"])
if definition["type"] in ["string", "int"]:
result += """
<input type='text' name='%s' id='%s' value='%s' />""" % (name, name, value)
if definition["type"] == "text":
result += "<textarea name='%s' id='%s'>%s</textarea>" \
% (name, name, value)
if definition["type"] in ["list", "list_yesno"]:
result += """
<select name='%s' id='%s'>""" % (name, name)
values = []
if definition["type"] == "list_yesno":
values = [("yes", _("Yes")), ("no", _("No"))]
else:
if definition.has_key("values"):
values = definition["values"]
for v in values:
selected = ""
if value == v[0]:
selected = " selected='selected'"
result += "<option value='%s'%s>%s</option>\n" % (v[0], selected, v[1].decode("utf-8"))
result += """
</select>
"""
if definition.has_key("help"):
result += """
<p class="help-block">%s</p>
""" % _(definition["help"])
result += """
</div>
</div>
"""
return result
@register.filter
def gender(value, target):
if genders.has_key(value):
trans = target == "m" and genders[value][0] or genders[value][1]
if trans.find("_") == -1:
return trans
return value
@register.simple_tag
def get_extra_admin_content(user, target, currentpage):
res = events.raiseQueryEvent("ExtraAdminContent", user, target, currentpage)
return "".join(res)
+261
View File
@@ -0,0 +1,261 @@
# coding: utf-8
"""
Basic tests for the 'admin' application
=======================================
"""
from django.test import TestCase
from django.test.client import Client
from django.utils import simplejson
from models import *
from modoboa.admin.lib import *
from modoboa.lib import parameters
from modoboa.lib.tests import ModoTestCase
import os
class DomainTestCase(TestCase):
def test(self):
dom = Domain.objects.create(name="test.com", quota=100)
self.assertIsNotNone(dom)
self.assertEqual(dom.name, "test.com")
self.assertEqual(dom.quota, 100)
self.assertEqual(dom.enabled, False)
self.assertEqual(dom.create_dir(), True)
path = os.path.join(parameters.get_admin("STORAGE_PATH"), dom.name)
self.assertEqual(os.path.exists(path), True)
dom.name = "toto.com"
dom.save()
self.assertEqual(dom.name, "toto.com")
path = os.path.join(parameters.get_admin("STORAGE_PATH"), dom.name)
self.assertEqual(os.path.exists(path), True)
dom.delete()
self.assertEqual(os.path.exists(path), False)
class DomainAliasTestCase(ModoTestCase):
fixtures = ["test_content.json"]
def test_model(self):
dom = Domain.objects.get(name="test.com")
domal = DomainAlias()
domal.name = "domalias.net"
domal.target = dom
domal.save()
self.assertEqual(dom.domainalias_count, 1)
domal.name = "domalias.org"
domal.save()
domal.delete()
def test_form(self):
clt = Client()
clt.login(username="admin", password="password")
dom = Domain.objects.get(name="test.com")
values = dict(name=dom.name, quota=dom.quota, enabled=dom.enabled,
aliases="domalias.net", aliases_1="domalias.com")
self.check_ajax_post("/modoboa/admin/domains/1/edit/", values)
self.assertEqual(len(dom.domainalias_set.all()), 2)
del values["aliases_1"]
self.check_ajax_post("/modoboa/admin/domains/1/edit/", values)
self.assertEqual(len(dom.domainalias_set.all()), 1)
class AccountTestCase(ModoTestCase):
fixtures = ["test_content.json",]
def test(self):
values = dict(username="tester@test.com", first_name="Tester", last_name="Toto",
password1="toto", password2="toto", role="SimpleUsers",
is_active=True, email="tester@test.com", stepid=2)
self.check_ajax_post("/modoboa/admin/accounts/new/", values)
account = User.objects.get(username="tester@test.com")
mb = account.mailbox_set.all()[0]
self.assertEqual(mb.full_address, "tester@test.com")
self.assertEqual(os.path.exists(mb.full_path), True)
self.assertEqual(mb.quota, 100)
self.assertEqual(mb.enabled, True)
self.assertEqual(account.username, mb.full_address)
self.assertTrue(account.check_password("toto"))
self.assertEqual(account.first_name, "Tester")
self.assertEqual(account.last_name, "Toto")
self.assertEqual(mb.domain.mailbox_count, 3)
values["email"] = "pouet@test.com"
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % account.id, values)
mb = Mailbox.objects.get(pk=mb.id)
self.assertEqual(mb.path, "%s/" % mb.address)
path = mb.full_path
self.assertEqual(mb.full_address, "pouet@test.com")
self.assertEqual(os.path.exists(path), True)
self.check_ajax_get("/modoboa/admin/accounts/delete/?selection=%d" \
% account.id, {})
self.assertEqual(os.path.exists(path), False)
def test_update_password(self):
"""Password update
Two cases:
* The default admin changes his password (no associated Mailbox)
* A normal user changes his password
"""
self.check_ajax_post("/modoboa/userprefs/changepassword/",
{"oldpassword" : "password",
"newpassword" : "titi", "confirmation" : "titi"})
self.clt.logout()
self.assertEqual(self.clt.login(username="admin", password="titi"), True)
self.assertEqual(self.clt.login(username="user@test.com", password="toto"),
True)
self.check_ajax_post("/modoboa/userprefs/changepassword/",
{"oldpassword" : "toto",
"newpassword" : "tutu", "confirmation" : "tutu"})
self.clt.logout()
self.assertEqual(self.clt.login(username="user@test.com", password="tutu"), True)
class AliasTestCase(ModoTestCase):
fixtures = ["test_content.json"]
def test_alias(self):
user = User.objects.get(username="user@test.com")
values = dict(
username="user@test.com", role="SimpleUsers",
is_active=user.is_active, email="user@test.com",
aliases="toto@test.com", aliases_1="titi@test.com"
)
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % user.id, values)
self.assertEqual(len(user.mailbox_set.all()[0].alias_set.all()), 2)
del values["aliases_1"]
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % user.id, values)
self.assertEqual(len(user.mailbox_set.all()[0].alias_set.all()), 1)
def test_dlist(self):
values = dict(email="all@test.com",
recipients="user@test.com",
recipients_1="admin@test.com",
recipients_2="ext@titi.com",
enabled=True)
self.check_ajax_post("/modoboa/admin/distriblists/new/", values)
user = User.objects.get(username="user@test.com")
self.assertEqual(len(user.mailbox_set.all()[0].alias_set.all()), 1)
admin = User.objects.get(username="admin@test.com")
self.assertEqual(len(admin.mailbox_set.all()[0].alias_set.all()), 1)
dlist = Alias.objects.get(address="all", domain__name="test.com")
self.assertEqual(len(dlist.get_recipients()), 3)
del values["recipients_1"]
self.check_ajax_post("/modoboa/admin/aliases/edit/%d/" % dlist.id,
values)
self.assertEqual(len(dlist.get_recipients()), 2)
self.check_ajax_get("/modoboa/admin/distriblists/delete/?selection=%d" \
% dlist.id, {})
self.assertRaises(Alias.DoesNotExist, Alias.objects.get,
address="all", domain__name="test.com")
def test_forward(self):
values = dict(email="forward@test.com", recipient="rcpt@dest.com")
self.check_ajax_post("/modoboa/admin/forwards/new/", values)
fwd = Alias.objects.get(address="forward", domain__name="test.com")
self.assertEqual(len(fwd.get_recipients()), 1)
values["recipient"] = "rcpt2@dest.com"
self.check_ajax_post("/modoboa/admin/aliases/edit/%d/" % fwd.id,
values)
self.assertEqual(len(fwd.get_recipients()), 1)
self.check_ajax_get("/modoboa/admin/forwards/delete/?selection=%d" \
% fwd.id, {})
self.assertRaises(Alias.DoesNotExist, Alias.objects.get,
address="forward", domain__name="test.com")
class PermissionsTestCase(ModoTestCase):
fixtures = ["test_content.json"]
def setUp(self):
"""
FIXME: je n'arrive pas à générer des données de test incluant
déjà les permissions (cf. table ObjectAccess). C'est pour
cette raison que j'assigne le domaine test.com ici...
"""
from modoboa.lib.permissions import grant_access_to_object
super(PermissionsTestCase, self).setUp()
self.user = User.objects.get(username="user@test.com")
self.values = dict(
username=self.user.username, role="DomainAdmins",
is_active=self.user.is_active, email="user@test.com"
)
self.admin = User.objects.get(username="admin@test.com")
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % self.admin.id, dict(
username=self.admin.username, role="DomainAdmins",
is_active=self.admin.is_active, email="admin@test.com",
password1="", password2="", domains="test.com"
))
def tearDown(self):
self.clt.logout()
def test_domain_admins(self):
self.values["role"] = "DomainAdmins"
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % self.user.id,
self.values)
self.assertEqual(self.user.group == "DomainAdmins", True)
self.values["role"] = "SimpleUsers"
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % self.user.id,
self.values)
self.assertEqual(self.user.group == 'DomainAdmins', False)
def test_superusers(self):
self.values["role"] = "SuperAdmins"
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % self.user.id,
self.values)
self.assertEqual(User.objects.get(username="user@test.com").is_superuser, True)
self.values["role"] = "SimpleUsers"
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % self.user.id,
self.values)
self.assertEqual(User.objects.get(username="user@test.com").is_superuser, False)
def test_self_modif(self):
self.clt.logout()
self.assertEqual(self.clt.login(username="admin@test.com", password="toto"),
True)
admin = User.objects.get(username="admin@test.com")
values = dict(username="admin@test.com", first_name="Admin", password1="", password2="",
is_active=True, email="admin@test.com")
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % admin.id, values)
self.assertEqual(admin.group, "DomainAdmins")
self.assertEqual(admin.can_access(Domain.objects.get(name="test.com")), True)
values["role"] = "SuperAdmins"
self.check_ajax_post("/modoboa/admin/accounts/edit/%d/" % admin.id, values)
admin = User.objects.get(username="admin@test.com")
self.assertEqual(admin.group, "DomainAdmins")
def test_domadmin_access(self):
self.clt.logout()
self.assertEqual(self.clt.login(username="admin@test.com", password="toto"),
True)
response = self.clt.get("/modoboa/admin/domains/")
self.assertEqual(response.status_code, 302)
user = User.objects.get(username="user@test.com")
response = self.clt.get("/modoboa/admin/accounts/edit/%d/" % user.id,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertNotEqual(response["Content-Type"], "application/json")
+40
View File
@@ -0,0 +1,40 @@
from django.conf.urls.defaults import *
urlpatterns = patterns(
'modoboa.admin.views',
url(r'^$', 'domains', name="index"),
url(r'^domains/$', 'domains', name="domains"),
(r'^domains/list/$', 'domains_list'),
(r'^domains/new/', 'newdomain'),
(r'^domains/(?P<dom_id>\d+)/edit/$', 'editdomain'),
(r'^domains/delete/$', 'deldomain'),
(r'^domains/import/$', 'import_domains'),
(r'^settings/$', 'viewparameters'),
(r'^settings/parameters/$', 'viewparameters'),
(r'^settings/parameters/save/$', 'saveparameters'),
(r'^settings/extensions/$', 'viewextensions'),
(r'^settings/extensions/save/$', 'saveextensions'),
(r'^permissions/remove/$', 'remove_permission'),
(r'^identities/$', 'identities'),
(r'^identities/import/$', 'import_identities'),
(r'^accounts/list/$', 'accounts_list'),
(r'^accounts/new/$', 'newaccount'),
(r'^accounts/edit/(?P<accountid>\d+)/$', 'editaccount'),
(r'^accounts/delete/$', 'delaccount'),
(r'^mailboxes/list/$', 'mboxes_list'),
(r'^distriblists/new/$', 'newdlist'),
(r'^distriblists/delete/$', 'deldlist'),
(r'^forwards/new/$', 'newforward'),
(r'^forwards/delete/$', 'delforward'),
(r'^aliases/new/$', 'newalias'),
(r'^aliases/edit/(?P<alid>\d+)/$', 'editalias_dispatcher'),
(r'^aliases/delete/$', 'delalias'),
)
+661
View File
@@ -0,0 +1,661 @@
# coding: utf-8
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.translation import ugettext as _, ungettext
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators \
import login_required, permission_required, user_passes_test
from django.db.models import Q
from django.contrib import messages
from django.db import transaction, IntegrityError
from lib import render_listing
from forms import *
from modoboa import admin, userprefs
from models import *
from modoboa.admin.tables import *
from modoboa.lib import events, parameters
from modoboa.lib.exceptions import *
from modoboa.lib.webutils \
import _render, ajax_response, ajax_simple_response
from modoboa.lib.emailutils import split_mailbox
from modoboa.lib.models import Parameter
from modoboa.lib.permissions import *
@login_required
def domains(request):
if not request.user.has_perm("admin.view_domains"):
if request.user.has_perm("admin.view_mailboxes"):
return HttpResponseRedirect(reverse(identities))
return HttpResponseRedirect(reverse(userprefs.views.index))
domains = request.user.get_domains()
squery = request.GET.get("searchquery", None)
if squery is not None:
q = Q(name__contains=squery)
q |= Q(domainalias__name__contains=squery)
domains = domains.filter(q).distinct()
return render_listing(request, "domains", "admin/domains.html",
objects=domains, squery=squery)
@login_required
@permission_required("auth.add_user")
def domains_list(request):
doms = map(lambda dom: dom.name, request.user.get_domains())
return ajax_simple_response(doms)
def _validate_domain(request, form, successmsg, commonctx, tplname,
callback=None, tpl_form_name="form"):
"""Domain form validation
Common function shared between creation and modification actions.
"""
error = None
if form.is_valid():
try:
domain = form.save(request.user)
except AdminError, e:
error = str(e)
# except IntegrityError:
# error = _("An alias with this name already exists")
else:
if callback is not None:
callback(request.user, domain)
messages.info(request, successmsg, fail_silently=True)
return ajax_response(request, url=reverse(admin.views.domains))
commonctx[tpl_form_name] = form
commonctx["error"] = error
return ajax_response(request, status="ko", template=tplname, **commonctx)
@login_required
@permission_required("admin.add_domain")
@transaction.commit_on_success
def newdomain(request, tplname="admin/newdomainform.html"):
events.raiseEvent("CanCreate", request.user, "domains")
def newdomain_cb(user, domain):
grant_access_to_object(user, domain, is_owner=True)
events.raiseEvent("CreateDomain", user, domain)
commonctx = {"title" : _("New domain"),
"action_label" : _("Create"),
"action_classes" : "submit",
"action" : reverse(newdomain),
"formid" : "domform"}
if request.method == "POST":
form = DomainFormGeneral(request.POST)
return _validate_domain(request, form, _("Domain created"), commonctx,
tplname, callback=newdomain_cb)
form = DomainFormGeneral()
commonctx["form"] = form
return _render(request, tplname, commonctx)
@login_required
@permission_required("admin.change_domain")
def editdomain(request, dom_id, tplname="admin/editdomainform.html"):
domain = Domain.objects.get(pk=dom_id)
if not request.user.can_access(domain):
raise PermDeniedException
domadmins = filter(
lambda u: request.user.can_access(u) and not u.is_superuser,
domain.admins
)
if not request.user.is_superuser:
domadmins = filter(lambda u: u.group == "DomainAdmins", domadmins)
instances = dict(general=domain)
events.raiseEvent("FillDomainInstances", request.user, domain, instances)
commonctx = {"title" : domain.name,
"action_label" : _("Update"),
"action_classes" : "submit",
"action" : reverse(editdomain, args=[dom_id]),
"formid" : "domform",
"domain" : domain}
if request.method == "POST":
form = DomainForm(request.user, request.POST, instances=instances)
return _validate_domain(request, form, _("Domain modified"), commonctx, tplname,
tpl_form_name="tabs")
commonctx["tabs"] = DomainForm(request.user, instances=instances)
commonctx["domadmins"] = domadmins
return _render(request, tplname, commonctx)
@login_required
@permission_required("admin.delete_domain")
@transaction.commit_on_success
def deldomain(request):
selection = request.GET["selection"].split(",")
error = None
keepdir = True if request.GET.get("keepdir", "false") == "true" else False
try:
mb = Mailbox.objects.get(user__id=request.user.id)
except Mailbox.DoesNotExist:
mb = None
for dom in Domain.objects.filter(id__in=selection):
if not request.user.can_access(dom):
raise PermDeniedException
if mb and mb.domain == dom:
raise AdminError(_("You can't delete your own domain"))
dom.delete(keepdir=keepdir)
msg = ungettext("Domain deleted", "Domains deleted", len(selection))
messages.info(request, msg, fail_silently=True)
return ajax_response(request)
def _validate_alias(request, form, successmsg, tplname, commonctx, callback=None):
"""Alias validation
Common function shared between creation and modification actions.
"""
error = None
if form.is_valid():
form.set_recipients()
try:
alias = form.save()
except IntegrityError:
raise AdminError(_("Alias with this name already exists"))
if callback:
callback(request.user, alias)
messages.info(request, successmsg)
return ajax_response(request, url=reverse(admin.views.identities))
if request.POST.has_key("targets"):
targets = request.POST.getlist("targets")
commonctx["targets"] = targets[:-1]
commonctx["form"] = form
commonctx["error"] = error
return ajax_response(request, status="ko", template=tplname, **commonctx)
def _new_alias(request, tplname, formclass, ctx, successmsg):
events.raiseEvent("CanCreate", request.user, "mailbox_aliases")
ctx.update(action_label=_("Create"), action_classes="submit")
if request.method == "POST":
def callback(user, alias):
grant_access_to_object(user, alias, is_owner=True)
events.raiseEvent("MailboxAliasCreated", user, alias)
if user.is_superuser:
for admin in alias.domain.admins:
grant_access_to_object(admin, alias)
form = formclass(request.user, request.POST)
return _validate_alias(request, form, successmsg, tplname, ctx, callback)
form = formclass(request.user)
ctx["form"] = form
return _render(request, tplname, ctx)
@login_required
@permission_required("admin.add_alias")
@transaction.commit_on_success
def newdlist(request):
ctx = dict(title=_("New distribution list"),
action=reverse(newdlist),
formid="aliasform")
return _new_alias(request, "common/generic_modal_form.html",
DlistForm, ctx, _("Distribution list created"))
@login_required
@permission_required("admin.add_alias")
@transaction.commit_on_success
def newalias(request):
ctx = dict(title=_("New alias"),
action=reverse(newalias),
formid="aliasform")
return _new_alias(request, "common/generic_modal_form.html",
AliasForm, ctx, _("Alias created"))
@login_required
@permission_required("admin.add_alias")
@transaction.commit_on_success
def newforward(request):
ctx = dict(title=_("New forward"),
action=reverse(newforward),
formid="aliasform")
return _new_alias(request, "common/generic_modal_form.html",
ForwardForm, ctx, _("Forward created"))
def _edit_alias(request, alias, tplname, formclass, ctx, successmsg):
if not request.user.can_access(alias):
raise PermDeniedException
ctx.update(title=alias.full_address, action_label=_("Update"),
action_classes="submit")
if request.method == "POST":
form = formclass(request.user, request.POST, instance=alias)
return _validate_alias(request, form, successmsg, tplname, ctx)
form = formclass(request.user, instance=alias)
ctx["form"] = form
return _render(request, tplname, ctx)
def editalias(request, alias, ctx):
return _edit_alias(request, alias, "common/generic_modal_form.html",
AliasForm, ctx, _("Alias modified"))
def editdlist(request, alias, ctx):
return _edit_alias(request, alias, "admin/dlistform.html",
DlistForm, ctx, _("Distribution list modified"))
def editforward(request, alias, ctx):
return _edit_alias(request, alias, "common/generic_modal_form.html",
ForwardForm, ctx, _("Forward modified"))
@login_required
@permission_required("admin.change_alias")
def editalias_dispatcher(request, alid):
alias = Alias.objects.get(pk=alid)
ctx = dict(action=reverse(editalias_dispatcher, args=[alias.id]), formid="aliasform")
if len(alias.get_recipients()) >= 2:
return editdlist(request, alias, ctx)
if alias.extmboxes != "":
return editforward(request, alias, ctx)
return editalias(request, alias, ctx)
def _del_alias(request, msg, msgs):
selection = request.GET["selection"].split(",")
for alid in selection:
alias = Alias.objects.get(pk=alid)
if not request.user.can_access(alias):
raise PermDeniedException
alias.delete()
msg = ungettext(msg, msgs, len(selection))
messages.info(request, msg)
return ajax_response(request)
@login_required
@permission_required("admin.delete_alias")
@transaction.commit_on_success
def delalias(request):
return _del_alias(request, "Alias deleted", "Aliases deleted")
@login_required
@permission_required("admin.delete_alias")
@transaction.commit_on_success
def deldlist(request):
return _del_alias(request, "Distribution list deleted", "Distribution lists deleted")
@login_required
@permission_required("admin.delete_alias")
@transaction.commit_on_success
def delforward(request):
return _del_alias(request, "Forward deleted", "Forwards deleted")
@login_required
@user_passes_test(lambda u: u.has_perm("auth.add_user") or u.has_perm("admin.add_alias"))
def identities(request, tplname='admin/identities.html'):
idents_list = request.user.get_identities()
squery = request.GET.get("searchquery", None)
if squery:
uct = get_content_type(User)
uids = idents_list.filter(content_type=uct).values_list("object_id", flat=True)
objects = [u for u in User.objects.filter(pk__in=uids, username__contains=squery)]
alct = get_content_type(Alias)
alids = idents_list.filter(content_type=alct).values_list("object_id", flat=True)
if squery.find('@') != -1:
local_part, domname = split_mailbox(squery)
mbaliases = Alias.objects.filter(address__contains=local_part,
domain__name__contains=domname)
q = Q(address__contains=local_part, domain__name__contains=domname)
else:
q = Q(address__contains=squery)
objects += [al for al in Alias.objects.filter(Q(pk__in=alids) & q)]
else:
objects = []
for oa in idents_list:
if oa.content_object:
objects.append(oa.content_object)
objects = sorted(objects, key=lambda o: o.identity)
return render_listing(request, "identities", tplname,
objects=objects, squery=squery)
@login_required
@permission_required("auth.add_user")
def accounts_list(request):
accs = User.objects.filter(is_superuser=False).exclude(groups__name='SimpleUsers')
res = map(lambda a: a.username, accs.all())
return ajax_simple_response(res)
@login_required
@permission_required("admin.add_mailbox")
def mboxes_list(request):
mboxes = request.user.get_mailboxes()
return ajax_simple_response([mb.full_address for mb in mboxes])
@login_required
@permission_required("auth.add_user")
@transaction.commit_on_success
def newaccount(request, tplname='admin/newaccount.html'):
from modoboa.lib.formutils import CreationWizard
def create_account(steps):
"""Account creation callback
Called when all creation steps have been validated.
:param steps: the steps data
"""
genform = steps[0]["form"]
genform.is_valid()
account = genform.save()
grant_access_to_object(request.user, account, is_owner=True)
events.raiseEvent("AccountCreated", account)
mailform = steps[1]["form"]
mb = mailform.save(request.user, account)
ctx = dict(
title=_("New account"),
action=reverse(newaccount),
formid="newaccount_form",
submit_label=_("Create")
)
cwizard = CreationWizard(create_account)
cwizard.add_step(AccountFormGeneral, _("General"),
[dict(classes="btn-inverse next", label=_("Next"))],
new_args=[request.user])
cwizard.add_step(AccountFormMail, _("Mail"),
[dict(classes="btn-primary submit", label=_("Create")),
dict(classes="btn-inverse prev", label=_("Previous"))])
if request.method == "POST":
retcode, data = cwizard.validate_step(request)
if retcode == -1:
raise AdminError(data)
if retcode == 1:
return ajax_simple_response(dict(
status="ok", title=cwizard.get_title(data + 1), stepid=data
))
if retcode == 2:
messages.info(request, _("Account created"))
return ajax_simple_response(dict(status="ok"))
from modoboa.lib.templatetags.libextras import render_form
return ajax_simple_response(dict(
status="ko", stepid=data, form=render_form(cwizard.steps[data]["form"])
))
cwizard.create_forms()
ctx.update(steps=cwizard.steps)
ctx.update(subtitle="1. %s" % cwizard.steps[0]['title'])
return _render(request, tplname, ctx)
@login_required
@permission_required("auth.change_user")
@transaction.commit_on_success
def editaccount(request, accountid, tplname="common/tabforms.html"):
account = User.objects.get(pk=accountid)
if not request.user.can_access(account):
raise PermDeniedException
mb = None
if account.has_mailbox:
mb = account.mailbox_set.all()[0]
instances = dict(general=account, mail=mb, perms=account)
events.raiseEvent("FillAccountInstances", request.user, account, instances)
ctx = dict(
title=account.username,
formid="accountform",
action=reverse(editaccount, args=[accountid]),
action_label=_("Update"),
action_classes="submit"
)
if request.method == "POST":
classes = {}
form = AccountForm(request.user, request.POST,
instances=instances, classes=classes)
account.oldgroup = account.group
if form.is_valid(mandatory_only=True):
form.save_general_form()
if form.is_valid(optional_only=True):
events.raiseEvent("AccountModified", account, form.account)
form.save()
messages.info(request, _("Account updated"))
return ajax_simple_response(dict(status="ok"))
transaction.rollback()
ctx["tabs"] = form
return ajax_response(request, status="ko", template=tplname, **ctx)
ctx["tabs"] = AccountForm(request.user, instances=instances)
return _render(request, tplname, ctx)
@login_required
@permission_required("auth.delete_user")
@transaction.commit_on_success
def delaccount(request):
selection = request.GET["selection"].split(",")
keepdir = True if request.GET.get("keepdir", "false") == "true" else False
for account in User.objects.filter(id__in=selection):
account.delete(request.user, keepdir)
msg = ungettext("Account deleted", "Accounts deleted", len(selection))
messages.info(request, msg, fail_silently=True)
return ajax_response(request)
@login_required
@permission_required("admin.add_domain")
def remove_permission(request):
domid = request.GET.get("domid", None)
daid = request.GET.get("daid", None)
if domid is None or daid is None:
raise AdminError(_("Invalid request"))
try:
account = User.objects.get(pk=daid)
domain = Domain.objects.get(pk=domid)
except (User.DoesNotExist, Domain.DoesNotExist):
raise AdminError(_("Invalid request"))
if not request.user.can_access(account) or not request.user.can_access(domain):
raise PermDeniedException
ungrant_access_to_object(domain, account)
return ajax_simple_response(dict(status="ok"))
@login_required
@user_passes_test(lambda u: u.is_superuser)
def viewparameters(request, tplname='admin/parameters.html'):
apps = sorted(parameters._params.keys())
gparams = []
for app in apps:
tmp = {"name" : app, "params" : []}
for p in parameters._params_order[app]['A']:
param_def = parameters._params[app]['A'][p]
newdef = {"name" : p,
"value" : parameters.get_admin(p, app=app),
"help" : param_def["help"],
"default" : param_def["deflt"],
"type" : param_def["type"]}
if "values" in param_def.keys():
newdef["values"] = param_def["values"]
tmp["params"] += [newdef]
gparams += [tmp]
return _render(request, tplname, {
"selection" : "settings",
"left_selection" : "parameters",
"gparams" : gparams
})
@login_required
@user_passes_test(lambda u: u.is_superuser)
def saveparameters(request):
for pname, v in request.POST.iteritems():
if pname == "update":
continue
app, name = pname.split('.')
parameters.save_admin(name, v, app=app)
return ajax_simple_response(dict(status="ok", message=_("Parameters saved")))
@login_required
@user_passes_test(lambda u: u.is_superuser)
def viewextensions(request, tplname='admin/extensions.html'):
from modoboa.extensions import exts_pool
exts = exts_pool.list_all()
for ext in exts:
try:
dbext = Extension.objects.get(name=ext["id"])
ext["selection"] = dbext.enabled
except Extension.DoesNotExist:
dbext = Extension()
dbext.name = ext["id"]
dbext.enabled = False
dbext.save()
ext["selection"] = False
tbl = ExtensionsTable(request, exts)
return _render(request, tplname, {
"selection" : "settings",
"left_selection" : "extensions",
"extensions" : tbl
})
@login_required
@user_passes_test(lambda u: u.is_superuser)
def saveextensions(request):
from modoboa import extensions
actived_exts = Extension.objects.filter(enabled=True)
found = []
for k, v in request.POST.iteritems():
if k.startswith("select_"):
parts = k.split("_", 1)
dbext = Extension.objects.get(name=parts[1])
if not dbext in actived_exts:
dbext.on()
else:
found += [dbext]
for ext in actived_exts:
if not ext in found:
ext.off()
return ajax_simple_response(dict(
status="ok", message=_("Modifications applied."), reload=True
))
def import_domain(user, row):
"""Specific code for domains import"""
dom = Domain()
dom.create_from_csv(user, row)
grant_access_to_object(user, dom, is_owner=True)
events.raiseEvent("CreateDomain", user, dom)
def import_account(user, row):
"""Specific code for accounts import"""
mb = Mailbox()
mb.create_from_csv(user, row)
grant_access_to_object(user, mb.user, is_owner=True)
grant_access_to_object(user, mb, is_owner=True)
events.raiseEvent("AccountCreated", mb.user)
events.raiseEvent("CreateMailbox", user, mb)
def import_dlist(user, row):
"""Specific code for distribution lists import"""
dlist = Alias()
dlist.create_from_csv(user, row)
grant_access_to_object(user, dlist, is_owner=True)
events.raiseEvent("MailboxAliasCreated", user, dlist)
def importdata(request):
"""Generic import function
As the process of importing data from a CSV file is the same
whatever the type, we do a maximum of the work here.
:param request: a ``Request`` instance
:param typ: a string indicating the object type being imported
:return: a ``Response`` instance
"""
error = None
form = ImportDataForm(request.POST, request.FILES)
if form.is_valid():
import csv
try:
reader = csv.reader(request.FILES['sourcefile'],
delimiter=form.cleaned_data['sepcar'])
except Exception, e:
error = str(e)
if error is None:
try:
cpt = 0
for row in reader:
try:
fct = globals()["import_%s" % row[0].strip()]
except KeyError:
continue
fct(request.user, row)
cpt += 1
messages.info(request, _("%d objects imported successfully" % cpt))
return _render(request, "admin/import_done.html", {
"status" : "ok", "msg" : ""
})
except (IntegrityError, ModoboaException), e:
error = str(e)
print error
return _render(request, "admin/import_done.html", {
"status" : "ko", "msg" : error
})
@login_required
@user_passes_test(lambda u: u.has_perm("auth.add_user") or u.has_perm("auth.add_alias"))
@transaction.commit_on_success
def import_identities(request):
if request.method == "POST":
return importdata(request)
helptext = _("""Provide a CSV file where lines respect one of the following format:
<ul>
<li><em>account; loginname; password; first name; last name; address</em></li>
<li><em>dlist; address; recipient; recipient; ...</em></li>
</ul>
You can use a different character as separator.
""")
ctx = dict(
title=_("Import identities"),
action_label=_("Import"),
action_classes="submit",
action=reverse(import_identities),
formid="importform",
enctype="multipart/form-data",
target="import_target",
form=ImportDataForm(),
helptext=helptext
)
return _render(request, "admin/importform.html", ctx)
@login_required
@permission_required("admin.add_domain")
@transaction.commit_on_success
def import_domains(request):
if request.method == "POST":
return importdata(request)
helptext = _("""Provide a CSV file where lines respect the following format:<br/>
<em>domain; name; quota</em><br/>
You can use a different character as separator.
""")
ctx = dict(
title=_("Import domains"),
action_label=_("Import"),
action_classes="submit",
action=reverse(import_domains),
formid="importform",
enctype="multipart/form-data",
target="import_target",
helptext=helptext,
form=ImportDataForm()
)
return _render(request, "admin/importform.html", ctx)
+6
View File
@@ -0,0 +1,6 @@
# coding: utf-8
from modoboa.lib import parameters
from django.utils.translation import ugettext_lazy
parameters.register_admin("SECRET_KEY", type="string", deflt="abcdefghijklmnop",
help=ugettext_lazy("Key used to encrypt/decrypt passwords"))
+16
View File
@@ -0,0 +1,16 @@
from django import forms
from django.utils.translation import ugettext_lazy as _
class LoginForm(forms.Form):
username = forms.CharField(
label=_("Username"),
widget=forms.TextInput(attrs={"class" : "span3"})
)
password = forms.CharField(
label=_("Password"),
widget=forms.PasswordInput(attrs={"class" : "span3"})
)
rememberme = forms.BooleanField(
initial=False,
required=False
)
+27
View File
@@ -0,0 +1,27 @@
# coding: utf-8
import crypt, hashlib
import string
from random import Random
from Crypto.Cipher import AES
import base64
from modoboa.lib import parameters
def encrypt(clear):
key = parameters.get_admin("SECRET_KEY")
obj = AES.new(key, AES.MODE_ECB)
clear = str(clear)
if len(clear) % AES.block_size:
clear += " " * (AES.block_size - len(clear) % AES.block_size)
ciph = obj.encrypt(clear)
ciph = base64.b64encode(ciph)
return ciph
def decrypt(ciph):
obj = AES.new(parameters.get_admin("SECRET_KEY"), AES.MODE_ECB)
ciph = base64.b64decode(ciph)
clear = obj.decrypt(ciph)
return clear.rstrip(' ')
def get_password(request):
return decrypt(request.session["password"])
+3
View File
@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.
+23
View File
@@ -0,0 +1,23 @@
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
+58
View File
@@ -0,0 +1,58 @@
# coding: utf-8
from django.views.decorators.cache import never_cache
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from modoboa.lib import events
from modoboa.lib.webutils import _render
from modoboa.admin import views as admviews
from forms import LoginForm
from modoboa.auth.lib import *
def dologin(request):
error = None
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data["username"],
password=form.cleaned_data["password"])
if user:
if user.is_active:
if not form.cleaned_data["rememberme"]:
request.session.set_expiry(0)
login(request, user)
if request.user.id != 1:
request.session["password"] = encrypt(request.POST["password"])
request.session["django_language"] = \
parameters.get_user(request.user, "LANG", app="general")
events.raiseEvent("UserLogin", request,
form.cleaned_data["username"],
form.cleaned_data["password"])
next = request.POST["next"]
if next.strip() in ["", "None"]:
next = reverse(admviews.domains)
return HttpResponseRedirect(next)
else:
error = _("Account is disabled.")
error = _("Your username and password didn't match. Please try again.")
next = request.POST.get("next", None)
else:
form = LoginForm()
next = request.GET.get("next", None)
return _render(request, "registration/login.html", {
"form" : form, "error" : error, "next" : next,
"annoucements" : events.raiseQueryEvent("GetAnnouncement", "loginpage")
})
dologin = never_cache(dologin)
def dologout(request):
events.raiseEvent("UserLogout", request)
logout(request)
return HttpResponseRedirect(reverse(dologin))
+55
View File
@@ -0,0 +1,55 @@
# coding: utf-8
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from modoboa.lib import events
from modoboa.lib.webutils import static_url
@events.observe("UserMenuDisplay")
def menu(target, user):
import views
if target != "top_menu_middle":
return []
if not user.has_mailbox:
return []
return [
{"name" : "demo",
"label" : _("Test messages"),
"img" : static_url("pics/demo.png"),
"class" : "topdropdown",
"menu" : [
{"name" : "sendvirus",
"label" : _("Send virus"),
"img" : static_url("pics/send-receive.png"),
"url" : reverse(views.send_virus)},
{"name" : "sendspam",
"label" : _("Send spam"),
"img" : static_url("pics/send-receive.png"),
"url" : reverse(views.send_spam)}
]
}
]
@events.observe("GetAnnouncement")
def announcement(target):
if target == "loginpage":
txt = render_to_string("demo/login_announcement.html")
return [txt]
return ""
@events.observe("PasswordChange")
def password_change(user):
return [user.id == 1]
@events.observe("GetStaticContent")
def get_static_content(user):
if not user.has_mailbox:
return []
return """<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', 'a[name=sendspam]', simple_ajax_request);
$(document).on('click', 'a[name=sendvirus]', simple_ajax_request);
});
</script>"""
@@ -0,0 +1,13 @@
{% load i18n %}
{% blocktrans %}
<h3>Welcome to the online demo!</h3>
<p><b>Warning:</b> the demo's concent is resetted every two hours.</p>
<p>To try the demo, the following users are available (<i>username/password</i>): </p>
<ul>
<li>A super administrator : <b>admin/password</b></li>
<li>A domain administrator : <b>admin@demo.local/admin</b></li>
<li>A simple user : <b>user@demo.local/user</b></li>
</ul>
<p>Please report any issue or give any suggestion to
<a href="https://groups.google.com/forum/#!forum/modoboa-users">the mailing list</a>.</p>
{% endblocktrans %}
+6
View File
@@ -0,0 +1,6 @@
from django.conf.urls.defaults import *
urlpatterns = patterns('modoboa.demo.views',
(r'^sendvirus/$', 'send_virus'),
(r'^sendspam/$', 'send_spam'),
)
+42
View File
@@ -0,0 +1,42 @@
# coding: utf-8
import os
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from modoboa.lib.webutils import ajax_simple_response
from modoboa.lib.emailutils import sendmail_simple, sendmail_fromfile
from modoboa.lib.decorators import needs_mailbox
@login_required
@needs_mailbox()
def send_virus(request):
status, error = sendmail_fromfile("virus@example.net", request.user.username,
os.path.join(settings.MODOBOA_DIR,
"tmp/virus.msg"))
if status:
return ajax_simple_response(dict(status="ok", respmsg=_("Message sent")))
return ajax_simple_response(dict(status="ko", respmsg=error))
@login_required
@needs_mailbox()
def send_spam(request):
status, error = sendmail_simple("spam@example.net", request.user.username, """
This is the GTUBE, the
Generic
Test for
Unsolicited
Bulk
Email
If your spam filter supports it, the GTUBE provides a test by which you
can verify that the filter is installed correctly and is detecting incoming
spam. You can send yourself a test mail containing the following string of
characters (in upper case and with no white spaces and line breaks):
XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X
You should send this test mail from an account outside of your network.
""")
if status:
return ajax_simple_response(dict(status="ok", respmsg=_("Message sent")))
return ajax_simple_response(dict(status="ko", respmsg=error))
+78
View File
@@ -0,0 +1,78 @@
# coding: utf-8
import os, sys
import re
from django.conf import settings
from django.conf.urls.defaults import include
class ModoExtension(object):
"""Base extension class
Each Modoboa extension must inherit from this class to be
considered as valid.
"""
name = None
version = "0.1"
description = ""
url = None
needs_media = False
def infos(self):
return dict(name=self.name, label=self.label, version=self.version,
description=self.description, url=self.url)
def init(self):
pass
def destroy(self):
pass
def load(self):
pass
class ExtensionsPool(object):
"""The extensions manager"""
def __init__(self):
self.extensions = dict()
def register_extension(self, ext):
self.extensions[ext.name] = dict(cls=ext)
def get_extension(self, name):
if not self.extensions.has_key(name):
return None
if not self.extensions[name].has_key("instance"):
self.extensions[name]["instance"] = self.extensions[name]["cls"]()
return self.extensions[name]["instance"]
def get_extension_infos(self, name):
instance = self.get_extension(name)
return instance.infos()
def load_all(self, prefix):
from modoboa.admin.models import Extension
result = []
for extname, extdef in self.extensions.iteritems():
extinstance = self.get_extension(extname)
try:
ext = Extension.objects.get(name=extname)
if ext.enabled:
extinstance.load()
except Extension.DoesNotExist:
pass
baseurl = extinstance.url if extinstance.url is not None else extname
result += [(r'%s%s/' % (prefix, baseurl),
include("%s.urls" % extinstance.__module__))]
return result
def list_all(self):
result = []
for extname, extdef in self.extensions.iteritems():
infos = extdef["instance"].infos()
infos["id"] = extname
result += [infos]
return sorted(result, key=lambda i: i["name"])
exts_pool = ExtensionsPool()
@@ -0,0 +1,201 @@
# coding: utf-8
"""
Amavis quarantine manager (SQL based)
"""
from django.utils.translation import ugettext as _, ugettext_lazy
from django.core.urlresolvers import reverse
from django.template import Template, Context
from modoboa.lib import events, parameters
from modoboa.extensions import ModoExtension, exts_pool
class AmavisQuarantine(ModoExtension):
name = "amavis_quarantine"
label = "Amavis quarantine"
version = "1.0"
description = ugettext_lazy("Simple amavis quarantine management tool")
url = "quarantine"
def init(self):
"""Init function
Only run once, when the extension is enabled. We create records
for existing mailboxes in order Amavis considers them local.
"""
from modoboa.admin.models import Mailbox
from models import Users
for mb in Mailbox.objects.all():
try:
u = Users.objects.get(email=mb.full_address)
except Users.DoesNotExist:
u = Users()
u.email = mb.full_address
u.fullname = mb.user.fullname
u.local = "1"
u.priority = 7
u.policy_id = 1
u.save()
def load(self):
parameters.register_admin(
"MAX_MESSAGES_AGE", type="int",
deflt=14,
help=_("Quarantine messages maximum age (in days) before deletion")
)
parameters.register_admin(
"RELEASED_MSGS_CLEANUP", type="list_yesno", deflt="no",
help=_("Remove messages marked as released while cleaning up the database")
)
parameters.register_admin("AM_PDP_MODE", type="list",
deflt="unix",
values=[("inet", "inet"), ("unix", "unix")],
help=ugettext_lazy("Mode used to access the PDP server"))
parameters.register_admin("AM_PDP_HOST", type="string",
deflt="localhost",
help=ugettext_lazy("PDP server address (if inet mode)"))
parameters.register_admin("AM_PDP_PORT", type="int",
deflt=9998,
help=ugettext_lazy("PDP server port (if inet mode)"))
parameters.register_admin("AM_PDP_SOCKET", type="string",
deflt="/var/amavis/amavisd.sock",
help=ugettext_lazy("Path to the PDP server socket (if unix mode)"))
parameters.register_admin("CHECK_REQUESTS_INTERVAL", type="int",
deflt=30,
help=ugettext_lazy("Interval between two release requests checks"))
parameters.register_admin("USER_CAN_RELEASE", type="list_yesno", deflt="no",
help=ugettext_lazy("Allow users to directly release their messages"))
parameters.register_admin("SELF_SERVICE", type="list_yesno", deflt="no",
help=ugettext_lazy("Activate the 'self-service' mode"))
parameters.register_user(
"MESSAGES_PER_PAGE", type="int", deflt=40,
label="Number of displayed emails per page",
help=ugettext_lazy("Sets the maximum number of messages displayed in a page")
)
def destroy(self):
events.unregister("UserMenuDisplay", menu)
parameters.unregister_app("amavis_quarantine")
exts_pool.register_extension(AmavisQuarantine)
@events.observe("UserMenuDisplay")
def menu(target, user):
from modoboa.lib.webutils import static_url
if target == "top_menu":
return [
{"name" : "quarantine",
"label" : _("Quarantine"),
"url" : reverse('modoboa.extensions.amavis_quarantine.views.index')}
]
return []
@events.observe("DeleteDomain")
def on_delete_domain(domain):
from models import Users
try:
u = Users.objects.get(email="@%s" % domain.name)
except Users.DoesNotExist:
return
u.policy.delete()
u.delete()
@events.observe("CreateMailbox")
def create_user_record(user, mailbox):
from models import Users
try:
Users.objects.get(email=mailbox.full_address)
except Users.DoesNotExist:
u = Users()
u.email = mailbox.full_address
u.fullname = mailbox.user.fullname
u.local = "1"
u.priority = 7
u.policy_id = 1
u.save()
@events.observe("ModifyMailbox")
def modify_user_record(mailbox, oldmailbox):
if mailbox.full_address == oldmailbox.full_address:
return
u = Users.objects.get(email=oldmailbox.full_address)
u.email = mailbox.full_address
u.save()
@events.observe("DeleteMailbox")
def remove_user_record(mailboxes):
from models import Users
from modoboa.admin.models import Mailbox
if isinstance(mailboxes, Mailbox):
mailboxes = [mailboxes]
for mailbox in mailboxes:
try:
Users.objects.get(email=mailbox.full_address).delete()
except Users.DoesNotExist:
pass
@events.observe("GetStaticContent")
def extra_static_content(user):
if parameters.get_admin("USER_CAN_RELEASE") == "yes" \
or user.group == "SimpleUsers":
return []
tpl = Template("""<script type="text/javascript">
$(document).ready(function() {
var poller = new Poller("{{ url }}", {
interval: {{ interval }},
success_cb: function(data) {
var $link = $("#nbrequests");
if (data.requests > 0) {
$link.html(data.requests + " " + "{{ text }}");
$link.parent().removeClass('hidden');
} else {
$link.parent().addClass('hidden');
}
}
});
});
</script>""")
url = reverse("modoboa.extensions.amavis_quarantine.views.nbrequests")
interval = int(parameters.get_admin("CHECK_REQUESTS_INTERVAL")) * 1000
return [tpl.render(Context(dict(url=url, interval=interval, text=_("pending requests"))))]
@events.observe("TopNotifications")
def display_requests(user):
from lib import get_nb_requests
if parameters.get_admin("USER_CAN_RELEASE") == "yes" \
or user.group == "SimpleUsers":
return []
nbrequests = get_nb_requests(user)
url = reverse("modoboa.extensions.amavis_quarantine.views.index")
url += "#listing/?viewrequests=1"
tpl = Template('<div class="btn-group {{ css }}"><a id="nbrequests" href="{{ url }}" class="btn btn-danger">{{ label }}</a></div>')
css = "hidden" if nbrequests == 0 else ""
return [tpl.render(Context(dict(
label=_("%d pending requests" % nbrequests), url=url, css=css
)))]
@events.observe("ExtraDomainForm")
def extra_domain_form(user, domain):
from forms import DomainPolicyForm
if not user.is_superuser and not user.belongs_to_group("Resellers"):
return []
return [
dict(
id="amavis", title=_("Amavis"), cls=DomainPolicyForm
)
]
@events.observe("FillDomainInstances")
def fill_domain_instances(user, domain, instances):
if not user.is_superuser and not user.belongs_to_group("Resellers"):
return
instances["amavis"] = domain
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from modoboa.extensions.amavis_quarantine.models import *
if __name__ == "__main__":
from modoboa.extensions import amavis_quarantine
from modoboa.lib import parameters
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--debug", action="store_true",
help="Activate debug output")
options, args = parser.parse_args()
if options.debug:
import logging
l = logging.getLogger("django.db.backends")
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
amavis_quarantine.load()
max_messages_age = int(parameters.get_admin("MAX_MESSAGES_AGE",
app="amavis_quarantine"))
flags = ['D']
if parameters.get_admin("RELEASED_MSGS_CLEANUP",
app="amavis_quarantine") == "yes":
flags += ['R']
print "Deleting marked messages..."
ids = Msgrcpt.objects.filter(rs__in=flags).values("mail_id")
for msg in Msgs.objects.filter(mail_id__in=ids):
if not msg.msgrcpt_set.exclude(rs__in=flags).count():
msg.delete()
print "Deleting messages older than %d days..." % max_messages_age
limit = int(time.time()) - (max_messages_age * 24 * 3600)
Msgs.objects.filter(time_num__lt=limit).delete()
print "Deleting unreferenced e-mail addresses..."
for maddr in Maddr.objects.all():
if not len(maddr.msgs_set.all()) and not len(maddr.msgrcpt_set.all()):
maddr.delete()
print "Done."
@@ -0,0 +1,30 @@
class AmavisRouter(object):
"""A router to control all database operations on models in
the amavis_quarantine application"""
def db_for_read(self, model, **hints):
"Point all operations on amavis_quarantine models to 'amavis'"
if model._meta.app_label == 'amavis_quarantine':
return 'amavis'
return None
def db_for_write(self, model, **hints):
"Point all operations on amavis_quarantine models to 'amavis'"
if model._meta.app_label == 'amavis_quarantine':
return 'amavis'
return None
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in amavis_quarantine is involved"
if obj1._meta.app_label == 'amavis_quarantine' \
or obj2._meta.app_label == 'amavis_quarantine':
return True
return None
def allow_syncdb(self, db, model):
"Make sure the amavis_quarantine app only appears on the 'amavis' db"
if db == 'amavis':
return model._meta.app_label == 'amavis_quarantine'
elif model._meta.app_label == 'amavis_quarantine':
return False
return None
@@ -0,0 +1,46 @@
# coding: utf-8
from django import forms
from models import Policy, Users
class DomainPolicyForm(forms.ModelForm):
class Meta:
model = Policy
fields = ('bypass_virus_checks', 'bypass_spam_checks', 'spam_modifies_subj',
'spam_tag2_level', 'spam_kill_level')
widgets = {
'bypass_spam_checks' : forms.Select(attrs={'class' : 'span1'}),
'bypass_virus_checks' : forms.Select(attrs={'class' : 'span1'}),
'spam_modifies_subj' : forms.Select(attrs={'class' : 'span1'}),
'spam_tag2_level' : forms.TextInput(attrs={'class' : 'span1'}),
'spam_kill_level' : forms.TextInput(attrs={'class' : 'span1'}),
}
def __init__(self, *args, **kwargs):
if kwargs.has_key("instance"):
self.domain = kwargs["instance"]
try:
policy = Users.objects.get(email="@%s" % self.domain.name).policy
kwargs["instance"] = policy
except (Users.DoesNotExist, Policy.DoesNotExist), e:
del kwargs["instance"]
super(DomainPolicyForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
p = super(DomainPolicyForm, self).save(commit=False)
if commit:
p.save()
print p.id
try:
u = Users.objects.get(policy__id=p.id)
except Users.DoesNotExist:
u = Users()
u.email = "@%s" % self.domain.name
u.fullname = self.domain.name
u.policy = p
u.local = "1"
u.priority = 7
u.save()
p.save()
return p
@@ -0,0 +1,82 @@
# coding: utf-8
import socket
import re
import struct
import string
from functools import wraps
from django.core.urlresolvers import reverse
from django.db.models import Q
from modoboa.lib import parameters
from models import Msgrcpt
def selfservice(ssfunc=None):
"""Decorator used to expose views to the 'self-service' feature
The 'self-service' feature allows users to act on quarantined
messages without beeing authenticated.
This decorator only acts as a 'router'.
:param ssfunc: the function to call if the 'self-service'
pre-requisites are satisfied
"""
def decorator(f):
@wraps(f)
def wrapped_f(request, *args, **kwargs):
if request.user.is_authenticated():
return f(request, *args, **kwargs)
if parameters.get_admin("SELF_SERVICE") == "no":
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(reverse("modoboa.extensions.amavis_quarantine.views.index"))
return ssfunc(request, *args, **kwargs)
return wrapped_f
return decorator
def get_nb_requests(user):
"""Return the number of current pending requests
:param user: a ``User`` instance
"""
rq = Q(rs='p')
if not user.is_superuser:
doms = user.get_domains()
regexp = "(%s)" % '|'.join(map(lambda dom: dom.name, doms))
doms_q = Q(rid__email__regex=regexp)
rq &= doms_q
return len(Msgrcpt.objects.filter(rq))
class AMrelease(object):
def __init__(self):
mode = parameters.get_admin("AM_PDP_MODE")
if mode == "inet":
host = parameters.get_admin('AM_PDP_HOST')
port = parameters.get_admin('AM_PDP_PORT')
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, int(port)))
else:
path = parameters.get_admin('AM_PDP_SOCKET')
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(path)
def decode(self, answer):
def repl(match):
return struct.pack("B", string.atoi(match.group(0)[1:], 16))
return re.sub(r"%([0-9a-fA-F]{2})", repl, answer)
def __del__(self):
self.sock.close()
def sendreq(self, mailid, secretid, recipient, *others):
self.sock.send("""request=release
mail_id=%s
secret_id=%s
quar_type=Q
recipient=%s
""" % (mailid, secretid, recipient))
answer = self.sock.recv(1024)
answer = self.decode(answer)
if re.search("250 [\d\.]+ Ok", answer):
return True
return False
@@ -0,0 +1,155 @@
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
# into your database.
#
# Original Amavis version : 2.6.2
from django.db import models
from django.utils.translation import ugettext as _, ugettext_lazy
class Maddr(models.Model):
partition_tag = models.IntegerField(unique=True, null=True, blank=True)
id = models.BigIntegerField(primary_key=True)
email = models.CharField(unique=True, max_length=255)
domain = models.CharField(max_length=765)
class Meta:
db_table = u'maddr'
managed = False
class Mailaddr(models.Model):
id = models.IntegerField(primary_key=True)
priority = models.IntegerField()
email = models.CharField(unique=True, max_length=255)
class Meta:
db_table = u'mailaddr'
managed = False
class Msgs(models.Model):
partition_tag = models.IntegerField(null=True, blank=True)
mail_id = models.CharField(max_length=12, primary_key=True)
secret_id = models.CharField(max_length=12, blank=True)
am_id = models.CharField(max_length=60)
time_num = models.IntegerField()
time_iso = models.CharField(max_length=48)
sid = models.ForeignKey(Maddr, db_column='sid')
policy = models.CharField(max_length=765, blank=True)
client_addr = models.CharField(max_length=765, blank=True)
size = models.IntegerField()
content = models.CharField(max_length=1, blank=True)
quar_type = models.CharField(max_length=1, blank=True)
quar_loc = models.CharField(max_length=255, blank=True)
dsn_sent = models.CharField(max_length=3, blank=True)
spam_level = models.FloatField(null=True, blank=True)
message_id = models.CharField(max_length=765, blank=True)
from_addr = models.CharField(max_length=765, blank=True)
subject = models.CharField(max_length=765, blank=True)
host = models.CharField(max_length=765)
class Meta:
db_table = u'msgs'
managed = False
class Msgrcpt(models.Model):
partition_tag = models.IntegerField(null=True, blank=True)
mail = models.ForeignKey(Msgs, primary_key=True)
rid = models.ForeignKey(Maddr, db_column='rid', primary_key=True)
ds = models.CharField(max_length=3)
rs = models.CharField(max_length=3)
bl = models.CharField(max_length=3, blank=True)
wl = models.CharField(max_length=3, blank=True)
bspam_level = models.FloatField(null=True, blank=True)
smtp_resp = models.CharField(max_length=765, blank=True)
class Meta:
db_table = u'msgrcpt'
managed = False
unique_together = ("mail", "rid")
class Policy(models.Model):
id = models.AutoField(primary_key=True)
policy_name = models.CharField(max_length=96, blank=True)
virus_lover = models.CharField(max_length=3, blank=True)
spam_lover = models.CharField(max_length=3, blank=True)
banned_files_lover = models.CharField(max_length=3, blank=True)
bad_header_lover = models.CharField(max_length=3, blank=True)
bypass_virus_checks = models.CharField(
ugettext_lazy("Bypass virus checks"), max_length=3,
choices=(('Y', 'yes'), ('N', 'no')), blank=True
)
bypass_spam_checks = models.CharField(
ugettext_lazy("Bypass spam checks"), max_length=3,
choices=(('Y', 'yes'), ('N', 'no')), blank=True
)
bypass_banned_checks = models.CharField(max_length=3, blank=True)
bypass_header_checks = models.CharField(max_length=3, blank=True)
spam_modifies_subj = models.CharField(
ugettext_lazy("Modify spam subject"),
choices=(('Y', 'yes'), ('N', 'no')), max_length=3, blank=True
)
virus_quarantine_to = models.CharField(max_length=192, blank=True)
spam_quarantine_to = models.CharField(max_length=192, blank=True)
banned_quarantine_to = models.CharField(max_length=192, blank=True)
bad_header_quarantine_to = models.CharField(max_length=192, blank=True)
clean_quarantine_to = models.CharField(max_length=192, blank=True)
other_quarantine_to = models.CharField(max_length=192, blank=True)
spam_tag_level = models.FloatField(null=True, blank=True)
spam_tag2_level = models.FloatField(
ugettext_lazy("Spam tag2 level"), null=True, blank=True
)
spam_kill_level = models.FloatField(
ugettext_lazy("Spam kill level"), null=True, blank=True
)
spam_dsn_cutoff_level = models.FloatField(null=True, blank=True)
spam_quarantine_cutoff_level = models.FloatField(null=True, blank=True)
addr_extension_virus = models.CharField(max_length=192, blank=True)
addr_extension_spam = models.CharField(max_length=192, blank=True)
addr_extension_banned = models.CharField(max_length=192, blank=True)
addr_extension_bad_header = models.CharField(max_length=192, blank=True)
warnvirusrecip = models.CharField(max_length=3, blank=True)
warnbannedrecip = models.CharField(max_length=3, blank=True)
warnbadhrecip = models.CharField(max_length=3, blank=True)
newvirus_admin = models.CharField(max_length=192, blank=True)
virus_admin = models.CharField(max_length=192, blank=True)
banned_admin = models.CharField(max_length=192, blank=True)
bad_header_admin = models.CharField(max_length=192, blank=True)
spam_admin = models.CharField(max_length=192, blank=True)
spam_subject_tag = models.CharField(max_length=192, blank=True)
spam_subject_tag2 = models.CharField(max_length=192, blank=True)
message_size_limit = models.IntegerField(null=True, blank=True)
banned_rulenames = models.CharField(max_length=192, blank=True)
class Meta:
db_table = u'policy'
managed = False
class Quarantine(models.Model):
partition_tag = models.IntegerField(null=True, blank=True)
mail = models.ForeignKey(Msgs, primary_key=True)
chunk_ind = models.IntegerField()
mail_text = models.TextField()
class Meta:
db_table = u'quarantine'
managed = False
ordering = ["-mail__time_num"]
unique_together = ("mail", "chunk_ind")
class Users(models.Model):
id = models.AutoField(primary_key=True)
priority = models.IntegerField()
policy = models.ForeignKey(Policy)
email = models.CharField(unique=True, max_length=255)
fullname = models.CharField(max_length=765, blank=True)
local = models.CharField(max_length=3, blank=True)
class Meta:
db_table = u'users'
managed = False
class Wblist(models.Model):
rid = models.IntegerField(primary_key=True)
sid = models.IntegerField(primary_key=True)
wb = models.CharField(max_length=30)
class Meta:
db_table = u'wblist'
managed = False
@@ -0,0 +1,129 @@
# coding: utf-8
from datetime import datetime
from django.utils.translation import ugettext as _, ugettext_lazy
from django.db.models import Q
from modoboa.lib import tables
from modoboa.lib.webutils import static_url
from modoboa.lib.email_listing import MBconnector, EmailListing
from modoboa.lib.emailutils import *
from models import *
class Qtable(tables.Table):
tableid = "emails"
styles = "table-condensed"
idkey = "mailid"
type = tables.Column(
"type", align="center", width="30px",
label="<input type='checkbox' name='toggleselect' id='toggleselect' />",
sortable=False
)
rstatus = tables.ImgColumn("rstatus", width='25px')
from_ = tables.Column("from", label=ugettext_lazy("From"), limit=30)
subject = tables.Column("subject", label=ugettext_lazy("Subject"), limit=40)
time = tables.Column("date", label=ugettext_lazy("Date"))
to = tables.Column("to", label=ugettext_lazy("To"), sortable=False)
cols_order = []
def parse_date(self, value):
return datetime.fromtimestamp(value)
class SQLconnector(MBconnector):
orders = {
"from" : "mail__from_addr",
"subject" : "mail__subject",
"date" : "mail__time_num"
}
def __init__(self, mail_ids=None, filter=None):
self.count = None
self.mail_ids = mail_ids
self.filter = filter
def messages_count(self, **kwargs):
if self.count is None:
filter = Q(chunk_ind=1)
if self.mail_ids is not None:
filter &= Q(mail__in=self.mail_ids)
if self.filter:
filter &= self.filter
self.messages = Quarantine.objects.filter(filter)
if kwargs.has_key("order"):
totranslate = kwargs["order"][1:]
sign = kwargs["order"][:1]
if sign == " ":
sign = ""
order = sign + self.orders[totranslate]
self.messages = self.messages.order_by(order)
self.count = self.messages.count()
return self.count
def fetch(self, start=None, stop=None, **kwargs):
messages = self.messages[start - 1:stop]
emails = []
for qm in messages:
for rcpt in qm.mail.msgrcpt_set.all():
m = {"from" : qm.mail.from_addr,
"to" : rcpt.rid.email,
"subject" : qm.mail.subject,
"mailid" : qm.mail_id,
"date" : qm.mail.time_num,
"type" : qm.mail.content}
if rcpt.rs == '':
m["class"] = "unseen"
elif rcpt.rs == 'R':
m["img_rstatus"] = static_url("pics/release.png")
elif rcpt.rs == 'p':
m["class"] = "pending"
emails.append(m)
return emails
class SQLlisting(EmailListing):
tpl = "amavis_quarantine/index.html"
tbltype = Qtable
deflocation = "listing/"
defcallback = "updatelisting"
reset_wm_url = True
def __init__(self, user, msgs, filter, **kwargs):
if user.group == 'SimpleUsers':
Qtable.cols_order = ['type', 'rstatus', 'from_', 'subject', 'time']
else:
Qtable.cols_order = ['type', 'rstatus', 'to', 'from_', 'subject', 'time']
self.mbc = SQLconnector(msgs, filter)
super(SQLlisting, self).__init__(**kwargs)
class SQLemail(Email):
def __init__(self, msg, *args, **kwargs):
super(SQLemail, self).__init__(msg, *args, **kwargs)
fields = ["From", "To", "Cc", "Date", "Subject"]
for f in fields:
label = f
self.headers += [{"name" : label, "value" : self.get_header(msg, f)}]
try:
label = re.sub("-", "_", label)
setattr(self, label, msg[f])
except:
pass
qreason = self.get_header(msg, "X-Amavis-Alert")
self.qtype = ""
self.qreason = ""
if qreason != "":
self.qtype, self.qreason = qreason.split(',', 1)
def get_header(self, msg, name):
if msg.has_key(name):
return msg[name]
name = name.upper()
if msg.has_key(name):
return msg[name]
return ""
def render_headers(self, **kwargs):
return render_to_string("amavis_quarantine/mailheaders.html", {
"qtype" : self.qtype, "qreason" : self.qreason,
"headers" : self.headers,
})
@@ -0,0 +1,40 @@
#menubar {
position: fixed;
top: 60px;
padding-left: 15px;
padding-right: 15px;
left: 0;
right: 0;
}
#listing {
position: fixed;
padding: 0 15px;
right: 0;
left: 0;
}
#mailcontent {
border: 0;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#emails tbody tr:hover {
color: #0088cc;
}
thead tr {
position: relative;
z-index: 1;
}
td.unseen {
font-weight: bold;
}
td.pending {
font-style: italic;
}
@@ -0,0 +1,20 @@
#menubar {
padding-left: 15px;
}
#listing {
position: absolute;
padding: 0px;
right: 0;
left: 0;
bottom: 0;
overflow: hidden;
}
#mailcontent {
border: 0;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
@@ -0,0 +1,220 @@
var Quarantine = function(options) {
this.initialize(options);
};
Quarantine.prototype = {
constructor: Quarantine,
defaults: {
deflocation: "listing",
defcallback: "listing_cb"
},
initialize: function(options) {
this.options = $.extend({}, this.defaults, options);
this.navobj = new History(this.options);
this.register_navcallbacks();
this.listen();
},
update_page: function(data) {
if (data.menu != undefined) {
$("#menubar").html(data.menu);
$("#searchfield").searchbar({navobj: this.navobj});
}
if (data.navbar) {
$("#bottom-bar-right").html(data.navbar);
}
if (data.listing != undefined) {
$("#listing").html(data.listing);
$("#listing").css({
top: $("#menubar").outerHeight() + 60 + "px",
bottom: $("#bottom-bar").outerHeight() + "px",
overflow: "auto"
});
}
},
listen: function() {
$(document).on("dblclick", "tbody>tr", $.proxy(this.viewmail_loader, this));
$(document).on("click", "a[name=selectmsgs]", $.proxy(this.selectmsgs, this));
$(document).on("click", "a[name=release-multi]",
$.proxy(this.release_selection, this));
$(document).on("click", "a[name=delete-multi]",
$.proxy(this.delete_selection, this));
$(document).on("click", "a[name=viewrequests]",
$.proxy(this.view_requests, this));
$(document).on("click", "#bottom-bar a", $.proxy(this.load_page, this));
$(document).on("click", "a[name=release]", $.proxy(this.release, this));
$(document).on("click", "a[name=delete]", $.proxy(this.delete, this));
$(document).on("click", "a[name=headers]", $.proxy(this.headers, this));
},
load_page: function(e) {
e.preventDefault();
var $link = $(e.target).parent();
this.navobj.delparam("rcpt");
this.navobj.from_string($link.attr("href")).update();
},
view_requests: function(e) {
e.preventDefault();
this.navobj.setparam("viewrequests", "1").update();
},
viewmail_loader: function(e) {
e.preventDefault();
var $tr = $(e.target).parent();
var $to = $tr.find("td[name=to]");
this.navobj.baseurl($tr.attr("id"));
if ($to.length) {
this.navobj.setparam("rcpt", $to.html().trim());
}
this.navobj.update();
},
selectmsgs: function(e) {
e.preventDefault();
var type = $(e.target).attr("href");
if (type == "") {
$("#emails").htmltable("clear_selection");
return;
}
$("td[name=type]").each(function() {
var $this = $(this);
if ($this.html().trim() == type) {
$("#emails").htmltable("select_row", $this.parent());
}
});
},
_send_selection: function(e, name, message) {
var $link = $(e.target);
e.preventDefault();
if (!this.htmltable.current_selection().length ||
!confirm(message)) {
return;
}
var selection = [];
this.htmltable.current_selection().each(function() {
var $tr = $(this);
var $to = $tr.find("td[name=to]");
if ($to.length) {
selection.push($to.html().trim() + " " + $tr.attr("id"));
} else {
selection.push($tr.attr("id"));
}
});
$.ajax({
url: $link.attr("href"),
data: "action=" + name + "&selection=" + selection.join(","),
type: 'POST',
dataType: 'json',
success: $.proxy(this.action_cb, this)
});
},
release_selection: function(e) {
this._send_selection(e, "release", gettext("Release this selection?"));
},
delete_selection: function(e) {
this._send_selection(e, "delete", gettext("Delete this selection?"));
},
_send_action: function(e, message) {
var $link = $(e.target);
e.preventDefault();
if (!confirm(message)) {
return;
}
$.ajax({
url: $link.attr("href"),
dataType: 'json',
success: $.proxy(this.action_cb, this)
});
},
release: function(e) {
this._send_action(e, gettext("Release this message?"));
},
delete: function(e) {
this._send_action(e, gettext("Delete this message?"));
},
show_rawheaders: function($mailcontent) {
$mailcontent.find("#rawheaders").removeClass("hidden");
$mailcontent.find("#emailheaders").addClass("hidden");
},
headers: function(e) {
e.preventDefault();
var $link = $(e.target);
var $mailcontent = $("#mailcontent").contents();
var $headers = $mailcontent.find("#emailheaders");
var $rawheaders = $mailcontent.find("#rawheaders");
if ($headers.hasClass("hidden")) {
$link.html(gettext("View full headers"));
$headers.removeClass("hidden");
$rawheaders.addClass("hidden");
return;
}
$link.html(gettext("Hide full headers"));
if (!$rawheaders.length) {
$.ajax({
url: $link.attr("href"),
success: $.proxy(function(data) {
$mailcontent.find("#table-container").append($(data));
this.show_rawheaders($mailcontent);
}, this)
});
return;
}
this.show_rawheaders($mailcontent);
},
update_params: function(e) {
var $link = $(e.target);
e.preventDefault();
this.navobj.updateparams($link.attr("href")).update();
},
register_navcallbacks: function() {
this.navobj.register_callback("_listing",
$.proxy(this.listing_cb, this));
this.navobj.register_callback("viewmail",
$.proxy(this.viewmail_cb, this));
},
listing_cb: function(data) {
this.update_page(data);
$("#emails").htmltable();
this.htmltable = $("#emails").data("htmltable");
},
viewmail_cb: function(data) {
this.update_page(data);
$("#listing").css("overflow", "hidden");
},
action_cb: function(data) {
if (data.status == "ok") {
this.navobj.parse_string(data.url, true).update(true);
$("body").notify("success", data.respmsg, 2000);
} else {
$("body").notify("error", data.respmsg);
}
}
};
@@ -0,0 +1,35 @@
function send_action(e, message) {
var $link = $(e.target);
e.preventDefault();
if (!confirm(message)) {
return;
}
$.ajax({
url: $link.attr("href"),
dataType: 'json',
success: function(data) {
if (data.status == "ok") {
$("body").notify("success", data.respmsg, 2000);
} else {
$("body").notify("error", data.respmsg);
}
}
});
}
function release(e) {
send_action(e, gettext("Release this message?"));
}
function remove(e) {
send_action(e, gettext("Delete this message?"));
}
$(document).ready(function() {
$("#listing").css({
top: $("#menubar").outerHeight() + 10
});
$(document).on("click", "a[name=release]", release);
$(document).on("click", "a[name=delete]", remove);
});
@@ -0,0 +1 @@
{% if pre %}<pre>{% endif %}{{ body }}{% if pre %}</pre>{% endif %}
@@ -0,0 +1,21 @@
{% extends "fixed.html" %}{% load i18n %}
{% block pagetitle %}{% trans "Quarantine management" %}{% endblock %}
{% block html_head %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}amavis_quarantine/css/quarantine.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery.htmltable.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/history.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/searchbar.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}amavis_quarantine/js/quarantine.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var qm = new Quarantine({
deflocation: "{{ deflocation }}",
defcallback: "{{ defcallback }}"
});
});
</script>
{% endblock %}
{% block fixed_content %}
<div id="menubar"></div>
<div id="listing"></div>
{% endblock %}
@@ -0,0 +1,5 @@
{% extends "common/mailheaders.html" %}
{% block emailheaders %}
{% if qtype %}<div class="alert alert-error"><strong>{{ qtype }}</strong> {{ qreason }}</div>{% endif %}
{{ block.super }}
{% endblock %}
@@ -0,0 +1,4 @@
<pre id="rawheaders" class="well">
{% for k, v in headers %}{{ k }}: {{ v }}
{% endfor %}
</pre>
@@ -0,0 +1,27 @@
<!DOCTYPE html>{% load i18n libextras amextras %}
<html lang="{{ LANGUAGE_CODE }}">
<head>
<meta charset="utf-8" />
<title>Modoboa</title>
<link rel="icon" type="image/png" href="{{ STATIC_URL }}css/logo-icon.png" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/bootstrap-responsive.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}amavis_quarantine/css/selfservice.css" />
<script src="{{ STATIC_URL }}js/jquery.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}js/bootstrap.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}js/global.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}js/notify.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}amavis_quarantine/js/selfservice.js" type="text/javascript"></script>
{% url django.views.i18n.javascript_catalog as catalog_url %}
<script type="text/javascript" src="{{ catalog_url }}"></script>
<script type="text/javascript">
set_media_url("{{ STATIC_URL }}");
</script>
</head>
<body>
<div id="fixed_content">
<div id="menubar">{% viewm_menu_simple user mail_id rcpt secret_id %}</div>
<div id="listing">{{ content }}</div>
</div>
</body>
</html>
@@ -0,0 +1,112 @@
from django import template
from django.template.loader import render_to_string
from django.template import Template, Context
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.conf import settings
from modoboa.lib.webutils import static_url
from modoboa.extensions import amavis_quarantine
register = template.Library()
@register.simple_tag
def viewm_menu(user, mail_id, rcpt):
entries = [
{"name" : "release",
"img" : "icon-white icon-ok",
"class" : "btn-success",
"url" : reverse(amavis_quarantine.views.release, args=[mail_id]) \
+ ("?rcpt=%s" % rcpt if rcpt else ""),
"label" : _("Release")},
{"name" : "delete",
"class" : "btn-danger",
"img" : "icon-white icon-trash",
"url" : reverse(amavis_quarantine.views.delete, args=[mail_id]) \
+ ("?rcpt=%s" % rcpt if rcpt else ""),
"label" : _("Delete")},
{"name" : "headers",
"url" : reverse(amavis_quarantine.views.viewheaders, args=[mail_id]),
"label" : _("View full headers")},
]
menu = render_to_string('common/buttons_list.html',
{"entries" : entries, "extraclasses" : "pull-left"})
entries = [{"name" : "close",
"url" : "javascript:history.go(-1);",
"img" : "icon-remove"}]
menu += render_to_string('common/buttons_list.html',
{"entries" : entries, "extraclasses" : "pull-right"})
return menu
@register.simple_tag
def viewm_menu_simple(user, mail_id, rcpt, secret_id=""):
entries = [
{"name" : "release",
"img" : "icon-white icon-ok",
"class" : "btn-success",
"url" : reverse(amavis_quarantine.views.release, args=[mail_id]) \
+ ("?rcpt=%s" % rcpt \
+ (("&secret_id=%s" % secret_id) if secret_id != "" else "")),
"label" : _("Release")},
{"name" : "delete",
"img" : "icon-white icon-trash",
"class" : "btn-danger",
"url" : reverse(amavis_quarantine.views.delete, args=[mail_id]) \
+ "?rcpt=%s" % rcpt \
+ ("&secret_id=%s" % secret_id if secret_id != "" else ""),
"label" : _("Delete")},
]
return render_to_string('common/buttons_list.html',
{"entries" : entries})
@register.simple_tag
def quar_menu(user):
entries = [
{"name" : "release-multi",
"url" : reverse(amavis_quarantine.views.process),
"img" : "icon-white icon-ok",
"class" : "btn-success",
"label" : _("Release")},
{"name" : "delete-multi",
"img" : "icon-white icon-trash",
"class" : "btn-danger",
"url" : reverse(amavis_quarantine.views.process),
"label" : _("Delete")},
{"name" : "select",
"url" : "",
"label" : _("Content Class"),
"menu" : [
{"name" : "selectmsgs",
"url" : "",
"label" : _("Nothing")},
{"name" : "selectmsgs",
"url" : "S",
"label" : _("Spam")},
{"name" : "selectmsgs",
"url" : "V",
"label" : _("Virus")},
{"name" : "selectmsgs",
"url" : "H",
"label" : _("Bad header")},
{"name" : "selectmsgs",
"url" : "M",
"label" : _("Bad MIME")}
]
}
]
if user.group != 'SimpleUsers':
extraopts = [{"name" : "to", "label" : _("To")}]
else:
extraopts = []
extracontent = render_to_string('common/email_searchbar.html', {
"STATIC_URL" : settings.STATIC_URL,
"extraopts" : extraopts
})
return render_to_string('common/buttons_list.html', dict(
entries=entries, extracontent=extracontent
))
@@ -0,0 +1,14 @@
from django.conf.urls.defaults import *
urlpatterns = patterns(
'modoboa.extensions.amavis_quarantine.views',
(r'^$', 'index'),
(r'^listing/$', '_listing'),
(r'^getmailcontent/(?P<mail_id>[\w\-\+]+)/$', 'getmailcontent'),
(r'^process/$', 'process'),
(r'^nbrequests/$', 'nbrequests'),
(r'^delete/(?P<mail_id>[\w\-\+]+)/$', 'delete'),
(r'^release/(?P<mail_id>[\w\-\+]+)/$', 'release'),
(r'^(?P<mail_id>[\w\-\+]+)/$', 'viewmail'),
(r'^(?P<mail_id>[\w\-\+]+)/headers/$', 'viewheaders'),
)
@@ -0,0 +1,309 @@
# coding: utf-8
import email
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.template import Template, Context
from django.utils import simplejson
from django.utils.translation import ugettext as _, ungettext
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators \
import login_required, user_passes_test
from django.db.models import Q
from modoboa.lib import parameters
from modoboa.lib.exceptions import ModoboaException
from modoboa.lib.webutils import _render, getctx, ajax_response, ajax_simple_response
from modoboa.admin.models import Mailbox
from lib import *
from templatetags.amextras import *
from modoboa.lib.email_listing import parse_search_parameters
from sql_listing import *
def __get_current_url(request):
if request.session.has_key("page"):
res = "?page=%s" % request.session["page"]
else:
res = ""
params = "&".join(map(lambda p: "%s=%s" % (p, request.session[p]),
filter(request.session.has_key, ["criteria", "pattern"])))
if params != "":
res += "?%s" % (params)
return res
def empty_quarantine(request):
content = "<div class='alert alert-info'>%s</div>" % _("Empty quarantine")
ctx = getctx("ok", level=2, listing=content, navbar="",
menu=quar_menu(request.user))
return HttpResponse(simplejson.dumps(ctx), mimetype="application/json")
@login_required
def _listing(request):
flt = None
rcptfilter = None
msgs = None
if not request.user.is_superuser and request.user.group != 'SimpleUsers':
if not len(request.user.get_domains()):
return empty_quarantine(request)
order = request.GET.get("order", "-date")
if not request.session.has_key("navparams"):
request.session["navparams"] = {}
request.session["navparams"]["order"] = order
parse_search_parameters(request)
if request.session.has_key("pattern"):
criteria = request.session["criteria"]
if criteria == "both":
criteria = "from_addr,subject,to"
for c in criteria.split(","):
if c == "from_addr":
nfilter = Q(mail__from_addr__contains=request.session["pattern"])
elif c == "subject":
nfilter = Q(mail__subject__contains=request.session["pattern"])
elif c == "to":
rcptfilter = request.session["pattern"]
continue
else:
raise Exception("unsupported search criteria %s" % c)
flt = nfilter if flt is None else flt | nfilter
if request.GET.get("viewrequests", None) == "1":
q = Q(rs='p')
else:
q = ~Q(rs='D')
if request.user.group == 'SimpleUsers':
q &= Q(rid__email=request.user.email)
else:
if not request.user.is_superuser:
doms = request.user.get_domains()
regexp = "(%s)" % '|'.join(map(lambda dom: dom.name, doms))
doms_q = Q(rid__email__regex=regexp)
q &= doms_q
if rcptfilter is not None:
q &= Q(rid__email__contains=rcptfilter)
msgs = Msgrcpt.objects.filter(q).values("mail_id")
if request.GET.has_key("page"):
request.session["page"] = request.GET["page"]
pageid = int(request.session["page"])
else:
if request.session.has_key("page"):
del request.session["page"]
pageid = 1
lst = SQLlisting(request.user, msgs, flt,
navparams=request.session["navparams"],
elems_per_page=int(parameters.get_user(request.user,
"MESSAGES_PER_PAGE")))
page = lst.paginator.getpage(pageid)
if not page:
return empty_quarantine(request)
content = lst.fetch(request, page.id_start, page.id_stop)
navbar = lst.render_navbar(page, "listing/?")
ctx = getctx("ok", listing=content, navbar=navbar,
menu=quar_menu(request.user))
return HttpResponse(simplejson.dumps(ctx), mimetype="application/json")
@login_required
def index(request):
return _render(request, "amavis_quarantine/index.html", dict(
deflocation="listing/", defcallback="listing_cb", selection="quarantine"
))
def getmailcontent_selfservice(request, mail_id):
from sql_listing import SQLemail
qmails = Quarantine.objects.filter(mail=mail_id)
content = ""
for qm in qmails:
content += qm.mail_text
msg = email.message_from_string(content)
mail = SQLemail(msg, mformat="plain", links="0")
return _render(request, "common/viewmail.html", {
"headers" : mail.render_headers(),
"mailbody" : mail.body
})
@selfservice(getmailcontent_selfservice)
def getmailcontent(request, mail_id):
from sql_listing import SQLemail
qmails = Quarantine.objects.filter(mail=mail_id)
content = ""
for qm in qmails:
content += qm.mail_text
msg = email.message_from_string(content)
mail = SQLemail(msg, mformat="plain", links="0")
return _render(request, "common/viewmail.html", {
"headers" : mail.render_headers(),
"mailbody" : mail.body
})
def viewmail_selfservice(request, mail_id,
tplname="amavis_quarantine/viewmail_selfservice.html"):
rcpt = request.GET.get("rcpt", None)
secret_id = request.GET.get("secret_id", "")
if rcpt is None:
raise Http404
content = Template("""
<iframe src="{% url modoboa.extensions.amavis_quarantine.views.getmailcontent mail_id %}" id="mailcontent"></iframe>
""").render(Context(dict(mail_id=mail_id)))
return _render(request, tplname, dict(
mail_id=mail_id, rcpt=rcpt, secret_id=secret_id, content=content
))
@selfservice(viewmail_selfservice)
def viewmail(request, mail_id):
if request.user.group != 'SimpleUsers':
rcpt = request.GET["rcpt"]
else:
rcpt = None
if request.user.has_mailbox:
mb = Mailbox.objects.get(user=request.user)
if not rcpt or rcpt == mb.full_address:
msgrcpt = Msgrcpt.objects.get(mail=mail_id, rid__email=mb.full_address)
msgrcpt.rs = 'V'
msgrcpt.save()
content = Template("""
<iframe src="{{ url }}" id="mailcontent"></iframe>
""").render(Context({"url" : reverse(getmailcontent, args=[mail_id])}))
menu = viewm_menu(request.user, mail_id, rcpt)
ctx = getctx("ok", menu=menu, listing=content)
return HttpResponse(simplejson.dumps(ctx), mimetype="application/json")
@login_required
def viewheaders(request, mail_id):
content = ""
for qm in Quarantine.objects.filter(mail=mail_id):
content += qm.mail_text
msg = email.message_from_string(content)
return _render(request, 'amavis_quarantine/viewheader.html', {
"headers" : msg.items()
})
def check_mail_id(request, mail_id):
if type(mail_id) in [str, unicode]:
if request.GET.has_key("rcpt"):
mail_id = ["%s %s" % (request.GET["rcpt"], mail_id)]
else:
mail_id = [mail_id]
return mail_id
def delete_selfservice(request, mail_id):
rcpt = request.GET.get("rcpt", None)
if rcpt is None:
raise ModoboaException(_("Invalid request"))
try:
msgrcpt = Msgrcpt.objects.get(mail=mail_id, rid__email=rcpt)
msgrcpt.rs = 'D'
msgrcpt.save()
except Msgrcpt.DoesNotExist:
raise ModoboaException(_("Invalid request"))
return ajax_simple_response(dict(status="ok", respmsg=_("Message deleted")))
@selfservice(delete_selfservice)
def delete(request, mail_id):
mail_id = check_mail_id(request, mail_id)
if request.user.group == 'SimpleUsers':
mb = Mailbox.objects.get(user=request.user)
msgrcpts = Msgrcpt.objects.filter(mail__in=mail_id, rid__email=mb.full_address)
msgrcpts.update(rs='D')
else:
for mid in mail_id:
r, i = mid.split()
msgrcpt = Msgrcpt.objects.get(mail=i, rid__email=r)
msgrcpt.rs = 'D'
msgrcpt.save()
message = ungettext("%(count)d message deleted successfully",
"%(count)d messages deleted successfully",
len(mail_id)) % {"count" : len(mail_id)}
return ajax_response(request, respmsg=message,
url=__get_current_url(request))
def release_selfservice(request, mail_id):
rcpt = request.GET.get("rcpt", None)
secret_id = request.GET.get("secret_id", None)
if rcpt is None or secret_id is None:
raise ModoboaException(_("Invalid request"))
try:
msgrcpt = Msgrcpt.objects.get(mail=mail_id, rid__email=rcpt)
except Msgrcpt.DoesNotExist:
raise ModoboaException(_("Invalid request"))
if secret_id != msgrcpt.mail.secret_id:
raise ModoboaException(_("Invalid request"))
if parameters.get_admin("USER_CAN_RELEASE") == "no":
msgrcpt.rs = 'p'
msg = _("Request sent")
else:
amr = AMrelease()
result = amr.sendreq(mail_id, secret_id, rcpt)
if result:
rcpt.rs = 'R'
msg = _("Message released")
else:
raise ModoboaException(result)
msgrcpt.save()
return ajax_simple_response(dict(status="ok", respmsg=msg))
@selfservice(release_selfservice)
def release(request, mail_id):
mail_id = check_mail_id(request, mail_id)
if request.user.group == 'SimpleUsers':
mb = Mailbox.objects.get(user=request.user)
msgrcpts = Msgrcpt.objects.filter(mail__in=mail_id, rid__email=mb.full_address)
if parameters.get_admin("USER_CAN_RELEASE") == "no":
msgrcpts.update(rs='p')
message = ungettext("%(count)d request sent",
"%(count)d requests sent",
len(mail_id)) % {"count" : len(mail_id)}
return ajax_response(request, "ok", respmsg=message,
url=__get_current_url(request))
else:
msgrcpts = []
for mid in mail_id:
r, i = mid.split()
msgrcpts += [Msgrcpt.objects.get(mail=i, rid__email=r)]
amr = AMrelease()
error = None
for rcpt in msgrcpts:
result = amr.sendreq(rcpt.mail.mail_id, rcpt.mail.secret_id, rcpt.rid.email)
if result:
rcpt.rs = 'R'
rcpt.save()
else:
error = result
break
if not error:
message = ungettext("%(count)d message released successfully",
"%(count)d messages released successfully",
len(mail_id)) % {"count" : len(mail_id)}
else:
message = error
return ajax_response(request, "ko" if error else "ok", respmsg=message,
url=__get_current_url(request))
@login_required
def process(request):
ids = request.POST.get("selection", "")
ids = ids.split(",")
if not len(ids):
return HttpResponseRedirect(reverse(index))
if request.POST["action"] == "release":
return release(request, ids)
if request.POST["action"] == "delete":
return delete(request, ids)
@login_required
@user_passes_test(lambda u: u.group != 'SimpleUsers')
def nbrequests(request):
nbrequests = get_nb_requests(request.user)
return ajax_simple_response(dict(status="ok", requests=nbrequests))
+135
View File
@@ -0,0 +1,135 @@
# coding: utf-8
"""
The *limits* extension
----------------------
"""
from django.contrib.auth.models import Permission, Group
from django.db import IntegrityError
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from modoboa.lib import events
from modoboa.extensions import ModoExtension, exts_pool
from models import *
from forms import ResourcePoolForm
import controls
import views
class Limits(ModoExtension):
name = "limits"
label = "Limits"
version = "1.0"
description = ugettext_lazy("Per administrator resources to limit the number of objects they can create")
def init(self):
from modoboa.admin.models import User, Domain
ct = ContentType.objects.get(app_label="admin", model="domain")
dagrp = Group.objects.get(name="DomainAdmins")
grp = Group(name="Resellers")
grp.save()
grp.permissions.add(*dagrp.permissions.all())
ct = ContentType.objects.get_for_model(Permission)
for pname in ["view_permissions"]:
perm = Permission.objects.get(content_type=ct, codename=pname)
grp.permissions.add(perm)
ct = ContentType.objects.get_for_model(Domain)
for pname in ["view_domains", "add_domain", "change_domain", "delete_domain"]:
perm = Permission.objects.get(content_type=ct, codename=pname)
grp.permissions.add(perm)
grp.save()
for user in User.objects.filter(groups__name='DomainAdmins'):
try:
controls.create_pool(user)
except IntegrityError:
pass
def destroy(self):
Group.objects.get(name="Resellers").delete()
exts_pool.register_extension(Limits)
@events.observe("GetExtraRoles")
def get_extra_roles(user):
if user.is_superuser:
return [("Resellers", _("Reseller")),]
return []
@events.observe("ExtraAdminContent")
def display_pool_usage(user, target, currentpage):
from django.template.loader import render_to_string
if target != "leftcol" or user.is_superuser:
return []
if currentpage == "identities":
names = ["mailboxes_limit", "mailbox_aliases_limit"]
if user.has_perm("admin.add_domain"):
names += ["domain_admins_limit"]
else:
names = ["domains_limit", "domain_aliases_limit"]
limits = user.limitspool.limit_set.filter(name__in=names, maxvalue__gt=0)
if len(limits) == 0:
return []
return [render_to_string("limits/poolusage.html", dict(limits=limits))]
@events.observe("ExtraAccountForm")
def extra_account_form(user, account=None):
if not user.is_superuser and not user.belongs_to_group("Resellers"):
return []
if account:
if not account.belongs_to_group("Resellers") and \
not account.belongs_to_group("DomainAdmins"):
return []
return [
dict(
id="resources", title=_("Resources"), cls=ResourcePoolForm
)
]
@events.observe("CheckExtraAccountForm")
def check_form_access(account, form):
if form["id"] != "resources":
return [True]
if not account.belongs_to_group("Resellers") and \
not account.belongs_to_group("DomainAdmins"):
return [False]
return [True]
@events.observe("FillAccountInstances")
def fill_account_instances(user, account, instances):
if not user.is_superuser and not user.belongs_to_group("Resellers"):
return
if not account.belongs_to_group("Resellers") and \
not account.belongs_to_group("DomainAdmins"):
return
instances["resources"] = account
@events.observe("GetStaticContent")
def get_static_content(user):
if user.group == "SimpleUsers":
return []
return """<style>
.resource {
margin: 5px 0;
}
.resource .progress {
margin-bottom: 0px;
}
.resource .progress .bar {
color: #000000;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$(".progress").tooltip();
});
</script>
"""
+166
View File
@@ -0,0 +1,166 @@
# coding: utf-8
"""
:mod:`controls` --- provides event handlers that check if limits are reached
----------------------------------------------------------------------------
"""
from modoboa.lib import events
from lib import *
from models import *
from modoboa.lib.permissions import get_object_owner
def check_limit(user, lname):
"""Check if a user has reached a defined limit
We check if the user will not reach the given limit after this
creation.
Raise a ``LimitReached`` exception if the limit is reached.
:param user: a ``User`` object
"""
try:
if user.limitspool.will_be_reached(lname):
raise LimitReached(user.limitspool.get_limit(lname))
except LimitsPool.DoesNotExist:
pass
def inc_limit(user, lname):
try:
user.limitspool.inc_curvalue(lname)
except LimitsPool.DoesNotExist:
pass
def dec_limit(user, lname):
if user is None:
return
try:
user.limitspool.dec_curvalue(lname)
except LimitsPool.DoesNotExist:
pass
def move_pool_resource(owner, user):
try:
pool = user.limitspool
except LimitsPool.DoesNotExist:
return
if not owner.is_superuser:
for ltpl in limits_tpl:
l = user.limitspool.get_limit(ltpl[0])
if l.maxvalue < 0:
continue
ol = owner.limitspool.get_limit(ltpl[0])
ol.curvalue += l.curvalue
ol.maxvalue += l.maxvalue
ol.save()
user.limitspool.delete()
@events.observe('CreateDomain')
def inc_nb_domains(user, domain):
inc_limit(user, 'domains_limit')
@events.observe('DeleteDomain')
def dec_nb_domains(domain):
owner = get_object_owner(domain)
dec_limit(owner, 'domains_limit')
for domalias in domain.domainalias_set.all():
dec_nb_domaliases(domalias)
for mailbox in domain.mailbox_set.all():
dec_nb_mailboxes(mailbox)
for mbalias in domain.alias_set.all():
dec_nb_mbaliases(mbalias)
@events.observe('DomainAliasCreated')
def inc_nb_domaliases(user, domalias):
inc_limit(user, 'domain_aliases_limit')
@events.observe('DomainAliasDeleted')
def dec_nb_domaliases(domainaliases):
from modoboa.admin.models import DomainAlias
if isinstance(domainaliases, DomainAlias):
domainaliases = [domainaliases]
for domainalias in domainaliases:
owner = get_object_owner(domainalias)
dec_limit(owner, 'domain_aliases_limit')
@events.observe('CreateMailbox')
def inc_nb_mailboxes(user, mailbox):
inc_limit(user, 'mailboxes_limit')
@events.observe('DeleteMailbox')
def dec_nb_mailboxes(mailboxes):
from modoboa.admin.models import Mailbox
if isinstance(mailboxes, Mailbox):
mailboxes = [mailboxes]
for mailbox in mailboxes:
owner = get_object_owner(mailbox)
dec_limit(owner, 'mailboxes_limit')
@events.observe('MailboxAliasCreated')
def inc_nb_mbaliases(user, mailboxalias):
inc_limit(user, 'mailbox_aliases_limit')
@events.observe('MailboxAliasDeleted')
def dec_nb_mbaliases(mailboxalias):
owner = get_object_owner(mailboxalias)
dec_limit(owner, 'mailbox_aliases_limit')
@events.observe('CanCreate')
def can_create_new_object(user, objtype):
check_limit(user, '%s_limit' % objtype)
@events.observe("AccountCreated")
def create_pool(user):
owner = get_object_owner(user)
if not owner.is_superuser and \
not owner.belongs_to_group("Resellers"):
return
if user.belongs_to_group("DomainAdmins"):
check_limit(owner, 'domain_admins_limit')
inc_limit(owner, 'domain_admins_limit')
if user.belongs_to_group("DomainAdmins") or \
user.belongs_to_group("Resellers"):
p = LimitsPool(user=user)
p.save()
p.create_limits()
@events.observe("AccountModified")
def on_account_modified(old, new):
owner = get_object_owner(old)
if owner.group not in ["SuperAdmins", "Resellers"]:
return
if not new.group in ["DomainAdmins", "Resellers"]:
move_pool_resource(owner, new)
try:
pool = new.limitspool
except LimitsPool.DoesNotExist:
p = LimitsPool(user=new)
p.save()
p.create_limits()
if old.oldgroup == "DomainAdmins":
if new.group != "DomainAdmins":
dec_limit(owner, 'domain_admins_limit')
return
if new.group == "DomainAdmins":
check_limit(owner, 'domain_admins_limit')
inc_limit(owner, 'domain_admins_limit')
@events.observe("AccountDeleted")
def on_account_deleted(account):
owner = get_object_owner(account)
if not owner.group in ["SuperAdmins", "Resellers"]:
return
move_pool_resource(owner, account)
if account.group == "DomainAdmins":
dec_limit(owner, 'domain_admins_limit')
@@ -0,0 +1 @@
[{"pk": 1, "model": "limits.limitspool", "fields": {"user": 2}}, {"pk": 1, "model": "limits.limit", "fields": {"curvalue": 0, "name": "domain_admins_limit", "pool": 1, "maxvalue": -2}}, {"pk": 2, "model": "limits.limit", "fields": {"curvalue": 0, "name": "domains_limit", "pool": 1, "maxvalue": -2}}, {"pk": 3, "model": "limits.limit", "fields": {"curvalue": 0, "name": "domain_aliases_limit", "pool": 1, "maxvalue": -2}}, {"pk": 4, "model": "limits.limit", "fields": {"curvalue": 0, "name": "mailboxes_limit", "pool": 1, "maxvalue": 5}}, {"pk": 5, "model": "limits.limit", "fields": {"curvalue": 0, "name": "mailbox_aliases_limit", "pool": 1, "maxvalue": 5}}]
+89
View File
@@ -0,0 +1,89 @@
# coding: utf-8
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User, Group
from models import *
from lib import *
class ResourcePoolForm(forms.Form):
domain_admins_limit = forms.IntegerField(
label=ugettext_lazy("Domain admins"),
help_text=ugettext_lazy("Maximum number of domain administrators this user can create")
)
domains_limit = forms.IntegerField(label=ugettext_lazy("Domains"),
help_text=ugettext_lazy("Maximum number of domains this user can create"))
domain_aliases_limit = forms.IntegerField(label=ugettext_lazy("Domain aliases"),
help_text=ugettext_lazy("Maximum number of domain aliases this user can create"))
mailboxes_limit = forms.IntegerField(label=ugettext_lazy("Mailboxes"),
help_text=ugettext_lazy("Maximum number of mailboxes this user can create"))
mailbox_aliases_limit = forms.IntegerField(label=ugettext_lazy("Mailbox aliases"),
help_text=ugettext_lazy("Maximum number of mailbox aliases this user can create"))
def __init__(self, *args, **kwargs):
if kwargs.has_key("instance"):
self.account = kwargs["instance"]
del kwargs["instance"]
super(ResourcePoolForm, self).__init__(*args, **kwargs)
if hasattr(self, "account"):
if self.account.group != "Resellers":
del self.fields["domain_admins_limit"]
del self.fields["domains_limit"]
del self.fields["domain_aliases_limit"]
self.load_from_user(self.account)
def check_limit_value(self, lname):
if self.cleaned_data[lname] < -1:
raise forms.ValidationError(_("Invalid limit"))
return self.cleaned_data[lname]
def clean_domains_limit(self):
return self.check_limit_value("domains_limit")
def clean_domain_aliases_limit(self):
return self.check_limit_value("domain_aliases_limit")
def clean_mailboxes_limit(self):
return self.check_limit_value("mailboxes_limit")
def clean_mailbox_aliases_limit(self):
return self.check_limit_value("mailbox_aliases_limit")
def load_from_user(self, user):
for l in limits_tpl:
if not self.fields.has_key(l[0]):
continue
self.fields[l[0]].initial = user.limitspool.getmaxvalue(l[0])
def allocate_from_pool(self, limit, pool):
ol = pool.get_limit(limit.name)
if ol.maxvalue == -2:
raise BadLimitValue(_("Your resources are not initialized yet"))
newvalue = self.cleaned_data[limit.name]
if newvalue == -1 and ol.maxvalue != -1:
raise BadLimitValue(_("You're not allowed to define unlimited values"))
if limit.maxvalue > -1:
newvalue -= limit.maxvalue
if newvalue == 0:
return
remain = ol.maxvalue - ol.curvalue
if newvalue > remain:
raise UnsifficientResource(ol)
ol.maxvalue -= newvalue
ol.save()
def save(self):
from modoboa.lib.permissions import get_object_owner
owner = get_object_owner(self.account)
for ltpl in limits_tpl:
if not self.cleaned_data.has_key(ltpl[0]):
continue
l = self.account.limitspool.limit_set.get(name=ltpl[0])
if not owner.is_superuser:
self.allocate_from_pool(l, owner.limitspool)
l.maxvalue = self.cleaned_data[ltpl[0]]
l.save()
+35
View File
@@ -0,0 +1,35 @@
# coding: utf-8
"""
:mod:`lib` --- public functions
-------------------------------
"""
from django.contrib.auth.models import Group
from django.utils.translation import ugettext as _
from modoboa.lib.exceptions import ModoboaException
class LimitReached(ModoboaException):
def __init__(self, limit):
self.limit = limit
def __str__(self):
return _("%s: limit reached") % self.limit.label
class UnsifficientResource(ModoboaException):
def __init__(self, limit):
self.limit = limit
def __str__(self):
return _("Not enough resources")
class BadLimitValue(ModoboaException):
pass
def is_reseller(user):
"""Tell if a user is a reseller or not
:param user: a User object
:return: True if the user is a reseller, False otherwise.
"""
grp = Group.objects.get(name="Resellers")
return grp in user.groups.all()
@@ -0,0 +1,100 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'LimitsPool'
db.create_table('limits_limitspool', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True)),
))
db.send_create_signal('limits', ['LimitsPool'])
# Adding model 'Limit'
db.create_table('limits_limit', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('curvalue', self.gf('django.db.models.fields.IntegerField')(default=0)),
('maxvalue', self.gf('django.db.models.fields.IntegerField')(default=-2)),
('pool', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['limits.LimitsPool'])),
))
db.send_create_signal('limits', ['Limit'])
# Adding unique constraint on 'Limit', fields ['name', 'pool']
db.create_unique('limits_limit', ['name', 'pool_id'])
def backwards(self, orm):
# Removing unique constraint on 'Limit', fields ['name', 'pool']
db.delete_unique('limits_limit', ['name', 'pool_id'])
# Deleting model 'LimitsPool'
db.delete_table('limits_limitspool')
# Deleting model 'Limit'
db.delete_table('limits_limit')
models = {
'admin.user': {
'Meta': {'object_name': 'User', '_ormbases': ['auth.User']},
'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'limits.limit': {
'Meta': {'unique_together': "(('name', 'pool'),)", 'object_name': 'Limit'},
'curvalue': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'maxvalue': ('django.db.models.fields.IntegerField', [], {'default': '-2'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'pool': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['limits.LimitsPool']"})
},
'limits.limitspool': {
'Meta': {'object_name': 'LimitsPool'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['admin.User']", 'unique': 'True'})
}
}
complete_apps = ['limits']
+103
View File
@@ -0,0 +1,103 @@
# coding: utf-8
from django.db import models
from django.contrib.contenttypes import generic
from django.utils.translation import ugettext as _, ugettext_lazy
from modoboa.admin.models import User
limits_tpl = [
("domain_admins_limit", ugettext_lazy("Domain admins")),
("domains_limit", ugettext_lazy("Domains")),
("domain_aliases_limit", ugettext_lazy("Domain aliases")),
("mailboxes_limit", ugettext_lazy("Mailboxes")),
("mailbox_aliases_limit", ugettext_lazy("Mailbox aliases"))
]
class LimitsPool(models.Model):
user = models.OneToOneField(User)
def create_limits(self):
for ltpl in limits_tpl:
l = Limit()
l.name = ltpl[0]
l.pool = self
l.save()
def getcurvalue(self, lname):
l = self.limit_set.get(name=lname)
return l.curvalue
def getmaxvalue(self, lname):
l = self.limit_set.get(name=lname)
return l.maxvalue
def inc_curvalue(self, lname, nb=1):
l = self.limit_set.get(name=lname)
l.curvalue += nb
l.save()
def dec_curvalue(self, lname, nb=1):
l = self.limit_set.get(name=lname)
if not l.curvalue:
return
l.curvalue -= nb
l.save()
def dec_limit(self, lname, nb=1):
l = self.limit_set.get(name=lname)
l.curvalue -= nb
if l.maxvalue > -1:
l.maxvalue -= nb
l.save()
def inc_limit(self, lname, nb=1):
l = self.limit_set.get(name=lname)
l.curvalue += nb
if l.maxvalue > -1:
l.maxvalue += nb
l.save()
def will_be_reached(self, lname, nb=1):
l = self.limit_set.get(name=lname)
if l.maxvalue <= -1:
return False
if l.curvalue + nb > l.maxvalue:
return True
return False
def get_limit(self, lname):
try:
return self.limit_set.get(name=lname)
except Limit.DoesNotExist:
return None
class Limit(models.Model):
name = models.CharField(max_length=255)
curvalue = models.IntegerField(default=0)
maxvalue = models.IntegerField(default=-2)
pool = models.ForeignKey(LimitsPool)
class Meta:
unique_together = (("name", "pool"),)
@property
def usage(self):
if self.maxvalue < 0:
return -1
if self.maxvalue == 0:
return 0
return int(float(self.curvalue) / self.maxvalue * 100)
@property
def label(self):
for l in limits_tpl:
if l[0] == self.name:
return l[1]
return ""
def __str__(self):
if self.maxvalue == -2:
return _("undefined")
if self.maxvalue == -1:
return _("unlimited")
return "%d%%" % self.usage
@@ -0,0 +1,8 @@
{% load i18n libextras %}
<div class="well">
<h6>{% trans "Resources usage" %}</h6>{% for l in limits %}
<div class="resource">
{{ l.label }} ({{ l }})
<div rel="tooltip" title="{{ l.curvalue }}/{{ l.maxvalue }}" class="progress {% progress_color l.usage %}"><div class="bar" style="width: {{ l }}"></div></div>
</div>
{% endfor %}</div>
+6
View File
@@ -0,0 +1,6 @@
from django.conf.urls.defaults import *
urlpatterns = patterns(
'modoboa.extensions.limits.views',
)
+1
View File
@@ -0,0 +1 @@
# coding: utf-8
@@ -0,0 +1,113 @@
# coding: utf-8
"""
Postfix auto-replies plugin.
This module provides a way to integrate Modoboa auto-reply
functionality into Postfix.
"""
from django.conf.urls.defaults import include
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _, ugettext_lazy
from modoboa.lib import events, parameters
from modoboa.extensions import ModoExtension, exts_pool
from models import *
class PostfixAutoreply(ModoExtension):
name = "postfix_autoreply"
label = "Postfix autoreply"
version = "1.0"
description = ugettext_lazy("Auto-reply (vacation) functionality using Postfix")
def init(self):
from modoboa.admin.models import Domain
for dom in Domain.objects.all():
try:
trans = Transport.objects.get(domain="autoreply.%s" % dom.name)
except Transport.DoesNotExist:
onCreateDomain(None, dom)
else:
continue
for mb in dom.mailbox_set.all():
try:
alias = Alias.objects.get(full_address=mb.full_address)
except Alias.DoesNotExist:
onCreateMailbox(None, mb)
def load(self):
parameters.register_admin(
"AUTOREPLIES_TIMEOUT",
type="int", deflt=86400,
help=ugettext_lazy("Timeout in seconds between two auto-replies to the same recipient")
)
def destroy(self):
events.unregister("CreateDomain", onCreateDomain)
events.unregister("DeleteDomain", onDeleteDomain)
events.unregister("CreateMailbox", onCreateMailbox)
events.unregister("DeleteMailbox", onDeleteMailbox)
events.unregister("ModifyMailbox", onModifyMailbox)
events.unregister("UserMenuDisplay", menu)
parameters.unregister_app("postfix_autoreply")
exts_pool.register_extension(PostfixAutoreply)
@events.observe("UserMenuDisplay")
def menu(target, user):
import views
if target != "uprefs_menu":
return []
if not user.has_mailbox:
return []
return [
{"name" : "autoreply",
"url" : reverse(views.autoreply),
"label" : ugettext_lazy("Auto-reply message")}
]
@events.observe("CreateDomain")
def onCreateDomain(user, domain):
transport = Transport()
transport.domain = "autoreply.%s" % domain.name
transport.method = "autoreply:"
transport.save()
@events.observe("DeleteDomain")
def onDeleteDomain(domain):
trans = Transport.objects.get(domain="autoreply.%s" % domain.name)
trans.delete()
@events.observe("CreateMailbox")
def onCreateMailbox(user, mailbox):
alias = Alias()
alias.full_address = mailbox.full_address
alias.autoreply_address = \
"%s@autoreply.%s" % (mailbox.full_address, mailbox.domain.name)
alias.save()
@events.observe("DeleteMailbox")
def onDeleteMailbox(mailboxes):
from modoboa.admin.models import Mailbox
if isinstance(mailboxes, Mailbox):
mailboxes = [mailboxes]
for mailbox in mailboxes:
try:
alias = Alias.objects.get(full_address=mailbox.full_address)
except Alias.DoesNotExist:
pass
else:
alias.delete()
@events.observe("ModifyMailbox")
def onModifyMailbox(mailbox, oldmailbox):
if oldmailbox.full_address == mailbox.full_address:
return
alias = Alias.objects.get(full_address=oldmailbox.full_address)
alias.full_address = mailbox.full_address
alias.autoreply_address = \
"%s@autoreply.%s" % (mailbox.full_address, mailbox.domain.name)
alias.save()
@@ -0,0 +1,26 @@
# coding: utf-8
from django import forms
from models import ARmessage
from django.utils.translation import ugettext as _, ugettext_lazy
import datetime
class ARmessageForm(forms.ModelForm):
untildate = forms.DateField(
label=ugettext_lazy('Until'),
required=False,
help_text=ugettext_lazy("Activate your auto reply until this date")
)
class Meta:
model = ARmessage
fields = ('subject', 'content', 'enabled')
def __init__(self, *args, **kwargs):
super(ARmessageForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['subject', 'content', 'untildate', 'enabled']
def clean_untildate(self):
if self.cleaned_data["untildate"] is not None:
if self.cleaned_data["untildate"] < datetime.date.today():
raise forms.ValidationError(_("This date is over"))
return self.cleaned_data['untildate']
@@ -0,0 +1,52 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Transport'
db.create_table('postfix_autoreply_transport', (
('domain', self.gf('django.db.models.fields.CharField')(max_length=300)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('method', self.gf('django.db.models.fields.CharField')(max_length=255)),
))
db.send_create_signal('postfix_autoreply', ['Transport'])
# Adding model 'Alias'
db.create_table('postfix_autoreply_alias', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('full_address', self.gf('django.db.models.fields.CharField')(max_length=255)),
('autoreply_address', self.gf('django.db.models.fields.CharField')(max_length=255)),
))
db.send_create_signal('postfix_autoreply', ['Alias'])
def backwards(self, orm):
# Deleting model 'Transport'
db.delete_table('postfix_autoreply_transport')
# Deleting model 'Alias'
db.delete_table('postfix_autoreply_alias')
models = {
'postfix_autoreply.alias': {
'Meta': {'object_name': 'Alias'},
'autoreply_address': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'postfix_autoreply.transport': {
'Meta': {'object_name': 'Transport'},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'method': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['postfix_autoreply']
@@ -0,0 +1,132 @@
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from modoboa.lib.dbutils import db_table_exists
class Migration(SchemaMigration):
def forwards(self, orm):
# Renaming/Creating model 'ARmessage'
if db_table_exists('main_armessage'):
db.rename_table('main_armessage', 'postfix_autoreply_armessage')
else:
db.create_table('postfix_autoreply_armessage', (
('mbox', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['admin.Mailbox'])),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('subject', self.gf('django.db.models.fields.CharField')(max_length=255)),
('content', self.gf('django.db.models.fields.TextField')()),
('enabled', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True))
))
db.send_create_signal('postfix_autoreply', ['ARmessage'])
db.add_column('postfix_autoreply_armessage', 'untildate',
models.DateTimeField(null=True))
# Renaming model 'ARhistoric'
if db_table_exists('main_arhistoric'):
db.rename_table('main_arhistoric', 'postfix_autoreply_arhistoric')
else:
db.create_table('postfix_autoreply_arhistoric', (
('armessage', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['postfix_autoreply.ARmessage'])),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('last_sent', self.gf('django.db.models.fields.DateTimeField')(auto_now=True)),
('sender', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal('postfix_autoreply', ['ARhistoric'])
def backwards(self, orm):
raise RuntimeError("Cannot reverse this migration.")
models = {
'admin.domain': {
'Meta': {'object_name': 'Domain'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'quota': ('django.db.models.fields.IntegerField', [], {})
},
'admin.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Domain']"}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'gid': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'quota': ('django.db.models.fields.IntegerField', [], {}),
'uid': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'postfix_autoreply.alias': {
'Meta': {'object_name': 'Alias'},
'autoreply_address': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'full_address': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'postfix_autoreply.arhistoric': {
'Meta': {'object_name': 'ARhistoric'},
'armessage': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['postfix_autoreply.ARmessage']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_sent': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'sender': ('django.db.models.fields.TextField', [], {})
},
'postfix_autoreply.armessage': {
'Meta': {'object_name': 'ARmessage'},
'content': ('django.db.models.fields.TextField', [], {}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mbox': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['admin.Mailbox']"}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'untildate': ('django.db.models.fields.DateTimeField', [], {})
},
'postfix_autoreply.transport': {
'Meta': {'object_name': 'Transport'},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'method': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['postfix_autoreply']

Some files were not shown because too many files have changed in this diff Show More