views.py 34.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

18
from netaddr import IPNetwork
19 20
from django.views.generic import (TemplateView, UpdateView, DeleteView,
                                  CreateView)
21
from django.core.exceptions import ValidationError
22
from django.core.urlresolvers import reverse_lazy
23
from django.shortcuts import render, redirect, get_object_or_404
24
from django.http import HttpResponse, Http404
25 26 27

from django_tables2 import SingleTableView

Kálmán Viktor committed
28 29 30
from firewall.models import (
    Host, Vlan, Domain, Group, Record, BlacklistItem, Rule, VlanGroup,
    SwitchPort, EthernetDevice, Firewall)
31
from vm.models import Interface
Kálmán Viktor committed
32 33 34 35 36 37 38 39 40 41
from .tables import (
    HostTable, VlanTable, SmallHostTable, DomainTable, GroupTable,
    RecordTable, BlacklistItemTable, RuleTable, VlanGroupTable,
    SmallRuleTable, SmallGroupRuleTable, SmallRecordTable, SwitchPortTable,
    SmallDhcpTable, FirewallTable
)
from .forms import (
    HostForm, VlanForm, DomainForm, GroupForm, RecordForm, BlacklistItemForm,
    RuleForm, VlanGroupForm, SwitchPortForm, FirewallForm
)
42 43

from django.contrib import messages
44
from django.contrib.messages.views import SuccessMessageMixin
45 46
from django.views.generic.edit import FormMixin
from django.utils.translation import ugettext_lazy as _
47
from braces.views import LoginRequiredMixin, SuperuserRequiredMixin
48 49
# from django.db.models import Q
from operator import itemgetter
50
from itertools import chain
Kálmán Viktor committed
51
from dashboard.views import AclUpdateView
52
from dashboard.forms import AclUserOrGroupAddForm
53

54 55 56
try:
    from django.http import JsonResponse
except ImportError:
Bach Dániel committed
57
    from django.utils import simplejson
58

59 60 61 62 63 64 65 66 67 68 69 70
    class JsonResponse(HttpResponse):
        """JSON response for Django < 1.7
        https://gist.github.com/philippeowagner/3179eb475fe1795d6515
        """
        def __init__(self, content, mimetype='application/json',
                     status=None, content_type=None):
            super(JsonResponse, self).__init__(
                content=simplejson.dumps(content),
                mimetype=mimetype,
                status=status,
                content_type=content_type)

71

72 73 74 75 76 77 78 79 80 81
class MagicMixin(object):

    def get(self, *args, **kwargs):
        if self.request.is_ajax():
            result = self._get_ajax(*args, **kwargs)
            return JsonResponse({k: unicode(result[k] or "") for k in result})
        else:
            return super(MagicMixin, self).get(*args, **kwargs)


82 83 84 85 86
class InitialOwnerMixin(FormMixin):
    def get_initial(self):
        initial = super(InitialOwnerMixin, self).get_initial()
        initial['owner'] = self.request.user
        return initial
87 88


89
class IndexView(LoginRequiredMixin, SuperuserRequiredMixin, TemplateView):
90 91 92 93 94 95
    template_name = "network/index.html"

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)

        size = 13
96 97
        blacklists = BlacklistItem.objects.all().order_by(
            '-modified_at')[:size]
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
        domains = Domain.objects.all().order_by('-modified_at')[:size]
        groups = Group.objects.all().order_by('-modified_at')[:size]
        hosts = Host.objects.all().order_by('-modified_at')[:size]
        records = Record.objects.all().order_by('-modified_at')[:size]
        vlans = Vlan.objects.all().order_by('-modified_at')[:size]
        vlangroups = VlanGroup.objects.all().order_by('-modified_at')[:size]
        rules = Rule.objects.all().order_by('-modified_at')[:size]

        result_list = []
        for i in (sorted(chain(domains, groups, hosts, records, vlans,
                               vlangroups, rules),
                         key=lambda x: x.modified_at, reverse=True)[:size]):
            result_list.append(
                {
                    'class_name': unicode(i.__class__.__name__),
                    'modified_at': i.modified_at,
                    'created_at': i.created_at,
                    'name': unicode(i),
                    'link': i.get_absolute_url()
                })

        context['latest_blacklists'] = blacklists
        context['latest'] = result_list
        return context


