Change tabs to spaces
authorMagnus Hagander <magnus@hagander.net>
Sun, 24 Feb 2019 11:11:46 +0000 (12:11 +0100)
committerMagnus Hagander <magnus@hagander.net>
Sun, 24 Feb 2019 11:11:46 +0000 (12:11 +0100)
pgmailmgr/auth.py
pgmailmgr/mailmgr/forms.py
pgmailmgr/mailmgr/models.py
pgmailmgr/mailmgr/views.py
pgmailmgr/settings.py

index c3118d518d56c75e7f1693e2798bc87d353e9b85..0a7101e85d8091269697c1ea44dc6529a9ab2335 100644 (file)
@@ -32,10 +32,10 @@ from Crypto.Cipher import AES
 import time
 
 class AuthBackend(ModelBackend):
-       # We declare a fake backend that always fails direct authentication -
-       # since we should never be using direct authentication in the first place!
-       def authenticate(self, username=None, password=None):
-               raise Exception("Direct authentication not supported")
+    # We declare a fake backend that always fails direct authentication -
+    # since we should never be using direct authentication in the first place!
+    def authenticate(self, username=None, password=None):
+        raise Exception("Direct authentication not supported")
 
 
 ####
@@ -44,85 +44,85 @@ class AuthBackend(ModelBackend):
 
 # Handle login requests by sending them off to the main site
 def login(request):
-       if request.GET.has_key('next'):
-               return HttpResponseRedirect("%s?su=%s" % (
-                               settings.PGAUTH_REDIRECT,
-                               quote_plus(request.GET['next']),
-                               ))
-       else:
-               return HttpResponseRedirect(settings.PGAUTH_REDIRECT)
+    if request.GET.has_key('next'):
+        return HttpResponseRedirect("%s?su=%s" % (
+                settings.PGAUTH_REDIRECT,
+                quote_plus(request.GET['next']),
+                ))
+    else:
+        return HttpResponseRedirect(settings.PGAUTH_REDIRECT)
 
 # Handle logout requests by logging out of this site and then
 # redirecting to log out from the main site as well.
 def logout(request):
-       if request.user.is_authenticated():
-               django_logout(request)
-       return HttpResponseRedirect("%slogout/" % settings.PGAUTH_REDIRECT)
+    if request.user.is_authenticated():
+        django_logout(request)
+    return HttpResponseRedirect("%slogout/" % settings.PGAUTH_REDIRECT)
 
 # Receive an authentication response from the main website and try
 # to log the user in.
 def auth_receive(request):
-       if request.GET.has_key('s') and request.GET['s'] == "logout":
-               # This was a logout request
-               return HttpResponseRedirect('/')
+    if request.GET.has_key('s') and request.GET['s'] == "logout":
+        # This was a logout request
+        return HttpResponseRedirect('/')
 
-       if not request.GET.has_key('i'):
-               raise Exception("Missing IV")
-       if not request.GET.has_key('d'):
-               raise Exception("Missing data!")
+    if not request.GET.has_key('i'):
+        raise Exception("Missing IV")
+    if not request.GET.has_key('d'):
+        raise Exception("Missing data!")
 
-       # Set up an AES object and decrypt the data we received
-       decryptor = AES.new(base64.b64decode(settings.PGAUTH_KEY),
-                                               AES.MODE_CBC,
-                                               base64.b64decode(str(request.GET['i']), "-_"))
-       s = decryptor.decrypt(base64.b64decode(str(request.GET['d']), "-_")).rstrip(' ')
+    # Set up an AES object and decrypt the data we received
+    decryptor = AES.new(base64.b64decode(settings.PGAUTH_KEY),
+                        AES.MODE_CBC,
+                        base64.b64decode(str(request.GET['i']), "-_"))
+    s = decryptor.decrypt(base64.b64decode(str(request.GET['d']), "-_")).rstrip(' ')
 
-       # Now un-urlencode it
-       try:
-               data = urlparse.parse_qs(s, strict_parsing=True)
-       except ValueError, e:
-               raise Exception("Invalid encrypted data received.")
+    # Now un-urlencode it
+    try:
+        data = urlparse.parse_qs(s, strict_parsing=True)
+    except ValueError, e:
+        raise Exception("Invalid encrypted data received.")
 
