views.py 29.2 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 19 20 21 22 23 24 25
from django.views.generic import (TemplateView, UpdateView, DeleteView,
                                  CreateView)
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.http import HttpResponse

from django_tables2 import SingleTableView

26
from firewall.models import (Host, Vlan, Domain, Group, Record, BlacklistItem,
27
                             Rule, VlanGroup, SwitchPort, EthernetDevice)
28
from vm.models import Interface
29
from .tables import (HostTable, VlanTable, SmallHostTable, DomainTable,
30
                     GroupTable, RecordTable, BlacklistItemTable, RuleTable,
31
                     VlanGroupTable, SmallRuleTable, SmallGroupRuleTable,
32
                     SmallRecordTable, SwitchPortTable)
33
from .forms import (HostForm, VlanForm, DomainForm, GroupForm, RecordForm,
34
                    BlacklistItemForm, RuleForm, VlanGroupForm, SwitchPortForm)
35 36 37 38

from django.contrib import messages
from django.views.generic.edit import FormMixin
from django.utils.translation import ugettext_lazy as _
39
from braces.views import LoginRequiredMixin, SuperuserRequiredMixin
40 41
# from django.db.models import Q
from operator import itemgetter
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
from itertools import chain
import json


class SuccessMessageMixin(FormMixin):
    """
    Adds a success message on successful form submission.
    From django/contrib/messages/views.py@9a85ad89
    """
    success_message = ''

    def form_valid(self, form):
        response = super(SuccessMessageMixin, self).form_valid(form)
        success_message = self.get_success_message(form.cleaned_data)
        if success_message:
            messages.success(self.request, success_message)
        return response

    def get_success_message(self, cleaned_data):
        return self.success_message % cleaned_data


64
class IndexView(LoginRequiredMixin, SuperuserRequiredMixin, TemplateView):
65 66 67 68 69 70
    template_name = "network/index.html"

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

        size = 13
71 72
        blacklists = BlacklistItem.objects.all().order_by(
            '-modified_at')[:size]
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
        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


99 100
class BlacklistList(LoginRequiredMixin, SuperuserRequiredMixin,
                    SingleTableView):
101 102
    model = BlacklistItem
    table_class = BlacklistItemTable
103 104 105 106
    template_name = "network/blacklist-list.html"
    table_pagination = False


107 108
class BlacklistDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                      SuccessMessageMixin, UpdateView):
109
    model = BlacklistItem
110
    template_name = "network/blacklist-edit.html"
111 112
    form_class = BlacklistItemForm
    success_message = _(u'Successfully modified blacklist item'
113 114 115 116 117 118 119 120 121 122 123 124
                        '%(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


125 126
class BlacklistCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                      SuccessMessageMixin, CreateView):
127
    model = BlacklistItem
128
    template_name = "network/blacklist-create.html"
129 130
    form_class = BlacklistItemForm
    success_message = _(u'Successfully created blacklist item '
131 132 133
                        '%(ipv4)s - %(type)s!')


134
class BlacklistDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
135
    model = BlacklistItem
136 137 138 139 140 141
    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:
142
            to_delete = BlacklistItem.objects.get(pk=self.kwargs['pk'])
143 144 145 146 147 148 149 150 151 152 153 154 155
            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')


156
class DomainList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
157 158 159 160 161 162
    model = Domain
    table_class = DomainTable
    template_name = "network/domain-list.html"
    table_pagination = False


163 164
class DomainDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                   SuccessMessageMixin, UpdateView):
165 166 167
    model = Domain
    template_name = "network/domain-edit.html"
    form_class = DomainForm
168
    success_message = _(u'Successfully modified domain %(name)s!')
169 170 171 172 173 174 175

    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)
176 177 178 179 180 181 182
        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(
183
                    instance__destroyed_at=None)
184 185
            )
        )
186 187 188 189
        context['record_list'] = SmallRecordTable(q)
        return context


190 191
class DomainCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                   SuccessMessageMixin, CreateView):
192 193 194
    model = Domain
    template_name = "network/domain-create.html"
    form_class = DomainForm
195
    success_message = _(u'Successfully created domain %(name)s!')
196 197


198
class DomainDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
199 200 201 202 203 204 205 206 207 208 209 210 211
    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'):
212
            messages.error(request, _(u"Object name does not match!"))
213 214 215
            return self.get(request, *args, **kwargs)

        response = super(DomainDelete, self).delete(request, *args, **kwargs)
216
        messages.success(request, _(u"Domain successfully deleted!"))
217 218 219 220 221
        return response

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

222
        records_from_hosts = _(u'Records from hosts')
223 224 225 226 227
        deps = []
        # vlans
        vlans = Vlan.objects.filter(domain=self.object).all()
        if len(vlans) > 0:
            deps.append({
228
                'name': _('Vlans'),
229 230 231 232 233 234 235
                'data': vlans
            })

            # hosts
            hosts = Host.objects.filter(vlan__in=deps[0]['data'])
            if len(hosts) > 0:
                deps.append({
236
                    'name': _('Hosts'),
237 238 239 240 241
                    'data':  hosts
                })

                # records
                records = Record.objects.filter(
242 243
                    host__in=deps[1]['data']
                    # Q(domain=self.object) | (host__in=deps[1]['data'])
244 245 246
                )
                if len(records) > 0:
                    deps.append({
247
                        'name': records_from_hosts,
248 249 250
                        'data': records
                    })