124 125
class BlacklistList(LoginRequiredMixin, SuperuserRequiredMixin,
                    SingleTableView):
126 127
    model = BlacklistItem
    table_class = BlacklistItemTable
128 129 130 131
    template_name = "network/blacklist-list.html"
    table_pagination = False


132 133
class BlacklistDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                      SuccessMessageMixin, UpdateView):
134
    model = BlacklistItem
135
    template_name = "network/blacklist-edit.html"
136 137
    form_class = BlacklistItemForm
    success_message = _(u'Successfully modified blacklist item'
138 139 140 141 142 143 144 145 146 147 148 149
                        '%(ipv4)s - %(type)s!')

    def get_success_url(self):
        if 'pk' in self.kwargs:
            return reverse_lazy('network.blacklist', kwargs=self.kwargs)

    def get_context_data(self, **kwargs):
        context = super(BlacklistDetail, self).get_context_data(**kwargs)
        context['blacklist_pk'] = self.object.pk
        return context


150 151
class BlacklistCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                      SuccessMessageMixin, CreateView):
152
    model = BlacklistItem
153
    template_name = "network/blacklist-create.html"
154 155
    form_class = BlacklistItemForm
    success_message = _(u'Successfully created blacklist item '
156 157 158
                        '%(ipv4)s - %(type)s!')


159
class BlacklistDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
160
    model = BlacklistItem
161 162 163 164 165 166
    template_name = "network/confirm/base_delete.html"

    def get_context_data(self, **kwargs):
        """ display more information about the object """
        context = super(BlacklistDelete, self).get_context_data(**kwargs)
        if 'pk' in self.kwargs:
167
            to_delete = BlacklistItem.objects.get(pk=self.kwargs['pk'])
168 169 170 171 172 173 174 175 176 177 178 179 180
            context['object'] = "%s - %s - %s" % (to_delete.ipv4,
                                                  to_delete.reason,
                                                  to_delete.type)
            return context

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return self.request.POST['next']
        else:
            return reverse_lazy('network.blacklist_list')


181
class DomainList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
182 183 184 185 186 187
    model = Domain
    table_class = DomainTable
    template_name = "network/domain-list.html"
    table_pagination = False


188 189
class DomainDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                   SuccessMessageMixin, UpdateView):
190 191 192
    model = Domain
    template_name = "network/domain-edit.html"
    form_class = DomainForm
193
    success_message = _(u'Successfully modified domain %(name)s!')
194 195 196 197 198 199 200

    def get_success_url(self):
        if 'pk' in self.kwargs:
            return reverse_lazy('network.domain', kwargs=self.kwargs)

    def get_context_data(self, *args, **kwargs):
        context = super(DomainDetail, self).get_context_data(**kwargs)
201 202 203 204 205 206 207
        self.object = self.get_object()
        context['domain_pk'] = self.object.pk

        q = Record.objects.filter(
            domain=self.object,
            host__in=Host.objects.filter(
                interface__in=Interface.objects.filter(
208
                    instance__destroyed_at=None)
209 210
            )
        )
211 212 213 214
        context['record_list'] = SmallRecordTable(q)
        return context


215
class DomainCreate(LoginRequiredMixin, SuperuserRequiredMixin,
216
                   SuccessMessageMixin, InitialOwnerMixin, CreateView):
217 218 219
    model = Domain
    template_name = "network/domain-create.html"
    form_class = DomainForm
220
    success_message = _(u'Successfully created domain %(name)s!')
221 222