-       # Check the timestamp in the authentication
-       if (int(data['t'][0]) < time.time() - 10):
-               raise Exception("Authentication token too old.")
+    # Check the timestamp in the authentication
+    if (int(data['t'][0]) < time.time() - 10):
+        raise Exception("Authentication token too old.")
 
-       # Update the user record (if any)
-       try:
-               user = User.objects.get(username=data['u'][0])
-               # User found, let's see if any important fields have changed
-               changed = False
-               if user.first_name != data['f'][0]:
-                       user.first_name = data['f'][0]
-                       changed = True
-               if user.last_name != data['l'][0]:
-                       user.last_name = data['l'][0]
-                       changed = True
-               if user.email != data['e'][0]:
-                       user.email = data['e'][0]
-                       changed= True
-               if changed:
-                       user.save()
-       except User.DoesNotExist, e:
-               # User not found, create it!
-               user = User(username=data['u'][0],
-                                       first_name=data['f'][0],
-                                       last_name=data['l'][0],
-                                       email=data['e'][0],
-                                       password='setbypluginnotasha1',
-                                       )
-               user.save()
+    # Update the user record (if any)
+    try:
+        user = User.objects.get(username=data['u'][0])
+        # User found, let's see if any important fields have changed
+        changed = False
+        if user.first_name != data['f'][0]:
+            user.first_name = data['f'][0]
+            changed = True
+        if user.last_name != data['l'][0]:
+            user.last_name = data['l'][0]
+            changed = True
+        if user.email != data['e'][0]:
+            user.email = data['e'][0]
+            changed= True
+        if changed:
+            user.save()
+    except User.DoesNotExist, e:
+        # User not found, create it!
+        user = User(username=data['u'][0],
+                    first_name=data['f'][0],
+                    last_name=data['l'][0],
+                    email=data['e'][0],
+                    password='setbypluginnotasha1',
+                    )
+        user.save()
 
-       # Ok, we have a proper user record. Now tell django that
-       # we're authenticated so it persists it in the session. Before
-       # we do that, we have to annotate it with the backend information.
-       user.backend = "%s.%s" % (AuthBackend.__module__, AuthBackend.__name__)
-       django_login(request, user)
+    # Ok, we have a proper user record. Now tell django that
+    # we're authenticated so it persists it in the session. Before
+    # we do that, we have to annotate it with the backend information.
+    user.backend = "%s.%s" % (AuthBackend.__module__, AuthBackend.__name__)
+    django_login(request, user)
 
-       # Finally, redirect the user
-       if data.has_key('su'):
-               return HttpResponseRedirect(data['su'][0])
-       # No redirect specified, see if we have it in our settings
-       if hasattr(settings, 'PGAUTH_REDIRECT_SUCCESS'):
-               return HttpResponseRedirect(settings.PGAUTH_REDIRECT_SUCCESS)
-       raise Exception("Authentication successful, but don't know where to redirect!")
+    # Finally, redirect the user
+    if data.has_key('su'):
+        return HttpResponseRedirect(data['su'][0])
+    # No redirect specified, see if we have it in our settings
+    if hasattr(settings, 'PGAUTH_REDIRECT_SUCCESS'):
+        return HttpResponseRedirect(settings.PGAUTH_REDIRECT_SUCCESS)
+    raise Exception("Authentication successful, but don't know where to redirect!")
index 0514ee80a4172a1841c47920512c703442e6fb0e..bc957ec9f74f2b2644ce11ce50ca441d943f15e0 100644 (file)
@@ -5,119 +5,119 @@ from django.db import connection
 from models import *
 
 class VirtualUserForm(forms.ModelForm):
