views_domains.py 10.2 KB
Newer Older
Ale's avatar
Ale committed
1 2
# python
import os
Ale's avatar
Ale committed
3 4
# django
from django import views
5
from django.views.generic.edit import FormView
Ale's avatar
Ale committed
6 7 8
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
Ale's avatar
Ale committed
9
from django.contrib import messages
10
from django.utils.encoding import force_bytes
Ale's avatar
Ale committed
11
from django.utils.translation import ugettext_lazy as _
Ale's avatar
Ale committed
12 13 14 15
# contrib
from ldap3 import HASHED_SALTED_SHA
from ldap3.utils.hashed import hashed
from ldap3 import MODIFY_REPLACE
Ale's avatar
Ale committed
16 17
# project
from . import utils
Ale's avatar
Ale committed
18
from .forms import AddDomainForm, EditDomainForm
Ale's avatar
Ale committed
19 20 21 22 23 24 25 26 27
from django.conf import settings


class DomainsListView(views.View):
    """
    Domains list view.
    """

    def get(self, request):
Ale's avatar
Ale committed
28
        domains = utils.get_existing_domains(request.ldap)
29
        admin = utils.get_admin(self.request.ldap)
Ale's avatar
Ale committed
30 31 32 33 34 35 36 37 38 39 40
        return render(request, 'pages/domains.html', locals())

class AddDomainView(FormView):
    """
    Form to add a new domain.
    """

    template_name = 'pages/domains-add.html'
    form_class    = AddDomainForm
    success_url   = reverse_lazy('domains')

Ale's avatar
Ale committed
41 42 43
    def get_form(self):
        """Return an instance of the form to be used in this view."""

44
        # Get users to display them on the webmaster select list
Ale's avatar
Ale committed
45 46 47 48 49 50 51 52 53 54 55 56
        self.request.ldap.search(
            settings.LDAP_TREE_USERS,
            settings.LDAP_FILTERS_USERS_WEBMASTER_FORM,
            attributes=['uid']
        )
        users = [ user.uid.value for user in self.request.ldap.entries ]
        self.request.ldap.search(
            settings.LDAP_TREE_USERS,
            settings.LDAP_FILTERS_SUDOERS,
            attributes=['uid']
        )
        superuser = self.request.ldap.entries[0].uid.value
57
        users.insert(0,superuser)
58 59 60 61

        # List of existing domains, for form validation
        domains = utils.get_existing_domains(self.request.ldap)
        domain_list = [ domain.vd.value for domain in domains ]
62 63 64
        domains_in_use = utils.domain_is_in_use(self.request.ldap)
        domains_used_list = [ domain.status.value for domain in domains_in_use]
        return AddDomainForm(users=users, domain_list=domain_list, domains_used_list=domains_used_list,**self.get_form_kwargs())
Ale's avatar
Ale committed
65 66 67 68

    def form_valid(self, form, **kwargs):
        """ Hook to be triggered if form is valid. """

Ale's avatar
Ale committed
69
        domain = form['name'].value()
Ale's avatar
Ale committed
70
        mail   = str(form['mail_server'].value()).upper()
Ale's avatar
Ale committed
71 72 73 74 75
        admin  = form['webmaster'].value()
        dkim   = form['dkim'].value()

        try:
            # Add domain
MaadiX's avatar
MaadiX committed
76
            dn = 'vd=%s,o=hosting,%s' % (domain, settings.LDAP_TREE_BASE)
Ale's avatar
Ale committed
77 78 79 80 81 82 83
            self.request.ldap.add(dn, ['VirtualDomain', 'top'], {
                'vd'            : domain,
                'adminid'       : admin,
                'accountActive' : mail,
                'lastChange'    : utils.unix_timestamp(),
                'delete'        : 'FALSE',
            })
84
            # Create postmaster