223
class DomainDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
224 225 226 227 228 229 230 231 232 233 234 235 236
    model = Domain
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return self.request.POST['next']
        else:
            return reverse_lazy('network.domain_list')

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        if unicode(self.object) != request.POST.get('confirm'):
237
            messages.error(request, _(u"Object name does not match!"))
238 239 240
            return self.get(request, *args, **kwargs)

        response = super(DomainDelete, self).delete(request, *args, **kwargs)
241
        messages.success(request, _(u"Domain successfully deleted!"))
242 243 244 245 246
        return response

    def get_context_data(self, **kwargs):
        context = super(DomainDelete, self).get_context_data(**kwargs)

247
        records_from_hosts = _(u'Records from hosts')
248 249 250 251 252
        deps = []
        # vlans
        vlans = Vlan.objects.filter(domain=self.object).all()
        if len(vlans) > 0:
            deps.append({
253
                'name': _('Vlans'),
254 255 256 257 258 259 260
                'data': vlans
            })

            # hosts
            hosts = Host.objects.filter(vlan__in=deps[0]['data'])
            if len(hosts) > 0:
                deps.append({
261
                    'name': _('Hosts'),
262 263 264 265 266
                    'data':  hosts
                })

                # records
                records = Record.objects.filter(
267 268
                    host__in=deps[1]['data']
                    # Q(domain=self.object) | (host__in=deps[1]['data'])
269 270 271
                )
                if len(records) > 0:
                    deps.append({
272
                        'name': records_from_hosts,
273 274 275
                        'data': records
                    })

276 277 278 279
        records = Record.objects.filter(domain=self.object)
        if len(records) > 0:
            # to filter out doubles (records from hosts and domains)
            indexes = map(itemgetter('name'), deps)
280
            n = indexes.index(records_from_hosts) if len(indexes) > 0 else 0
281
            deps.append({
282
                'name': u'Records only from the domain',
283 284 285 286
                'data': records.exclude(pk__in=deps[n]['data']) if n > 0
                else records
            })

287 288 289 290 291
        context['deps'] = deps
        context['confirmation'] = True
        return context


Kálmán Viktor committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
class FirewallList(LoginRequiredMixin, SuperuserRequiredMixin,
                   SingleTableView):
    model = Firewall
    table_class = FirewallTable
    template_name = "network/firewall-list.html"
    table_pagination = False


class FirewallDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                     SuccessMessageMixin, UpdateView):
    model = Firewall
    template_name = "network/firewall-edit.html"
    form_class = FirewallForm
    success_message = _(u'Succesfully modified firewall.')

    def get_success_url(self):
        if 'pk' in self.kwargs:
            return reverse_lazy('network.firewall', kwargs=self.kwargs)

    def get_context_data(self, **kwargs):
        context = super(FirewallDetail, self).get_context_data(**kwargs)
        return context


class FirewallCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                     SuccessMessageMixin, CreateView):
    model = Firewall
    template_name = "network/firewall-create.html"
    form_class = FirewallForm
    success_message = _(u'Successfully created firewall.')


class FirewallDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
    model = Firewall
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return next
        else:
            return reverse_lazy('network.firewall_list')


336
class GroupList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
337 338 339 340 341 342
    model = Group
    table_class = GroupTable
    template_name = "network/group-list.html"
    table_pagination = False


343
class GroupCreate(LoginRequiredMixin, SuperuserRequiredMixin,
344
                  SuccessMessageMixin, InitialOwnerMixin, CreateView):
345 346 347
    model = Group
    template_name = "network/group-create.html"
    form_class = GroupForm
348
    success_message = _(u'Successfully created host group %(name)s!')
349 350


351 352
class GroupDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                  SuccessMessageMixin, UpdateView):
353 354 355
    model = Group
    template_name = "network/group-edit.html"
    form_class = GroupForm
356
    success_message = _(u'Successfully modified host group %(name)s!')
357 358 359 360 361

    def get_success_url(self):
        if 'pk' in self.kwargs:
            return reverse_lazy('network.group', kwargs=self.kwargs)