-       class Meta:
-               model = VirtualUser
-               fields = ('local_domain', 'local_part', 'mail_quota', 'passwd', 'full_name')
-
-       def __init__(self, data=None, instance=None, user=None):
-               super(VirtualUserForm, self).__init__(data=data, instance=instance)
-               self.user = user
-
-       def clean_local_domain(self):
-               if not self.instance.pk: return self.cleaned_data['local_domain']
-               if self.cleaned_data['local_domain'] != self.instance.local_domain:
-                       raise ValidationError("Can't change local domain!")
-               return self.cleaned_data['local_domain']
-       
-       def clean_local_part(self):
-               if not self.instance.pk: return self.cleaned_data['local_part']
-               if self.cleaned_data['local_part'] != self.instance.local_part:
-                       raise ValidationError("Renaming accounts is not possible - you have to delete and add!")
-               return self.cleaned_data['local_part']
-
-       def clean_mail_quota(self):
-               if self.cleaned_data['mail_quota'] <= 1:
-                       raise ValidationError("Mail quota must be set")
-               return self.cleaned_data['mail_quota']
-
-       def clean_passwd(self):
-               if self.cleaned_data['passwd'] != self.instance.passwd:
-                       # Changing password requires calling pgcrypto. So let's do that...
-                       curs = connection.cursor()
-                       curs.execute("SELECT public.crypt(%(pwd)s, public.gen_salt('md5'))", {
-                                       'pwd': self.cleaned_data['passwd']
-                                       })
-                       return curs.fetchall()[0][0]
-               
-               return self.cleaned_data['passwd']
-
-       def clean(self):
-               if not self.cleaned_data.has_key('local_part'):
-                       return {}
-
-               # Validate that the pattern is allowed
-               curs = connection.cursor()
-               curs.execute("SELECT 1 FROM mailmgr_userpermissions WHERE user_id=%(uid)s AND domain_id=%(domain)s AND %(lp)s ~* ('^'||pattern||'$')", {
-                               'uid': self.user.pk,
-                               'domain': self.cleaned_data['local_domain'].pk,
-                               'lp': self.cleaned_data['local_part'],
-                               })
-               perms = curs.fetchall()
-
-               if len(perms) < 1:
-                       raise ValidationError("Permission denied to create that user for that domain!")
-
-               # If it's a new user, also check against if it already exists
-               if not self.instance.pk:
-                       old = VirtualUser.objects.filter(local_part=self.cleaned_data['local_part'], local_domain=self.cleaned_data['local_domain'])
-                       if len(old):
-                               raise ValidationError("A user with that name already exists in that domain!")
-
-               # Make sure we can't get a collision with a forwarding
-               forwarders = Forwarder.objects.filter(local_part=self.cleaned_data['local_part'], local_domain=self.cleaned_data['local_domain'])
-               if len(forwarders):
-                       raise ValidationError("A forwarder with that name already exists in that domain!")
-
-               return self.cleaned_data
+    class Meta:
+        model = VirtualUser
+        fields = ('local_domain', 'local_part', 'mail_quota', 'passwd', 'full_name')
+
+    def __init__(self, data=None, instance=None, user=None):
+        super(VirtualUserForm, self).__init__(data=data, instance=instance)
+        self.user = user
+
+    def clean_local_domain(self):
+        if not self.instance.pk: return self.cleaned_data['local_domain']
+        if self.cleaned_data['local_domain'] != self.instance.local_domain:
+            raise ValidationError("Can't change local domain!")
+        return self.cleaned_data['local_domain']
+    
+    def clean_local_part(self):
+        if not self.instance.pk: return self.cleaned_data['local_part']
+        if self.cleaned_data['local_part'] != self.instance.local_part:
+            raise ValidationError("Renaming accounts is not possible - you have to delete and add!")
+        return self.cleaned_data['local_part']
+
+    def clean_mail_quota(self):
+        if self.cleaned_data['mail_quota'] <= 1:
+            raise ValidationError("Mail quota must be set")
+        return self.cleaned_data['mail_quota']
+
+    def clean_passwd(self):
+        if self.cleaned_data['passwd'] != self.instance.passwd:
+            # Changing password requires calling pgcrypto. So let's do that...
+            curs = connection.cursor()
+            curs.execute("SELECT public.crypt(%(pwd)s, public.gen_salt('md5'))", {
+                    'pwd': self.cleaned_data['passwd']
+                    })
+            return curs.fetchall()[0][0]
+        
+        return self.cleaned_data['passwd']
+
+    def clean(self):
+        if not self.cleaned_data.has_key('local_part'):
+            return {}
+
+        # Validate that the pattern is allowed
+        curs = connection.cursor()
+        curs.execute("SELECT 1 FROM mailmgr_userpermissions WHERE user_id=%(uid)s AND domain_id=%(domain)s AND %(lp)s ~* ('^'||pattern||'$')", {
+                'uid': self.user.pk,
+                'domain': self.cleaned_data['local_domain'].pk,
+                'lp': self.cleaned_data['local_part'],
+                })
+        perms = curs.fetchall()
+
+        if len(perms) < 1:
+            raise ValidationError("Permission denied to create that user for that domain!")
+
+        # If it's a new user, also check against if it already exists
+        if not self.instance.pk:
+            old = VirtualUser.objects.filter(local_part=self.cleaned_data['local_part'], local_domain=self.cleaned_data['local_domain'])
+            if len(old):
+                raise ValidationError("A user with that name already exists in that domain!")
+
+        # Make sure we can't get a collision with a forwarding
+        forwarders = Forwarder.objects.filter(local_part=self.cleaned_data['local_part'], local_domain=self.cleaned_data['local_domain'])
+        if len(forwarders):
+            raise ValidationError("A forwarder with that name already exists in that domain!")
+
+        return self.cleaned_data
 
 
 
 class ForwarderForm(forms.ModelForm):