Ale's avatar
Ale committed
85 86 87 88 89 90 91 92
            postmaster_dn  = 'cn=postmaster,' + dn
            postmaster_pwd = utils.gen_pwd()
            self.request.ldap.add(postmaster_dn, ['VirtualMailAlias', 'top'], {
                'cn'            : 'Postmaster',
                'sn'            : 'Postmaster',
                'mail'          : 'postmaster@%s' % domain,
                'maildrop'      : 'postmaster',
                'accountActive' : mail,
93
                'creationDate'  : utils.ldap_creation_date(),
Ale's avatar
Ale committed
94 95 96 97 98 99 100 101 102 103 104 105
                'lastChange'    : utils.unix_timestamp(),
                'userpassword'  : hashed(HASHED_SALTED_SHA, postmaster_pwd)
            })
            # Add abuse email
            mail     = 'abuse@' + domain
            abuse_dn = 'mail=%s,%s' % (mail, dn)
            self.request.ldap.add(abuse_dn, ['VirtualMailAlias', 'top'], {
                'cn'            : 'abuse',
                'sn'            : 'abuse',
                'mail'          : mail,
                'maildrop'      : 'postmaster',
                'accountActive' : 'TRUE',
106 107
                'creationDate'  : utils.ldap_creation_date(),
                'lastChange'    : utils.unix_timestamp()
Ale's avatar
Ale committed
108 109 110
            })
            # DKIM
            if dkim:
111
                utils.add_dkim(self.request.ldap, domain)
Ale's avatar
Ale committed
112 113

            # If Rainloop installed check if con file exists, else creates it
114
            if 'rainloop' in self.request.enabled_services:
Ale's avatar
Ale committed
115
                utils.check_rainloop_conf(domain)
116
            messages.success(self.request, _('Dominio %s añadido con éxito' % domain))
Ale's avatar
Ale committed
117 118
        except Exception as e:
            utils.p("view_domains.py", "✕ There's was a problem creating the domain %s" % domain, e)
119
            messages.error(self.request, _('Ha habido un problema creando el dominio %s.' % domain))
Ale's avatar
Ale committed
120 121

        return super(AddDomainView, self).form_valid(form)
Ale's avatar
Ale committed
122 123 124 125 126 127 128 129 130 131

class EditDomainView(FormView):
    """
    Form to edit a new domain.
    """

    template_name = 'pages/domain.html'
    form_class    = EditDomainForm
    success_url   = reverse_lazy('domains')

Ale's avatar
Ale committed
132 133 134 135 136 137 138 139
    def get_context_data(self, **kwargs):
        """Insert the form into the context dict."""

        self.domain_name = self.request.GET.get('domain')
        context = super(EditDomainView, self).get_context_data(**kwargs)
        context['domain'] = self.domain_name
        return context

Ale's avatar
Ale committed
140 141 142
    def get_form(self):
        """Return an instance of the form to be used in this view."""

Ale's avatar
Ale committed
143
        self.domain_name = self.request.GET.get('domain')
Ale's avatar
Ale committed
144 145 146 147 148
        domain      = utils.get_domain(self.request.ldap, self.domain_name)
        has_dkim    = utils.has_dkim(self.request.ldap, self.domain_name)
        kwargs = self.get_form_kwargs()
        kwargs['initial'] = {
            'webmaster'   : domain.adminid.value,
149
            'mail_server' : utils.ldap_val(domain.accountActive.value),
Ale's avatar
Ale committed
150 151 152 153
            'dkim'        : has_dkim,
            'old_dkim'    : has_dkim,
        }
        users = utils.get_users(self.request.ldap)
admin's avatar
admin committed
154
        return EditDomainForm(users=users, domain=self.domain_name,**kwargs)
Ale's avatar
Ale committed
155 156

    def form_valid(self, form):
Ale's avatar
Ale committed
157 158 159
        dn = 'vd=%s,%s' % (self.domain_name, settings.LDAP_TREE_HOSTING)
        webmaster = form['webmaster'].value()
        mail      = form['mail_server'].value()
160
        dkim     = bool(form['dkim'].value())
root's avatar
root committed
161
        old_dkim = utils.ldap_val(form['old_dkim'].value())
Ale's avatar
Ale committed
162

Ale's avatar
Ale committed
163 164 165 166 167 168
        try:
            self.request.ldap.modify(dn, {
                'adminid'       : [( MODIFY_REPLACE, webmaster )],
                'accountActive' : [( MODIFY_REPLACE, utils.ldap_bool(mail) )],
            })
        except Exception as e:
169
            utils.p("✕ view_domains.py", "There was a problem updating the domain", e)