362 363 364
    def get_context_data(self, *args, **kwargs):
        context = super(GroupDetail, self).get_context_data(**kwargs)

365 366
        context['group_pk'] = self.object.pk

367 368 369 370 371
        # records
        q = Rule.objects.filter(hostgroup=self.object)
        context['rule_list'] = SmallRuleTable(q)
        return context

372

373
class GroupDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    model = Group
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return self.request.POST['next']
        else:
            return reverse_lazy('network.group_list')

    def get_context_data(self, *args, **kwargs):
        context = super(GroupDelete, self).get_context_data(**kwargs)
        context['group_pk'] = self.object.pk
        return context


390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
class HostMagicMixin(MagicMixin):
    def _get_ajax(self, *args, **kwargs):
        GET = self.request.GET
        result = {}
        vlan = get_object_or_404(Vlan.objects, pk=GET.get("vlan", ""))
        if "ipv4" in GET:
            try:
                result["ipv6"] = vlan.convert_ipv4_to_ipv6(GET["ipv4"]) or ""
            except:
                result["ipv6"] = ""
        else:
            try:
                result.update(vlan.get_new_address())
            except ValidationError:
                result["ipv4"] = ""
                result["ipv6"] = ""
        return result


409
class HostList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
410 411 412 413 414 415 416 417 418 419 420 421 422 423
    model = Host
    table_class = HostTable
    template_name = "network/host-list.html"
    table_pagination = False

    def get_context_data(self, **kwargs):
        context = super(HostList, self).get_context_data(**kwargs)
        q = Vlan.objects.all().order_by("name")
        context['vlans'] = q
        return context

    def get_table_data(self):
        vlan_id = self.request.GET.get('vlan')
        if vlan_id:
424
            data = Host.objects.filter(vlan=vlan_id).select_related()
425
        else:
426
            data = Host.objects.select_related()
427 428 429
        return data


430
class HostDetail(HostMagicMixin, LoginRequiredMixin, SuperuserRequiredMixin,
431
                 SuccessMessageMixin, UpdateView):
432 433 434
    model = Host
    template_name = "network/host-edit.html"
    form_class = HostForm
435
    success_message = _(u'Successfully modified host %(hostname)s!')
436

437 438
    def _get_ajax(self, *args, **kwargs):
        if "vlan" not in self.request.GET:
439 440 441
            host = Host.objects.get(pk=kwargs['pk'])
            host = {
                'hostname': host.hostname,
442 443
                'ipv4': str(host.ipv4),
                'ipv6': str(host.ipv6),
444 445
                'fqdn': host.get_fqdn()
            }
446
            return host
447
        else:
448 449 450 451 452
            return super(HostDetail, self)._get_ajax(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super(HostDetail, self).get(request, *args, **kwargs)
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

    def post(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        # this is usually not None (well, with curl and whatnot it can be)
        if pk:
            groups = Host.objects.get(pk=pk).groups.all()
            groups = [i.pk for i in groups]
            # request.POST is immutable
            post_copy = request.POST.copy()
            post_copy.setlist('groups', groups)
            request.POST = post_copy
            return super(HostDetail, self).post(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(HostDetail, self).get_context_data(**kwargs)
        # own rules
        q = Rule.objects.filter(host=self.object).all()
        context['rule_list'] = SmallRuleTable(q)

        # rules from host groups
        group_rule_list = []
        for group in self.object.groups.all():
            q = Rule.objects.filter(hostgroup=group).all()
            group_rule_list.append({
                'table': SmallGroupRuleTable(q),
                'name': unicode(group),
                'pk': group.pk
            })
        context['group_rule_list'] = group_rule_list

        # available groups
        rest = Group.objects.exclude(pk__in=self.object.groups.all()).all()
        context['not_used_groups'] = rest

        # set host pk (we need this for URL-s)
        context['host_pk'] = self.kwargs['pk']

490 491 492
        from network.tables import HostRecordsTable
        context['records_table'] = HostRecordsTable(
            Record.objects.filter(host=self.get_object()),
493
            request=self.request, template="django_tables2/table_no_page.html"
494 495
        )

496 497 498 499 500 501 502
        return context

    def get_success_url(self):
        if 'pk' in self.kwargs:
            return reverse_lazy('network.host', kwargs=self.kwargs)


503
class HostCreate(HostMagicMixin, LoginRequiredMixin, SuperuserRequiredMixin,
504
                 SuccessMessageMixin, InitialOwnerMixin, CreateView):
505 506 507
    model = Host
    template_name = "network/host-create.html"
    form_class = HostForm
508
    success_message = _(u'Successfully created host %(hostname)s!')
509

510 511 512 513 514 515 516
    def get_initial(self):
        initial = super(HostCreate, self).get_initial()

        for i in ("vlan", "mac", "hostname"):
            if i in self.request.GET and i not in self.request.POST:
                initial[i] = self.request.GET[i]
        if "vlan" in initial:
517 518
            if not initial['vlan'].isnumeric():
                raise Http404()
519 520 521 522 523 524 525
            vlan = get_object_or_404(Vlan.objects, pk=initial['vlan'])
            try:
                initial.update(vlan.get_new_address())
            except ValidationError as e:
                messages.error(self.request, e.message)
        return initial

526

527
class HostDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
    model = Host
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return self.request.POST['next']
        else:
            return reverse_lazy('network.host_list')

    def get_context_data(self, *args, **kwargs):
        context = super(HostDelete, self).get_context_data(**kwargs)

        deps = []
        records = Record.objects.filter(host=self.object).all()
        if records:
            deps.append({
545
                'name': _('Records'),
546 547 548 549 550 551 552 553 554 555
                'data': records
            })

        context['deps'] = deps
        context['confirmation'] = True
        return context

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        if unicode(self.object) != request.POST.get('confirm'):
556
            messages.error(request, _(u"Object name does not match!"))
557 558 559
            return self.get(request, *args, **kwargs)

        response = super(HostDelete, self).delete(request, *args, **kwargs)
560
        messages.success(request, _(u"Host successfully deleted!"))
561 562 563
        return response


564
class RecordList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
565 566 567 568 569
    model = Record
    table_class = RecordTable
    template_name = "network/record-list.html"
    table_pagination = False

570 571 572 573 574 575 576 577 578 579 580 581 582
    def get_context_data(self, **kwargs):
        context = super(RecordList, self).get_context_data(**kwargs)
        context['types'] = Record.CHOICES_type
        return context

    def get_table_data(self):
        type_id = self.request.GET.get('type')
        if type_id:
            data = Record.objects.filter(type=type_id).select_related()
        else:
            data = Record.objects.select_related()
        return data

583

584 585
class RecordDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                   SuccessMessageMixin, UpdateView):
586 587 588 589
    model = Record
    template_name = "network/record-edit.html"
    form_class = RecordForm
    # TODO fqdn
590
    success_message = _(u'Successfully modified record!')
591 592 593 594 595 596 597 598 599 600 601 602

    def get_context_data(self, **kwargs):
        context = super(RecordDetail, self).get_context_data(**kwargs)
        context['fqdn'] = self.object.fqdn
        context['record_pk'] = self.object.pk
        return context

    def get_success_url(self):
        if 'pk' in self.kwargs:
            return reverse_lazy('network.record', kwargs=self.kwargs)


603
class RecordCreate(LoginRequiredMixin, SuperuserRequiredMixin,
604
                   SuccessMessageMixin, InitialOwnerMixin, CreateView):
605 606 607 608
    model = Record
    template_name = "network/record-create.html"
    form_class = RecordForm
    # TODO fqdn
609
    success_message = _(u'Successfully created record!')
610

611
    def get_initial(self):
612 613 614
        initial = super(RecordCreate, self).get_initial()
        initial['domain'] = self.request.GET.get('domain')

615 616 617 618 619 620 621 622 623 624 625 626 627
        host_pk = self.request.GET.get("host")
        try:
            host = Host.objects.get(pk=host_pk)
        except (Host.DoesNotExist, ValueError):
            host = None

        if host:
            initial.update({
                'type': "CNAME",
                'host': host,
                'address': host.get_fqdn(),
            })

628
        return initial
629

630

631
class RecordDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
632 633 634 635 636 637 638 639 640 641 642
    model = Record
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return self.request.POST['next']
        else:
            return reverse_lazy('network.record_list')


643
class RuleList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
644 645 646 647 648
    model = Rule
    table_class = RuleTable
    template_name = "network/rule-list.html"
    table_pagination = False

649 650 651 652 653
    def get_table_data(self):
        return Rule.objects.select_related('host', 'hostgroup', 'vlan',
                                           'vlangroup', 'firewall',
                                           'foreign_network', 'owner')

654

655 656
class RuleDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                 SuccessMessageMixin, UpdateView):
657 658 659
    model = Rule
    template_name = "network/rule-edit.html"
    form_class = RuleForm
660
    success_message = _(u'Successfully modified rule!')
661 662 663 664 665 666 667 668 669 670 671 672 673 674

    def get_success_url(self):
        if 'pk' in self.kwargs:
            return reverse_lazy('network.rule', kwargs=self.kwargs)

    def get_context_data(self, **kwargs):
        context = super(RuleDetail, self).get_context_data(**kwargs)

        rule = self.get_object()

        context['rule'] = rule
        return context


675
class RuleCreate(LoginRequiredMixin, SuperuserRequiredMixin,
676
                 SuccessMessageMixin, InitialOwnerMixin, CreateView):
677 678 679
    model = Rule
    template_name = "network/rule-create.html"
    form_class = RuleForm
680
    success_message = _(u'Successfully created rule!')
681

682
    def get_initial(self):
683 684
        initial = super(RuleCreate, self).get_initial()
        initial.update({
685 686
            'host': self.request.GET.get('host'),
            'hostgroup': self.request.GET.get('hostgroup')
687 688
        })
        return initial
689

690

691
class RuleDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
692 693 694 695 696 697 698 699 700 701 702
    model = Rule
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return next
        else:
            return reverse_lazy('network.rule_list')


703 704
class SwitchPortList(LoginRequiredMixin, SuperuserRequiredMixin,
                     SingleTableView):
705 706 707 708 709 710
    model = SwitchPort
    table_class = SwitchPortTable
    template_name = "network/switch-port-list.html"
    table_pagination = False


711 712
class SwitchPortDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                       SuccessMessageMixin, UpdateView):
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
    model = SwitchPort
    template_name = "network/switch-port-edit.html"
    form_class = SwitchPortForm
    success_message = _(u'Succesfully modified switch port!')

    def get_success_url(self):
        if 'pk' in self.kwargs:
            return reverse_lazy('network.switch_port', kwargs=self.kwargs)

    def get_context_data(self, **kwargs):
        context = super(SwitchPortDetail, self).get_context_data(**kwargs)
        context['switch_port_pk'] = self.object.pk
        context['devices'] = EthernetDevice.objects.filter(
            switch_port=self.object.pk)
        return context