-       class Meta:
-               model = Forwarder
-               fields = ('local_part', 'local_domain', 'remote_name')
-
-       def __init__(self, data=None, instance=None, user=None):
-               super(ForwarderForm, self).__init__(data=data, instance=instance)
-               self.user = user
-
-       def clean_local_domain(self):
-               if not self.instance.pk: return self.cleaned_data['local_domain']
-               if self.cleaned_data['local_domain'] != self.instance.local_domain:
-                       raise ValidationError("Can't change local domain!")
-               return self.cleaned_data['local_domain']
-       
-       def clean_local_part(self):
-               if not self.instance.pk: return self.cleaned_data['local_part']
-               if self.cleaned_data['local_part'] != self.instance.local_part:
-                       raise ValidationError("Renaming forwarders is not possible - you have to delete and add!")
-               return self.cleaned_data['local_part']
-
-       def clean(self):
-               if not self.cleaned_data.has_key('local_part'):
-                       return {}
-
-               # Validate that the pattern is allowed
-               curs = connection.cursor()
-               curs.execute("SELECT 1 FROM mailmgr_userpermissions WHERE user_id=%(uid)s AND domain_id=%(domain)s AND %(lp)s ~* ('^'||pattern||'$')", {
-                               'uid': self.user.pk,
-                               'domain': self.cleaned_data['local_domain'].pk,
-                               'lp': self.cleaned_data['local_part'],
-                               })
-               perms = curs.fetchall()
-
-               if len(perms) < 1:
-                       raise ValidationError("Permission denied to create that forwarder for that domain!")
-
-               # If it's a new user, also check against if it already exists
-               if not self.instance.pk:
-                       old = Forwarder.objects.filter(local_part=self.cleaned_data['local_part'], local_domain=self.cleaned_data['local_domain'])
-                       if len(old):
-                               raise ValidationError("A forwarder with that name already exists in that domain!")
-
-               # Make sure we can't get a collision with a user
-               users = VirtualUser.objects.filter(local_part=self.cleaned_data['local_part'], local_domain=self.cleaned_data['local_domain'])
-               if len(users):
-                       raise ValidationError("A user with that name already exists in that domain!")
-
-               return self.cleaned_data
+    class Meta:
+        model = Forwarder
+        fields = ('local_part', 'local_domain', 'remote_name')
+
+    def __init__(self, data=None, instance=None, user=None):
+        super(ForwarderForm, self).__init__(data=data, instance=instance)
+        self.user = user
+
+    def clean_local_domain(self):
+        if not self.instance.pk: return self.cleaned_data['local_domain']
+        if self.cleaned_data['local_domain'] != self.instance.local_domain:
+            raise ValidationError("Can't change local domain!")
+        return self.cleaned_data['local_domain']
+    
+    def clean_local_part(self):
+        if not self.instance.pk: return self.cleaned_data['local_part']
+        if self.cleaned_data['local_part'] != self.instance.local_part:
+            raise ValidationError("Renaming forwarders is not possible - you have to delete and add!")
+        return self.cleaned_data['local_part']
+
+    def clean(self):
+        if not self.cleaned_data.has_key('local_part'):
+            return {}
+
+        # Validate that the pattern is allowed
+        curs = connection.cursor()
+        curs.execute("SELECT 1 FROM mailmgr_userpermissions WHERE user_id=%(uid)s AND domain_id=%(domain)s AND %(lp)s ~* ('^'||pattern||'$')", {
+                'uid': self.user.pk,
+                'domain': self.cleaned_data['local_domain'].pk,
+                'lp': self.cleaned_data['local_part'],
+                })
+        perms = curs.fetchall()
+
+        if len(perms) < 1:
+            raise ValidationError("Permission denied to create that forwarder for that domain!")
+
+        # If it's a new user, also check against if it already exists
+        if not self.instance.pk:
+            old = Forwarder.objects.filter(local_part=self.cleaned_data['local_part'], local_domain=self.cleaned_data['local_domain'])
+            if len(old):
+                raise ValidationError("A forwarder with that name already exists in that domain!")
+
+        # Make sure we can't get a collision with a user
+        users = VirtualUser.objects.filter(local_part=self.cleaned_data['local_part'], local_domain=self.cleaned_data['local_domain'])
+        if len(users):
+            raise ValidationError("A user with that name already exists in that domain!")
+
+        return self.cleaned_data
index 3f2cb07212a852826f57f25b9937cc5b96fc2f3b..86100b452578a970fa751c60b4a16b6212f11ec4 100644 (file)
@@ -3,73 +3,73 @@ from django.contrib.auth.models import User
 from django.db.models import signals
 
 class LocalDomain(models.Model):