Ale's avatar
Ale committed
170 171
            messages.error(self.request, _('Ha habido un error modificando el dominio. '
                                           'Si el problema persiste contacta '
172 173 174 175 176 177 178 179
                                         'con los administrador-s'))
        if dkim != old_dkim:
            if dkim:
                utils.add_dkim(self.request.ldap, self.domain_name)
            else:
                utils.remove_dkim(self.request.ldap, self.domain_name)

        messages.success(self.request, _('Dominio modificado con éxito'))
Ale's avatar
Ale committed
180
        return super(EditDomainView, self).form_valid(form)
181 182 183 184

class MailmanDomains(views.View):

    def get(self, request, *args, **kwargs):
185
        active_mail_domains = utils.get_active_maildomains(request.ldap)
186
        mailman_domains     = utils.get_mailman_domains()
MaadiX's avatar
MaadiX committed
187 188 189
        active              = _('Activado')
        inactive            = _('Desactivado')
        processing          = _('Procesando')
admin's avatar
admin committed
190
        has_dkim = False
MaadiX's avatar
MaadiX committed
191 192
        # Get dkim status in cpanel..if locked the puppet apply is going to be run
        # and dkim for mailman domains will be automatically creates
MaadiX's avatar
MaadiX committed
193
        #real_domains = utils.connect_to_postgre() 
admin's avatar
admin committed
194 195
        #dkim_cpanel_status = utils.get_dkim_status_cpanel(request.ldap)

196
        for domain in mailman_domains:
MaadiX's avatar
MaadiX committed
197
            domain['dkim_status'] = False
admin's avatar
admin committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
            try:
                request.ldap.search(
                    "ou=%s,%s" % (domain['mail_host'],settings.LDAP_TREE_DKIM ),
		    "(objectClass=organizationalUnit)"
		)
		# Check if dkim certificate exists in server 
                dkim_path = "/etc/opendkim/keys/%s/default.txt" % domain['mail_host']
                if os.path.isfile(dkim_path):
                    domain['DKIM'] = "<span class='fa fa-power-off enabled'></span> %s" % active  
		    # ou=aaa.com,ou=opendkim,ou=cpanel,dc=example,dc=tld

                # If dkim status is not ready, dkim is going to be created
                else:        
                    domain['DKIM'] = "<span class='fa fa-spin fa-cog'></span> %s" % processing 
                    # Run puppet local  to create dkim for mailman domains 
                    #domain['dkim_status'] =True 

            except Exception as e:
                print("There was a problem retrieving DKIM entry in LDAP: ")
                print( str(e) )
                #domain['DKIM'] = _('La clave DKIM no está activada para este dominio')
                domain['DKIM'] = "<span class='fa fa-power-off disabled'></span> "
                domain['dkim_status'] =True

            #domain['dkim_status'] = False
MaadiX's avatar
MaadiX committed
223
            # Check vhost web status for given domain
224
            if domain['mail_host'] in active_mail_domains:
MaadiX's avatar
MaadiX committed
225
                domain['status'] = "<span class='fa fa-power-off enabled'></span> %s" % active
226
            else:
MaadiX's avatar
MaadiX committed
227 228
                domain['status'] = "<span class='fa fa-power-off disabled'></span> %s" % inactive
            # Check if dkim certificate exists in server 
229
        return render(request, 'pages/mailman-domains.html', locals())
MaadiX's avatar
MaadiX committed
230 231 232 233 234 235 236 237 238

class CreateDkim(views.View):
    """ View to delete an entry from LDAP """

    def post(self, request):
        try:
            dn  = request.POST.get('dn')
            url = request.POST.get('url')
            # Create  item 
admin's avatar
admin committed
239 240
            utils.add_dkim(self.request.ldap, dn)
            # lock dkim cpanel
MaadiX's avatar
MaadiX committed
241 242 243 244 245 246 247 248 249 250
            utils.lock_dkim(self.request.ldap)
            messages.success(self.request, _('Creando certificado dkim para el dominio %s' % dn))
            return HttpResponseRedirect(url)
        except Exception as e:
            if settings.DEBUG:
                print(e)
            messages.error(self.request, _('Hubo algún problema creando el certifcado Dkim '
                                           'Contacta con los administrador-s si el problema persiste'))
            return HttpResponseRedirect(url)