730 731
class SwitchPortCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                       SuccessMessageMixin, CreateView):
732 733 734 735 736 737
    model = SwitchPort
    template_name = "network/switch-port-create.html"
    form_class = SwitchPortForm
    success_message = _(u'Successfully created switch port!')


738
class SwitchPortDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
739 740 741 742 743 744 745 746 747 748 749
    model = SwitchPort
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return next
        else:
            return reverse_lazy('network.switch_port_list')


750
class VlanList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
751 752 753 754 755 756
    model = Vlan
    table_class = VlanTable
    template_name = "network/vlan-list.html"
    table_pagination = False


Kálmán Viktor committed
757 758 759 760
class VlanAclUpdateView(AclUpdateView):
    model = Vlan


761
class VlanMagicMixin(MagicMixin):
762 763 764 765 766
    def _get_ajax(self, *args, **kwargs):
        GET = self.request.GET
        result = {}
        if "network4" in GET and "network6" in GET:
            try:
767 768 769
                result["ipv6_template"], result["host_ipv6_prefixlen"] = (
                    Vlan._magic_ipv6_template(IPNetwork(GET['network4']),
                                              IPNetwork(GET['network6'])))
770
            except:
771
                result["ipv6_template"] = result["host_ipv6_prefixlen"] = ""