251 252 253 254
        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)
255
            n = indexes.index(records_from_hosts) if len(indexes) > 0 else 0
256
            deps.append({
257
                'name': u'Records only from the domain',
258 259 260 261
                'data': records.exclude(pk__in=deps[n]['data']) if n > 0
                else records
            })

262 263 264 265 266
        context['deps'] = deps
        context['confirmation'] = True
        return context


267
class GroupList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
268 269 270 271 272 273
    model = Group
    table_class = GroupTable
    template_name = "network/group-list.html"
    table_pagination = False


274 275
class GroupCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                  SuccessMessageMixin, CreateView):
276 277 278
    model = Group
    template_name = "network/group-create.html"
    form_class = GroupForm
279
    success_message = _(u'Successfully created host group %(name)s!')
280 281


282 283
class GroupDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                  SuccessMessageMixin, UpdateView):
284 285 286
    model = Group
    template_name = "network/group-edit.html"
    form_class = GroupForm
287
    success_message = _(u'Successfully modified host group %(name)s!')
288 289 290 291 292

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

293 294 295
    def get_context_data(self, *args, **kwargs):
        context = super(GroupDetail, self).get_context_data(**kwargs)

296 297
        context['group_pk'] = self.object.pk

298 299 300 301 302
        # records
        q = Rule.objects.filter(hostgroup=self.object)
        context['rule_list'] = SmallRuleTable(q)
        return context

303

304
class GroupDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    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


321
class HostList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
322 323 324 325 326 327 328 329 330 331 332 333 334 335
    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:
336
            data = Host.objects.filter(vlan=vlan_id).select_related()
337
        else:
338
            data = Host.objects.select_related()
339 340 341
        return data


342 343
class HostDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                 SuccessMessageMixin, UpdateView):
344 345 346
    model = Host
    template_name = "network/host-edit.html"
    form_class = HostForm
347
    success_message = _(u'Successfully modified host %(hostname)s!')
348 349 350 351 352 353

    def get(self, request, *args, **kwargs):
        if request.is_ajax():
            host = Host.objects.get(pk=kwargs['pk'])
            host = {
                'hostname': host.hostname,
354 355
                'ipv4': str(host.ipv4),
                'ipv6': str(host.ipv6),
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
                'fqdn': host.get_fqdn()
            }
            return HttpResponse(json.dumps(host),
                                content_type="application/json")
        else:
            self.object = self.get_object()
            return super(HostDetail, self).get(request, *args, **kwargs)

    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']

        return context

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


407 408
class HostCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                 SuccessMessageMixin, CreateView):
409 410 411
    model = Host
    template_name = "network/host-create.html"
    form_class = HostForm
412
    success_message = _(u'Successfully created host %(hostname)s!')
413 414


415
class HostDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    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({
433
                'name': _('Records'),
434 435 436 437 438 439 440 441 442 443
                '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'):
444
            messages.error(request, _(u"Object name does not match!"))
445 446 447
            return self.get(request, *args, **kwargs)

        response = super(HostDelete, self).delete(request, *args, **kwargs)
448
        messages.success(request, _(u"Host successfully deleted!"))
449 450 451
        return response


452
class RecordList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
453 454 455 456 457
    model = Record
    table_class = RecordTable
    template_name = "network/record-list.html"
    table_pagination = False

458 459 460 461 462 463 464 465 466 467 468 469 470
    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

471

472 473
class RecordDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                   SuccessMessageMixin, UpdateView):
474 475 476 477
    model = Record
    template_name = "network/record-edit.html"
    form_class = RecordForm
    # TODO fqdn
478
    success_message = _(u'Successfully modified record!')
479 480 481 482 483 484 485 486 487 488 489 490

    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)


491 492
class RecordCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                   SuccessMessageMixin, CreateView):
493 494 495 496
    model = Record
    template_name = "network/record-create.html"
    form_class = RecordForm
    # TODO fqdn
497
    success_message = _(u'Successfully created record!')
498

499 500 501 502 503 504
    def get_initial(self):
        return {
            # 'owner': 1,
            'domain': self.request.GET.get('domain'),
        }

505

506
class RecordDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
507 508 509 510 511 512 513 514 515 516 517
    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')


518
class RuleList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
519 520 521 522 523
    model = Rule
    table_class = RuleTable
    template_name = "network/rule-list.html"
    table_pagination = False

524 525 526 527 528
    def get_table_data(self):
        return Rule.objects.select_related('host', 'hostgroup', 'vlan',
                                           'vlangroup', 'firewall',
                                           'foreign_network', 'owner')

529

530 531
class RuleDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                 SuccessMessageMixin, UpdateView):
532 533 534
    model = Rule
    template_name = "network/rule-edit.html"
    form_class = RuleForm
535
    success_message = _(u'Successfully modified rule!')
536 537 538 539 540 541 542 543 544 545 546 547 548 549

    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