-       local_domain_id = models.AutoField(null=False, primary_key=True)
-       domain_name = models.CharField(max_length=100, null=False, blank=False)
-       path = models.CharField(max_length=512, null=False, blank=False)
-       unix_user = models.IntegerField(null=False, blank=False, default=0)
-       unix_group = models.IntegerField(null=False, blank=False, default=0)
+    local_domain_id = models.AutoField(null=False, primary_key=True)
+    domain_name = models.CharField(max_length=100, null=False, blank=False)
+    path = models.CharField(max_length=512, null=False, blank=False)
+    unix_user = models.IntegerField(null=False, blank=False, default=0)
+    unix_group = models.IntegerField(null=False, blank=False, default=0)
 
-       def __unicode__(self):
-               return self.domain_name
+    def __unicode__(self):
+        return self.domain_name
 
-       trigger_update = True
-       class Meta:
-               ordering=('domain_name',)
-               db_table='mail"."local_domains'
-               managed=False
+    trigger_update = True
+    class Meta:
+        ordering=('domain_name',)
+        db_table='mail"."local_domains'
+        managed=False
 
 class Forwarder(models.Model):
-       forwarder_id = models.AutoField(null=False, primary_key=True)
-       local_part = models.CharField(max_length=100, null=False, blank=False)
-       local_domain = models.ForeignKey(LocalDomain, null=False, blank=False, db_column='local_domain_id')
-       remote_name = models.CharField(max_length=200, null=False, blank=False)
+    forwarder_id = models.AutoField(null=False, primary_key=True)
+    local_part = models.CharField(max_length=100, null=False, blank=False)
+    local_domain = models.ForeignKey(LocalDomain, null=False, blank=False, db_column='local_domain_id')
+    remote_name = models.CharField(max_length=200, null=False, blank=False)
 
-       def __unicode__(self):
-               return "%s@%s -> %s" % (self.local_part, self.local_domain.domain_name, self.remote_name)
+    def __unicode__(self):
+        return "%s@%s -> %s" % (self.local_part, self.local_domain.domain_name, self.remote_name)
 
-       trigger_update = True
-       class Meta:
-               ordering=('local_part',)
-               db_table='mail"."forwarder'
-               managed=False
+    trigger_update = True
+    class Meta:
+        ordering=('local_part',)
+        db_table='mail"."forwarder'
+        managed=False
 
 class VirtualUser(models.Model):