772
        return result
773 774 775


class VlanDetail(VlanMagicMixin, LoginRequiredMixin, SuperuserRequiredMixin,
776
                 SuccessMessageMixin, UpdateView):
777 778 779 780 781
    model = Vlan
    template_name = "network/vlan-edit.html"
    form_class = VlanForm
    slug_field = 'vid'
    slug_url_kwarg = 'vid'
782
    success_message = _(u'Succesfully modified vlan %(name)s!')
783 784 785

    def get_context_data(self, **kwargs):
        context = super(VlanDetail, self).get_context_data(**kwargs)
786
        context['host_list'] = SmallHostTable(self.object.host_set.all())
787
        context['dhcp_list'] = SmallDhcpTable(self.object.get_dhcp_clients())
788
        context['vlan_vid'] = self.kwargs.get('vid')
789 790
        context['acl'] = AclUpdateView.get_acl_data(
            self.object, self.request.user, 'network.vlan-acl')
791
        context['aclform'] = AclUserOrGroupAddForm()
792 793 794 795 796
        return context

    success_url = reverse_lazy('network.vlan_list')


797
class VlanCreate(VlanMagicMixin, LoginRequiredMixin, SuperuserRequiredMixin,
798
                 SuccessMessageMixin, InitialOwnerMixin, CreateView):
799 800 801
    model = Vlan
    template_name = "network/vlan-create.html"
    form_class = VlanForm
802
    success_message = _(u'Successfully created vlan %(name)s!')
803 804


805
class VlanDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    model = Vlan
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return next
        else:
            return reverse_lazy('network.vlan_list')

    def get_object(self, queryset=None):
        """ we identify vlans by vid and not pk """
        return Vlan.objects.get(vid=self.kwargs['vid'])

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        if unicode(self.object) != request.POST.get('confirm'):
823
            messages.error(request, _(u"Object name does not match!"))
824 825 826
            return self.get(request, *args, **kwargs)

        response = super(VlanDelete, self).delete(request, *args, **kwargs)
827
        messages.success(request, _(u"Vlan successfully deleted!"))
828 829 830 831 832 833 834 835 836 837
        return response

    def get_context_data(self, **kwargs):
        context = super(VlanDelete, self).get_context_data(**kwargs)

        deps = []
        # hosts
        hosts = Host.objects.filter(vlan=self.object).all()
        if len(hosts) > 0:
            deps.append({
838
                'name': _('Hosts'),
839 840 841 842 843 844 845
                'data': hosts
            })

            # records
            records = Record.objects.filter(host__in=deps[0]['data'])
            if len(records) > 0:
                deps.append({
846
                    'name': _('Records'),
847 848 849 850 851 852 853 854
                    'data':  records
                })

        context['deps'] = deps
        context['confirmation'] = True
        return context


855 856
class VlanGroupList(LoginRequiredMixin, SuperuserRequiredMixin,
                    SingleTableView):
857 858 859 860 861 862
    model = VlanGroup
    table_class = VlanGroupTable
    template_name = "network/vlan-group-list.html"
    table_pagination = False


863 864
class VlanGroupDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                      SuccessMessageMixin, UpdateView):
865 866 867 868
    model = VlanGroup
    template_name = "network/vlan-group-edit.html"
    form_class = VlanGroupForm
    success_url = reverse_lazy('network.vlan_group_list')
869
    success_message = _(u'Successfully modified vlan group %(name)s!')