550 551
class RuleCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                 SuccessMessageMixin, CreateView):
552 553 554
    model = Rule
    template_name = "network/rule-create.html"
    form_class = RuleForm
555
    success_message = _(u'Successfully created rule!')
556

557 558 559 560 561 562 563
    def get_initial(self):
        return {
            # 'owner': 1,
            'host': self.request.GET.get('host'),
            'hostgroup': self.request.GET.get('hostgroup')
        }

564

565
class RuleDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
566 567 568 569 570 571 572 573 574 575 576
    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')


577 578
class SwitchPortList(LoginRequiredMixin, SuperuserRequiredMixin,
                     SingleTableView):
579 580 581 582 583 584
    model = SwitchPort
    table_class = SwitchPortTable
    template_name = "network/switch-port-list.html"
    table_pagination = False


585 586
class SwitchPortDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                       SuccessMessageMixin, UpdateView):
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    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


604 605
class SwitchPortCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                       SuccessMessageMixin, CreateView):
606 607 608 609 610 611
    model = SwitchPort
    template_name = "network/switch-port-create.html"
    form_class = SwitchPortForm
    success_message = _(u'Successfully created switch port!')


612
class SwitchPortDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
613 614 615 616 617 618 619 620 621 622 623
    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')


624
class VlanList(LoginRequiredMixin, SuperuserRequiredMixin, SingleTableView):
625 626 627 628 629 630
    model = Vlan
    table_class = VlanTable
    template_name = "network/vlan-list.html"
    table_pagination = False


631 632
class VlanDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                 SuccessMessageMixin, UpdateView):
633 634 635 636 637
    model = Vlan
    template_name = "network/vlan-edit.html"
    form_class = VlanForm
    slug_field = 'vid'
    slug_url_kwarg = 'vid'
638
    success_message = _(u'Succesfully modified vlan %(name)s!')
639 640 641

    def get_context_data(self, **kwargs):
        context = super(VlanDetail, self).get_context_data(**kwargs)
642 643

        q = Host.objects.filter(interface__in=Interface.objects.filter(
644
            vlan=self.object, instance__destroyed_at=None
645 646
        ))

647 648 649 650 651 652 653
        context['host_list'] = SmallHostTable(q)
        context['vlan_vid'] = self.kwargs.get('vid')
        return context

    success_url = reverse_lazy('network.vlan_list')


654 655
class VlanCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                 SuccessMessageMixin, CreateView):
656 657 658
    model = Vlan
    template_name = "network/vlan-create.html"
    form_class = VlanForm
659
    success_message = _(u'Successfully created vlan %(name)s!')
660 661


662
class VlanDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
    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'):
680
            messages.error(request, _(u"Object name does not match!"))
681 682 683
            return self.get(request, *args, **kwargs)

        response = super(VlanDelete, self).delete(request, *args, **kwargs)
684
        messages.success(request, _(u"Vlan successfully deleted!"))
685 686 687 688 689 690 691 692 693 694
        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({
695
                'name': _('Hosts'),
696 697 698 699 700 701 702
                'data': hosts
            })

            # records
            records = Record.objects.filter(host__in=deps[0]['data'])
            if len(records) > 0:
                deps.append({
703
                    'name': _('Records'),
704 705 706 707 708 709 710 711
                    'data':  records
                })

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


712 713
class VlanGroupList(LoginRequiredMixin, SuperuserRequiredMixin,
                    SingleTableView):
714 715 716 717 718 719
    model = VlanGroup
    table_class = VlanGroupTable
    template_name = "network/vlan-group-list.html"
    table_pagination = False


720 721
class VlanGroupDetail(LoginRequiredMixin, SuperuserRequiredMixin,
                      SuccessMessageMixin, UpdateView):
722 723 724 725
    model = VlanGroup
    template_name = "network/vlan-group-edit.html"
    form_class = VlanGroupForm
    success_url = reverse_lazy('network.vlan_group_list')
726
    success_message = _(u'Successfully modified vlan group %(name)s!')
727 728 729 730 731 732 733

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


734 735
class VlanGroupCreate(LoginRequiredMixin, SuperuserRequiredMixin,
                      SuccessMessageMixin, CreateView):
736 737 738
    model = VlanGroup
    template_name = "network/vlan-group-create.html"
    form_class = VlanGroupForm
739
    success_message = _(u'Successfully created vlan group %(name)s!')
740 741


742
class VlanGroupDelete(LoginRequiredMixin, SuperuserRequiredMixin, DeleteView):
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    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)
770
        if not request.is_ajax():
771
            messages.success(request, _(u"Successfully removed %(host)s from "
772 773 774 775
                                        "%(group)s group!" % {
                                            'host': host,
                                            'group': group
                                        }))
776 777 778 779 780 781 782 783 784 785
        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)
786
        if not request.is_ajax():
787
            messages.success(request, _(u"Successfully added %(host)s to group"
788 789 790 791
                                        " %(group)s!" % {
                                            'host': host,
                                            'group': group
                                        }))
792
        return redirect(reverse_lazy('network.host', kwargs=kwargs))
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836


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))