-       virtual_user_id = models.AutoField(null=False, primary_key=True)
-       local_domain = models.ForeignKey(LocalDomain, null=False, blank=False, db_column='local_domain_id')
-       local_part = models.CharField(max_length=100, null=False, blank=False)
-       mail_quota = models.IntegerField(null=False)
-       passwd = models.CharField(max_length=100, null=False, blank=False, verbose_name="Password")
-       full_name = models.CharField(max_length=200, null=False, blank=True)
+    virtual_user_id = models.AutoField(null=False, primary_key=True)
+    local_domain = models.ForeignKey(LocalDomain, null=False, blank=False, db_column='local_domain_id')
+    local_part = models.CharField(max_length=100, null=False, blank=False)
+    mail_quota = models.IntegerField(null=False)
+    passwd = models.CharField(max_length=100, null=False, blank=False, verbose_name="Password")
+    full_name = models.CharField(max_length=200, null=False, blank=True)
 
-       def __unicode__(self):
-               return "%s@%s (%s)" % (self.local_part, self.local_domain.domain_name, self.full_name or '')
+    def __unicode__(self):
+        return "%s@%s (%s)" % (self.local_part, self.local_domain.domain_name, self.full_name or '')
 
-       trigger_update = True
-       class Meta:
-               ordering=('local_part',)
-               db_table='mail"."virtual_user'
-               managed=False
-               unique_together=('local_domain', 'local_part', )
+    trigger_update = True
+    class Meta:
+        ordering=('local_part',)
+        db_table='mail"."virtual_user'
+        managed=False
+        unique_together=('local_domain', 'local_part', )
 
 
 class UserPermissions(models.Model):
-       user = models.ForeignKey(User, null=False)
-       domain = models.ForeignKey(LocalDomain, null=False)
-       pattern = models.CharField(max_length=100, null=False, blank=False)
+    user = models.ForeignKey(User, null=False)
+    domain = models.ForeignKey(LocalDomain, null=False)
+    pattern = models.CharField(max_length=100, null=False, blank=False)
 
-       def __unicode__(self):
-               return "%s -> %s pattern '%s'" % (self.user, self.domain, self.pattern)
+    def __unicode__(self):
+        return "%s -> %s pattern '%s'" % (self.user, self.domain, self.pattern)
 
 class Log(models.Model):
-       user = models.ForeignKey(User, null=False)
-       when = models.DateTimeField(null=False, auto_now=True)
-       what = models.CharField(max_length=2048, null=False, blank=False)
+    user = models.ForeignKey(User, null=False)
+    when = models.DateTimeField(null=False, auto_now=True)
+    what = models.CharField(max_length=2048, null=False, blank=False)
 
-       def __unicode__(self):
-               return "%s (%s): %s" % (self.when, self.user, self.what)
+    def __unicode__(self):
+        return "%s (%s): %s" % (self.when, self.user, self.what)
 
-       class Meta:
-               ordering=('-when',)
+    class Meta:
+        ordering=('-when',)
 
 def pgmail_save_handler(sender, **kwargs):
     if hasattr(sender, 'trigger_update') and sender.trigger_update:
index 421e067b5753f3642a4754530e83030d7b6bfbb4..958f85b77b44aab5852c217cf09415c1ab0bfd17 100644 (file)
@@ -9,80 +9,80 @@ from models import *
 from forms import *
 
 def log(user, what):
-       l = Log()
-       l.user = user
-       l.what = what
-       l.save()
+    l = Log()
+    l.user = user
+    l.what = what
+    l.save()
 
 @login_required
 def home(request):
-       users = VirtualUser.objects.extra(where=["EXISTS (SELECT 1 FROM mailmgr_userpermissions p WHERE p.user_id=%s AND p.domain_id = local_domain_id AND local_part ~* ('^'||p.pattern||'$'))" % request.user.id])
-       forwards = Forwarder.objects.extra(where=["EXISTS (SELECT 1 FROM mailmgr_userpermissions p WHERE p.user_id=%s AND p.domain_id = local_domain_id AND local_part ~* ('^'||p.pattern||'$'))" % request.user.id])
+    users = VirtualUser.objects.extra(where=["EXISTS (SELECT 1 FROM mailmgr_userpermissions p WHERE p.user_id=%s AND p.domain_id = local_domain_id AND local_part ~* ('^'||p.pattern||'$'))" % request.user.id])
+    forwards = Forwarder.objects.extra(where=["EXISTS (SELECT 1 FROM mailmgr_userpermissions p WHERE p.user_id=%s AND p.domain_id = local_domain_id AND local_part ~* ('^'||p.pattern||'$'))" % request.user.id])
 