870 871 872 873 874 875 876

    def get_context_data(self, *args, **kwargs):
        context = super(VlanGroupDetail, self).get_context_data(**kwargs)
        context['vlangroup_pk'] = self.object.pk
        return context


877
class VlanGroupCreate(LoginRequiredMixin, SuperuserRequiredMixin,
878
                      SuccessMessageMixin, InitialOwnerMixin, CreateView):
879 880 881
    model = VlanGroup
    template_name = "network/vlan-group-create.html"
    form_class = VlanGroupForm
882
    success_message = _(u'Successfully created vlan group %(name)s!')
883 884


885
class VlanGroupDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
    model = VlanGroup
    template_name = "network/confirm/base_delete.html"

    def get_success_url(self):
        next = self.request.POST.get('next')
        if next:
            return next
        else:
            return reverse_lazy('network.vlan_group_list')


def remove_host_group(request, **kwargs):
    host = Host.objects.get(pk=kwargs['pk'])
    group = Group.objects.get(pk=kwargs['group_pk'])

    # for get we show the confirmation page
    if request.method == "GET":
        return render(request,
                      'network/confirm/remove_host_group.html',
                      {
                          'group': group.name,
                          'host': host.hostname
                      })

    # for post we actually remove the group from the host
    elif request.method == "POST":
        host.groups.remove(group)
913
        if not request.is_ajax():
914
            messages.success(request, _(u"Successfully removed %(host)s from "
915 916 917 918
                                        "%(group)s group!" % {
                                            'host': host,
                                            'group': group
                                        }))
919 920 921 922 923 924 925 926 927 928
        return redirect(reverse_lazy('network.host',
                                     kwargs={'pk': kwargs['pk']}))


def add_host_group(request, **kwargs):
    group_pk = request.POST.get('group')
    if request.method == "POST" and group_pk:
        host = Host.objects.get(pk=kwargs['pk'])
        group = Group.objects.get(pk=group_pk)
        host.groups.add(group)
929
        if not request.is_ajax():
930
            messages.success(request, _(u"Successfully added %(host)s to group"
931 932 933 934
                                        " %(group)s!" % {
                                            'host': host,
                                            'group': group
                                        }))
935
        return redirect(reverse_lazy('network.host', kwargs=kwargs))
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979


def remove_switch_port_device(request, **kwargs):
    device = EthernetDevice.objects.get(pk=kwargs['device_pk'])
    # for get we show the confirmation page
    if request.method == "GET":
        return render(request, 'network/confirm/base_delete.html',
                      {'object': device})

    # for post we actually remove the group from the host
    elif request.method == "POST":
        device.delete()
        if not request.is_ajax():
            messages.success(request, _(u"Successfully deleted ethernet device"
                                        " %(name)s!" % {
                                            'name': device.name,
                                        }))
        return redirect(reverse_lazy('network.switch_port',
                                     kwargs={'pk': kwargs['pk']}))


def add_switch_port_device(request, **kwargs):
    device_name = request.POST.get('device_name')

    if (request.method == "POST" and device_name and len(device_name) > 0
       and EthernetDevice.objects.filter(name=device_name).count() == 0):

        switch_port = SwitchPort.objects.get(pk=kwargs['pk'])
        new_device = EthernetDevice(name=device_name, switch_port=switch_port)
        new_device.save()
        if not request.is_ajax():
            messages.success(request, _(u"Successfully added %(name)s to this"
                                        " switch port" % {
                                            'name': device_name,
                                        }))
        return redirect(reverse_lazy('network.switch_port', kwargs=kwargs))

    elif not len(device_name) > 0:
        messages.error(request, _("Ethernet device name cannot be empty!"))
        return redirect(reverse_lazy('network.switch_port', kwargs=kwargs))
    elif EthernetDevice.objects.get(name=device_name) is not None:
        messages.error(request, _("There is already an ethernet device with"
                                  " that name!"))
        return redirect(reverse_lazy('network.switch_port', kwargs=kwargs))