Some minor housekeeping fixes.
[mailman-postorious.git] / src / postorius / views / domain.py
blob03f7c038f18fc954852df0c8b5b63e9b4a7d2c2d
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 1998-2021 by the Free Software Foundation, Inc.
4 # This file is part of Postorius.
6 # Postorius is free software: you can redistribute it and/or modify it under
7 # the terms of the GNU General Public License as published by the Free
8 # Software Foundation, either version 3 of the License, or (at your option)
9 # any later version.
11 # Postorius is distributed in the hope that it will be useful, but WITHOUT
12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 # more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Postorius. If not, see <http://www.gnu.org/licenses/>.
19 import logging
20 from urllib.error import HTTPError
22 from django.contrib import messages
23 from django.contrib.auth.decorators import login_required
24 from django.contrib.sites.models import Site
25 from django.http import Http404
26 from django.shortcuts import redirect, render
27 from django.utils.translation import gettext as _
28 from django.views.decorators.http import require_POST
30 from django_mailman3.lib.mailman import get_mailman_client
31 from django_mailman3.models import MailDomain
32 from django_mailman3.signals import domain_created, domain_deleted
34 from postorius.auth.decorators import superuser_required
35 from postorius.forms.domain_forms import (
36 DomainEditForm, DomainForm, DomainOwnerForm)
37 from postorius.models import Domain, Mailman404Error
40 log = logging.getLogger(__name__)
43 @login_required
44 @superuser_required
45 def domain_index(request):
46 existing_domains = Domain.objects.all()
47 for domain in existing_domains:
48 try:
49 web_host = MailDomain.objects.get(mail_domain=domain.mail_host)
50 except MailDomain.DoesNotExist:
51 site = Site.objects.get_current(request)
52 web_host = MailDomain.objects.create(
53 site=site, mail_domain=domain.mail_host)
54 domain.site = web_host.site
55 return render(request, 'postorius/domain/index.html', {
56 'domains': existing_domains,
60 @login_required
61 @superuser_required
62 def domain_new(request):
63 form_initial = {'site': Site.objects.get_current(request)}
64 if request.method == 'POST':
65 form = DomainForm(request.POST, initial=form_initial)
66 if form.is_valid():
67 domain = Domain(mail_host=form.cleaned_data['mail_host'],
68 description=form.cleaned_data['description'],
69 alias_domain=form.cleaned_data['alias_domain'],
70 owner=request.user.email)
71 try:
72 domain.save()
73 except HTTPError as e:
74 form.add_error('mail_host', e.reason)
75 else:
76 messages.success(request, _("New Domain registered"))
77 MailDomain.objects.get_or_create(
78 site=form.cleaned_data['site'],
79 mail_domain=form.cleaned_data['mail_host'])
80 domain_created.send(sender=Domain,
81 mail_host=form.cleaned_data['mail_host'])
82 return redirect("domain_index")
83 else:
84 form = DomainForm(initial=form_initial)
85 return render(request, 'postorius/domain/new.html', {'form': form})
88 @login_required
89 @superuser_required
90 def domain_edit(request, domain):
91 try:
92 domain_obj = Domain.objects.get(mail_host=domain)
93 except Mailman404Error:
94 raise Http404('Domain does not exist')
95 if request.method == 'POST':
96 form = DomainEditForm(request.POST)
97 if form.is_valid():
98 domain_obj.description = form.cleaned_data['description']
99 domain_obj.alias_domain = form.cleaned_data['alias_domain']
100 try:
101 web_host = MailDomain.objects.get(mail_domain=domain)
102 except MailDomain.DoesNotExist:
103 web_host = MailDomain.objects.create(
104 site=form.cleaned_data['site'], mail_domain=domain)
105 else:
106 web_host.site = form.cleaned_data['site']
107 web_host.save()
108 try:
109 domain_obj.save()
110 except HTTPError as e:
111 messages.error(request, e)
112 return redirect("domain_edit", domain=domain)
113 else:
114 messages.success(request, _("Domain %s updated") % domain)
115 return redirect("domain_index")
116 else:
117 messages.error(request, _('Please check the errors below'))
118 else:
119 form_initial = {
120 'description': domain_obj.description,
121 'alias_domain': domain_obj.alias_domain,
122 'site': MailDomain.objects.get(mail_domain=domain).site,
124 form = DomainEditForm(initial=form_initial)
126 return render(request, 'postorius/domain/edit.html', {
127 'domain': domain, 'form': form})
130 @login_required
131 @superuser_required
132 def domain_delete(request, domain):
133 """Deletes a domain but asks for confirmation first.
135 domain_obj = Domain.objects.get(mail_host=domain)
136 if request.method == 'POST':
137 try:
138 domain_obj.delete()
139 MailDomain.objects.filter(mail_domain=domain).delete()
140 messages.success(request,
141 _('The domain %s has been deleted.' % domain))
142 domain_deleted.send(sender=Domain, mail_host=domain)
143 return redirect("domain_index")
144 except HTTPError as e:
145 messages.error(request,
146 _('The domain could not be deleted: %s' % e.msg))
147 return redirect("domain_index")
148 domain_lists_page = domain_obj.get_list_page(count=10)
149 return render(request, 'postorius/domain/confirm_delete.html',
150 {'domain': domain_obj,
151 'lists': domain_lists_page})
154 @login_required
155 @superuser_required
156 def domain_owners(request, domain):
157 domain_obj = Domain.objects.get(mail_host=domain)
158 if request.method == 'POST':
159 form = DomainOwnerForm(request.POST)
160 if form.is_valid():
161 email = form.cleaned_data['email']
162 domain_obj.add_owner(email)
163 messages.success(request,
164 _('Added {} as an owner for {}'
165 ).format(email, domain_obj.mail_host))
166 return redirect("domain_index")
167 else:
168 form = DomainOwnerForm()
169 return render(request, 'postorius/domain/owners.html',
170 {'domain': domain_obj,
171 'form': form})
174 @require_POST
175 @login_required
176 @superuser_required
177 def remove_owners(request, domain, user_id):
178 domain_obj = Domain.objects.get(mail_host=domain)
179 # Since there is no way to remove one single owner, we do the only possible
180 # thing, remove all owners and add the rest back.
181 client = get_mailman_client()
182 try:
183 remove_email = client.get_user(user_id).addresses[0].email
184 all_owners_emails = [owner.addresses[0].email
185 for owner in domain_obj.owners]
186 except (KeyError, ValueError) as e:
187 # We get KeyError if the user has no address due to [0].
188 log.error('Unable to delete owner: %s', str(e))
189 raise Http404(str(e))
190 if remove_email in all_owners_emails:
191 all_owners_emails.remove(remove_email)
192 else:
193 messages.error(_('{} is not an owner for {}').format(
194 remove_email, domain_obj.mail_host))
195 return redirect("domain_index")
196 domain_obj.remove_all_owners()
197 for owner in all_owners_emails:
198 domain_obj.add_owner(owner)
199 messages.success(request,
200 _('Removed {} as an owner for {}'
201 ).format(remove_email, domain_obj.mail_host))
202 return redirect("domain_index")