-       return render(request, 'home.html', {
-                       'users': users,
-                       'forwarders': forwards,
-                       })
+    return render(request, 'home.html', {
+            'users': users,
+            'forwarders': forwards,
+            })
 
 @transaction.atomic
 @login_required
 def userform(request, userparam):
-       if userparam == 'add':
-               vu = VirtualUser()
-       else:
-               vulist = VirtualUser.objects.filter(pk=userparam).extra(where=["EXISTS (SELECT 1 FROM mailmgr_userpermissions p WHERE p.user_id=%s AND p.domain_id = local_domain_id AND local_part ~* ('^'||p.pattern||'$'))" % request.user.id])
-               if len(vulist) != 1:
-                       raise Http404("Not found or no permissions!")
-               vu = vulist[0]
+    if userparam == 'add':
+        vu = VirtualUser()
+    else:
+        vulist = VirtualUser.objects.filter(pk=userparam).extra(where=["EXISTS (SELECT 1 FROM mailmgr_userpermissions p WHERE p.user_id=%s AND p.domain_id = local_domain_id AND local_part ~* ('^'||p.pattern||'$'))" % request.user.id])
+        if len(vulist) != 1:
+            raise Http404("Not found or no permissions!")
+        vu = vulist[0]
 
-       if request.method == 'POST':
-               form = VirtualUserForm(data=request.POST, instance=vu, user=request.user)
-               if request.POST['passwd'] != vu.passwd:
-                       password_changed=True
-               else:
-                       password_changed=False
-               if form.is_valid():
-                       form.save()
-                       messages.add_message(request, messages.INFO, 'User %s updated' % vu)
-                       if password_changed:
-                               messages.add_message(request, messages.INFO, 'Password changed for user %s' % vu)
-                               log(request.user, "%s user %s, including changing the password" % (userparam=='add' and 'Added' or 'Updated', vu))
-                       else:
-                               log(request.user, "%s user %s, without changing the password" % (userparam=='add' and 'Added' or 'Updated', vu))
-                       return HttpResponseRedirect('/')
-       else:
-               # Generate a new form
-               form = VirtualUserForm(instance=vu, user=request.user)
+    if request.method == 'POST':
+        form = VirtualUserForm(data=request.POST, instance=vu, user=request.user)
+        if request.POST['passwd'] != vu.passwd:
+            password_changed=True
+        else:
+            password_changed=False
+        if form.is_valid():
+            form.save()
+            messages.add_message(request, messages.INFO, 'User %s updated' % vu)
+            if password_changed:
+                messages.add_message(request, messages.INFO, 'Password changed for user %s' % vu)
+                log(request.user, "%s user %s, including changing the password" % (userparam=='add' and 'Added' or 'Updated', vu))
+            else:
+                log(request.user, "%s user %s, without changing the password" % (userparam=='add' and 'Added' or 'Updated', vu))
+            return HttpResponseRedirect('/')
+    else:
+        # Generate a new form
+        form = VirtualUserForm(instance=vu, user=request.user)
 
-       return render(request,'form.html', {
-                       'form': form,
-                       'savebutton': (userparam == 'new') and "New" or "Save"
-                       })
+    return render(request,'form.html', {
+            'form': form,
+            'savebutton': (userparam == 'new') and "New" or "Save"
+            })
 
 @transaction.atomic
 @login_required
 def forwarderform(request, userparam):
-       if userparam == 'add':
-               fwd = Forwarder()
-       else:
-               fwdlist = Forwarder.objects.filter(pk=userparam).extra(where=["EXISTS (SELECT 1 FROM mailmgr_userpermissions p WHERE p.user_id=%s AND p.domain_id = local_domain_id AND local_part ~* ('^'||p.pattern||'$'))" % request.user.id])
-               if len(fwdlist) != 1:
-                       raise Http404("Not found or no permissions!")
-               fwd = fwdlist[0]
+    if userparam == 'add':
+        fwd = Forwarder()
+    else:
+        fwdlist = Forwarder.objects.filter(pk=userparam).extra(where=["EXISTS (SELECT 1 FROM mailmgr_userpermissions p WHERE p.user_id=%s AND p.domain_id = local_domain_id AND local_part ~* ('^'||p.pattern||'$'))" % request.user.id])
+        if len(fwdlist) != 1:
+            raise Http404("Not found or no permissions!")
+        fwd = fwdlist[0]
 
-       if request.method == 'POST':
-               form = ForwarderForm(data=request.POST, instance=fwd, user=request.user)
-               if form.is_valid():
-                       form.save()
-                       log(request.user, "%s forwarding %s -> %s" % (userparam=='add' and 'Added' or 'Updated', fwd, fwd.remote_name))
-                       messages.add_message(request, messages.INFO, 'Forwarder %s updated' % fwd)
-                       return HttpResponseRedirect('/')
-       else:
-               # Generate a new form
-               form = ForwarderForm(instance=fwd, user=request.user)
+    if request.method == 'POST':
+        form = ForwarderForm(data=request.POST, instance=fwd, user=request.user)
+        if form.is_valid():
+            form.save()
+            log(request.user, "%s forwarding %s -> %s" % (userparam=='add' and 'Added' or 'Updated', fwd, fwd.remote_name))
+            messages.add_message(request, messages.INFO, 'Forwarder %s updated' % fwd)
+            return HttpResponseRedirect('/')
+    else:
+        # Generate a new form
+        form = ForwarderForm(instance=fwd, user=request.user)
 
-       return render(request, 'form.html', {
-                       'form': form,
-                       'savebutton': (userparam == 'new') and "New" or "Save"
-                       })
+    return render(request, 'form.html', {
+            'form': form,
+            'savebutton': (userparam == 'new') and "New" or "Save"
+            })
 
index 12d67bcb0d11e3b17fecb7fbd0615eb2e82b2e1f..279319c117313f044375e389a03b2e51152f7724 100644 (file)
@@ -7,7 +7,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
 
 ADMINS = (
-       ('PostgreSQL webmaster', 'webmaster@postgresql.org'),
+    ('PostgreSQL webmaster', 'webmaster@postgresql.org'),
 )
 
 MANAGERS = ADMINS
@@ -100,23 +100,23 @@ MIDDLEWARE_CLASSES = (
 ROOT_URLCONF = 'pgmailmgr.urls'
 
 TEMPLATES = [{
-       'BACKEND': 'django.template.backends.django.DjangoTemplates',
-       'OPTIONS': {
-               'context_processors': [
-                       'django.template.context_processors.request',
-                       'django.contrib.auth.context_processors.auth',
-                       'django.contrib.messages.context_processors.messages',
-               ],
-               'loaders': [
-                       'django.template.loaders.filesystem.Loader',
-                       'django.template.loaders.app_directories.Loader',
-               ],
-       },
+    'BACKEND': 'django.template.backends.django.DjangoTemplates',
+    'OPTIONS': {
+        'context_processors': [
+            'django.template.context_processors.request',
+            'django.contrib.auth.context_processors.auth',
+            'django.contrib.messages.context_processors.messages',
+        ],
+        'loaders': [
+            'django.template.loaders.filesystem.Loader',
+            'django.template.loaders.app_directories.Loader',
+        ],
+    },
 }]
 
 TEMPLATE_CONTEXT_PROCESSORS = (
-       'django.contrib.auth.context_processors.auth',
-       'django.contrib.messages.context_processors.messages',
+    'django.contrib.auth.context_processors.auth',
+    'django.contrib.messages.context_processors.messages',
 )
 
 INSTALLED_APPS = (
@@ -124,8 +124,8 @@ INSTALLED_APPS = (
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
-       # Need to load our app before admin, to override template
-       'pgmailmgr.mailmgr',
+    # Need to load our app before admin, to override template
+    'pgmailmgr.mailmgr',
     # Uncomment the next line to enable the admin:
     'django.contrib.admin',
     # Uncomment the next line to enable admin documentation: