예제 #1
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all VLANs by search parameters.

        URLs: /vlan/find/
        """

        self.log.info('Find all VLANs')

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data,
                                       ['searchable_columns', 'asorting_cols'])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            vlan_map = networkapi_map.get('vlan')
            if vlan_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            start_record = vlan_map.get('start_record')
            end_record = vlan_map.get('end_record')
            asorting_cols = vlan_map.get('asorting_cols')
            searchable_columns = vlan_map.get('searchable_columns')
            custom_search = vlan_map.get('custom_search')

            number = vlan_map.get('numero')
            name = vlan_map.get('nome')
            iexact = vlan_map.get('exato')
            environment = vlan_map.get('ambiente')
            net_type = vlan_map.get('tipo_rede')
            network = vlan_map.get('rede')
            ip_version = vlan_map.get('versao')
            subnet = vlan_map.get('subrede')
            acl = vlan_map.get('acl')

            # Business Rules

            # Start with alls
            vlans = Vlan.objects.all().prefetch_related(
                'networkipv4_set', 'networkipv6_set')

            if number is not None:
                # If number is valid, add to filter
                if not is_valid_int_greater_zero_param(number, False):
                    raise InvalidValueError(None, 'numero', number)
                else:
                    vlans = vlans.filter(num_vlan=number)

            if name is not None:
                # If name is valid, add to filter
                if not is_valid_string_minsize(name, 3, False):
                    raise InvalidValueError(None, 'nome', name)
                else:
                    # Iexact must be valid to add name to filter
                    if not is_valid_boolean_param(iexact, False):
                        raise InvalidValueError(None, 'exato', iexact)
                    else:
                        if (iexact is None) or (iexact == 'False') or (iexact
                                                                       == '0'):
                            iexact = False

                        if iexact:
                            vlans = vlans.filter(nome=name)
                        else:
                            vlans = vlans.filter(nome__icontains=name)

            # If environment is valid, add to filter
            if environment is not None:
                if not is_valid_int_greater_zero_param(environment, False):
                    raise InvalidValueError(None, 'ambiente', environment)
                else:
                    vlans = vlans.filter(ambiente__pk=environment)

            if net_type is not None:
                # If net_type is valid, add to filter
                if not is_valid_int_greater_zero_param(net_type, False):
                    raise InvalidValueError(None, 'tipo_rede', net_type)
                else:
                    q1 = Q(networkipv4__network_type__id=net_type)
                    q2 = Q(networkipv6__network_type__id=net_type)
                    vlans = vlans.filter(q1 | q2)

            if acl is not None:
                # If acl is valid, add to filter
                if not is_valid_boolean_param(acl, False):
                    raise InvalidValueError(None, 'acl', acl)
                else:
                    if (acl is None) or (acl == 'False') or (acl == '0'):
                        acl = False
                    # If acl is true, only show vlans with false acl_valida
                    if acl:
                        vlans = vlans.filter(acl_valida=False)

            # If ip_version is valid
            if not is_valid_int_greater_equal_zero_param(ip_version):
                raise InvalidValueError(None, 'versao', ip_version)
            else:
                if ip_version == '0':
                    vlans = vlans.filter(
                        Q(networkipv6__isnull=True)
                        | Q(networkipv4__isnull=False))
                elif ip_version == '1':
                    vlans = vlans.filter(
                        Q(networkipv4__isnull=True)
                        | Q(networkipv6__isnull=False))

            if network is not None:
                # If network is valid
                if not is_valid_string_minsize(network, 1, False):
                    raise InvalidValueError(None, 'rede', network)
                else:
                    blocks, network, version = break_network(network)
                    try:
                        network_ip = IPNetwork(network)
                    except ValueError, e:
                        raise InvalidValueError(None, 'rede', network)

                # If subnet is valid, add to filter
                if not (subnet == '0' or subnet == '1'):
                    raise InvalidValueError(None, 'subrede', subnet)
                else:
                    # If subnet is 0, only filter network octs
                    if subnet == '0':

                        # Filter octs
                        if version == IP_VERSION.IPv4[0]:
                            # Network IP v4
                            oct1 = Q()
                            oct2 = Q()
                            oct3 = Q()
                            oct4 = Q()
                            blk = Q()

                            if len(blocks[0]) != 0:
                                oct1 = Q(networkipv4__oct1=blocks[0])
                            if len(blocks[1]) != 0:
                                oct2 = Q(networkipv4__oct2=blocks[1])
                            if len(blocks[2]) != 0:
                                oct3 = Q(networkipv4__oct3=blocks[2])
                            if len(blocks[3]) != 0:
                                oct4 = Q(networkipv4__oct4=blocks[3])
                            if len(blocks[4]) != 0:
                                blk = Q(networkipv4__block=blocks[4])

                            vlans = vlans.filter(oct1 & oct2 & oct3 & oct4
                                                 & blk)
                        else:
                            # Network IP v6
                            oct1 = Q()
                            oct2 = Q()
                            oct3 = Q()
                            oct4 = Q()
                            oct5 = Q()
                            oct6 = Q()
                            oct7 = Q()
                            oct8 = Q()
                            blk = Q()

                            if len(blocks[0]) != 0:
                                oct1 = Q(networkipv6__block1__iexact=blocks[0])
                            if len(blocks[1]) != 0:
                                oct2 = Q(networkipv6__block2__iexact=blocks[1])
                            if len(blocks[2]) != 0:
                                oct3 = Q(networkipv6__block3__iexact=blocks[2])
                            if len(blocks[3]) != 0:
                                oct4 = Q(networkipv6__block4__iexact=blocks[3])
                            if len(blocks[4]) != 0:
                                oct5 = Q(networkipv6__block5__iexact=blocks[4])
                            if len(blocks[5]) != 0:
                                oct6 = Q(networkipv6__block6__iexact=blocks[5])
                            if len(blocks[6]) != 0:
                                oct7 = Q(networkipv6__block7__iexact=blocks[6])
                            if len(blocks[7]) != 0:
                                oct8 = Q(networkipv6__block8__iexact=blocks[7])
                            if len(blocks[8]) != 0:
                                blk = Q(networkipv6__block=blocks[8])

                            vlans = vlans.filter(oct1 & oct2 & oct3 & oct4
                                                 & oct5 & oct6 & oct7 & oct8
                                                 & blk)
                    # If subnet is 1
                    else:

                        if version == IP_VERSION.IPv4[0]:
                            expl = split(network_ip.network.exploded, '.')
                        else:
                            expl = split(network_ip.network.exploded, ':')

                        expl.append(str(network_ip.prefixlen))

                        if blocks != expl:
                            raise InvalidValueError(None, 'rede', network)

                        # First, get all vlans filtered until now
                        itens = get_networks_simple(vlans)

                        ids_exclude = []
                        # Then iterate over it to verify each vlan
                        for vlan in itens:

                            is_subnet = verify_subnet(vlan, network_ip,
                                                      version)
                            if not is_subnet:
                                ids_exclude.append(vlan['id'])

                        vlans = vlans.exclude(id__in=ids_exclude)

            # Custom order
            if asorting_cols:
                if 'ambiente' in asorting_cols:
                    vlans = vlans.order_by('ambiente__divisao_dc__nome',
                                           'ambiente__ambiente_logico__nome',
                                           'ambiente__grupo_l3__nome')
                    asorting_cols.remove('ambiente')
                if '-ambiente' in asorting_cols:
                    vlans = vlans.order_by('-ambiente__divisao_dc__nome',
                                           '-ambiente__ambiente_logico__nome',
                                           '-ambiente__grupo_l3__nome')
                    asorting_cols.remove('-ambiente')
                if 'tipo_rede' in asorting_cols:
                    vlans = vlans.order_by(
                        'networkipv4__network_type__tipo_rede',
                        'networkipv6__network_type__tipo_rede')
                    asorting_cols.remove('tipo_rede')
                if '-tipo_rede' in asorting_cols:
                    vlans = vlans.order_by(
                        '-networkipv4__network_type__tipo_rede',
                        '-networkipv6__network_type__tipo_rede')
                    asorting_cols.remove('-tipo_rede')
                if 'network' in asorting_cols:
                    vlans = vlans.order_by(
                        'networkipv4__oct1', 'networkipv4__oct2',
                        'networkipv4__oct3', 'networkipv4__oct4',
                        'networkipv4__block', 'networkipv6__block1',
                        'networkipv6__block2', 'networkipv6__block3',
                        'networkipv6__block4', 'networkipv6__block5',
                        'networkipv6__block6', 'networkipv6__block7',
                        'networkipv6__block8', 'networkipv6__block')
                    asorting_cols.remove('network')
                if '-network' in asorting_cols:
                    vlans = vlans.order_by(
                        '-networkipv4__oct1', '-networkipv4__oct2',
                        '-networkipv4__oct3', '-networkipv4__oct4',
                        '-networkipv4__block', '-networkipv6__block1',
                        '-networkipv6__block2', '-networkipv6__block3',
                        '-networkipv6__block4', '-networkipv6__block5',
                        '-networkipv6__block6', '-networkipv6__block7',
                        '-networkipv6__block8', '-networkipv6__block')
                    asorting_cols.remove('-network')

            vlans = vlans.distinct()

            # Datatable paginator
            vlans, total = build_query_to_datatable(vlans, asorting_cols,
                                                    custom_search,
                                                    searchable_columns,
                                                    start_record, end_record)
            vlans = vlans.prefetch_related(
                'ambiente', 'networkipv4_set__network_type',
                'networkipv4_set__ip_set__ipequipamento_set__equipamento__equipamentoambiente_set__ambiente',
                'networkipv6_set__network_type',
                'networkipv6_set__ipv6_set__ipv6equipament_set__equipamento__equipamentoambiente_set__ambiente'
            )

            itens = get_networks(vlans, False)

            vlan_map = dict()
            vlan_map['vlan'] = itens
            vlan_map['total'] = total

            return self.response(dumps_networkapi(vlan_map))
예제 #2
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all VLANs by search parameters.

        URLs: /vlan/find/
        """

        self.log.info('Find all VLANs')

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data, ['searchable_columns', 'asorting_cols'])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            vlan_map = networkapi_map.get('vlan')
            if vlan_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            start_record = vlan_map.get('start_record')
            end_record = vlan_map.get('end_record')
            asorting_cols = vlan_map.get('asorting_cols')
            searchable_columns = vlan_map.get('searchable_columns')
            custom_search = vlan_map.get('custom_search')

            number = vlan_map.get('numero')
            name = vlan_map.get('nome')
            iexact = vlan_map.get('exato')
            environment = vlan_map.get('ambiente')
            net_type = vlan_map.get('tipo_rede')
            network = vlan_map.get('rede')
            ip_version = vlan_map.get('versao')
            subnet = vlan_map.get('subrede')
            acl = vlan_map.get('acl')

            # Business Rules

            # Start with alls
            vlans = Vlan.objects.all().prefetch_related(
                'networkipv4_set', 'networkipv6_set')

            if number is not None:
                # If number is valid, add to filter
                if not is_valid_int_greater_zero_param(number, False):
                    raise InvalidValueError(None, 'numero', number)
                else:
                    vlans = vlans.filter(num_vlan=number)

            if name is not None:
                # If name is valid, add to filter
                if not is_valid_string_minsize(name, 3, False):
                    raise InvalidValueError(None, 'nome', name)
                else:
                    # Iexact must be valid to add name to filter
                    if not is_valid_boolean_param(iexact, False):
                        raise InvalidValueError(None, 'exato', iexact)
                    else:
                        if (iexact is None) or (iexact == 'False') or (iexact == '0'):
                            iexact = False

                        if iexact:
                            vlans = vlans.filter(nome=name)
                        else:
                            vlans = vlans.filter(nome__icontains=name)

            # If environment is valid, add to filter
            if environment is not None:
                if not is_valid_int_greater_zero_param(environment, False):
                    raise InvalidValueError(None, 'ambiente', environment)
                else:
                    vlans = vlans.filter(ambiente__pk=environment)

            if net_type is not None:
                # If net_type is valid, add to filter
                if not is_valid_int_greater_zero_param(net_type, False):
                    raise InvalidValueError(None, 'tipo_rede', net_type)
                else:
                    q1 = Q(networkipv4__network_type__id=net_type)
                    q2 = Q(networkipv6__network_type__id=net_type)
                    vlans = vlans.filter(q1 | q2)

            if acl is not None:
                # If acl is valid, add to filter
                if not is_valid_boolean_param(acl, False):
                    raise InvalidValueError(None, 'acl', acl)
                else:
                    if (acl is None) or (acl == 'False') or (acl == '0'):
                        acl = False
                    # If acl is true, only show vlans with false acl_valida
                    if acl:
                        vlans = vlans.filter(acl_valida=False)

            # If ip_version is valid
            if not is_valid_int_greater_equal_zero_param(ip_version):
                raise InvalidValueError(None, 'versao', ip_version)
            else:
                if ip_version == '0':
                    vlans = vlans.filter(
                        Q(networkipv6__isnull=True) | Q(networkipv4__isnull=False))
                elif ip_version == '1':
                    vlans = vlans.filter(
                        Q(networkipv4__isnull=True) | Q(networkipv6__isnull=False))

            if network is not None:
                # If network is valid
                if not is_valid_string_minsize(network, 1, False):
                    raise InvalidValueError(None, 'rede', network)
                else:
                    blocks, network, version = break_network(network)
                    try:
                        network_ip = IPNetwork(network)
                    except ValueError, e:
                        raise InvalidValueError(None, 'rede', network)

                # If subnet is valid, add to filter
                if not (subnet == '0' or subnet == '1'):
                    raise InvalidValueError(None, 'subrede', subnet)
                else:
                    # If subnet is 0, only filter network octs
                    if subnet == '0':

                        # Filter octs
                        if version == IP_VERSION.IPv4[0]:
                            # Network IP v4
                            oct1 = Q()
                            oct2 = Q()
                            oct3 = Q()
                            oct4 = Q()
                            blk = Q()

                            if len(blocks[0]) != 0:
                                oct1 = Q(networkipv4__oct1=blocks[0])
                            if len(blocks[1]) != 0:
                                oct2 = Q(networkipv4__oct2=blocks[1])
                            if len(blocks[2]) != 0:
                                oct3 = Q(networkipv4__oct3=blocks[2])
                            if len(blocks[3]) != 0:
                                oct4 = Q(networkipv4__oct4=blocks[3])
                            if len(blocks[4]) != 0:
                                blk = Q(networkipv4__block=blocks[4])

                            vlans = vlans.filter(
                                oct1 & oct2 & oct3 & oct4 & blk)
                        else:
                            # Network IP v6
                            oct1 = Q()
                            oct2 = Q()
                            oct3 = Q()
                            oct4 = Q()
                            oct5 = Q()
                            oct6 = Q()
                            oct7 = Q()
                            oct8 = Q()
                            blk = Q()

                            if len(blocks[0]) != 0:
                                oct1 = Q(networkipv6__block1__iexact=blocks[0])
                            if len(blocks[1]) != 0:
                                oct2 = Q(networkipv6__block2__iexact=blocks[1])
                            if len(blocks[2]) != 0:
                                oct3 = Q(networkipv6__block3__iexact=blocks[2])
                            if len(blocks[3]) != 0:
                                oct4 = Q(networkipv6__block4__iexact=blocks[3])
                            if len(blocks[4]) != 0:
                                oct5 = Q(networkipv6__block5__iexact=blocks[4])
                            if len(blocks[5]) != 0:
                                oct6 = Q(networkipv6__block6__iexact=blocks[5])
                            if len(blocks[6]) != 0:
                                oct7 = Q(networkipv6__block7__iexact=blocks[6])
                            if len(blocks[7]) != 0:
                                oct8 = Q(networkipv6__block8__iexact=blocks[7])
                            if len(blocks[8]) != 0:
                                blk = Q(networkipv6__block=blocks[8])

                            vlans = vlans.filter(
                                oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8 & blk)
                    # If subnet is 1
                    else:

                        if version == IP_VERSION.IPv4[0]:
                            expl = split(network_ip.network.exploded, '.')
                        else:
                            expl = split(network_ip.network.exploded, ':')

                        expl.append(str(network_ip.prefixlen))

                        if blocks != expl:
                            raise InvalidValueError(None, 'rede', network)

                        # First, get all vlans filtered until now
                        itens = get_networks_simple(vlans)

                        ids_exclude = []
                        # Then iterate over it to verify each vlan
                        for vlan in itens:

                            is_subnet = verify_subnet(
                                vlan, network_ip, version)
                            if not is_subnet:
                                ids_exclude.append(vlan['id'])

                        vlans = vlans.exclude(id__in=ids_exclude)

            # Custom order
            if asorting_cols:
                if 'ambiente' in asorting_cols:
                    vlans = vlans.order_by(
                        'ambiente__divisao_dc__nome', 'ambiente__ambiente_logico__nome', 'ambiente__grupo_l3__nome')
                    asorting_cols.remove('ambiente')
                if '-ambiente' in asorting_cols:
                    vlans = vlans.order_by(
                        '-ambiente__divisao_dc__nome', '-ambiente__ambiente_logico__nome', '-ambiente__grupo_l3__nome')
                    asorting_cols.remove('-ambiente')
                if 'tipo_rede' in asorting_cols:
                    vlans = vlans.order_by(
                        'networkipv4__network_type__tipo_rede', 'networkipv6__network_type__tipo_rede')
                    asorting_cols.remove('tipo_rede')
                if '-tipo_rede' in asorting_cols:
                    vlans = vlans.order_by(
                        '-networkipv4__network_type__tipo_rede', '-networkipv6__network_type__tipo_rede')
                    asorting_cols.remove('-tipo_rede')
                if 'network' in asorting_cols:
                    vlans = vlans.order_by('networkipv4__oct1', 'networkipv4__oct2', 'networkipv4__oct3', 'networkipv4__oct4', 'networkipv4__block', 'networkipv6__block1', 'networkipv6__block2',
                                           'networkipv6__block3', 'networkipv6__block4', 'networkipv6__block5', 'networkipv6__block6', 'networkipv6__block7', 'networkipv6__block8', 'networkipv6__block')
                    asorting_cols.remove('network')
                if '-network' in asorting_cols:
                    vlans = vlans.order_by('-networkipv4__oct1', '-networkipv4__oct2', '-networkipv4__oct3', '-networkipv4__oct4', '-networkipv4__block', '-networkipv6__block1', '-networkipv6__block2',
                                           '-networkipv6__block3', '-networkipv6__block4', '-networkipv6__block5', '-networkipv6__block6', '-networkipv6__block7', '-networkipv6__block8', '-networkipv6__block')
                    asorting_cols.remove('-network')

            vlans = vlans.distinct()

            # Datatable paginator
            vlans, total = build_query_to_datatable(
                vlans, asorting_cols, custom_search, searchable_columns, start_record, end_record)
            vlans = vlans.prefetch_related('ambiente',
                                           'networkipv4_set__network_type',
                                           'networkipv4_set__ip_set__ipequipamento_set__equipamento__equipamentoambiente_set__ambiente',
                                           'networkipv6_set__network_type',
                                           'networkipv6_set__ipv6_set__ipv6equipament_set__equipamento__equipamentoambiente_set__ambiente')

            itens = get_networks(vlans, False)

            vlan_map = dict()
            vlan_map['vlan'] = itens
            vlan_map['total'] = total

            return self.response(dumps_networkapi(vlan_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all Equipments by search parameters.

        URLs: /equipment/find/
        """

        self.log.info('Find all Equipments')

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data, ["searchable_columns", "asorting_cols"])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            equipment_map = networkapi_map.get('equipamento')
            if equipment_map is None:
                msg = u'There is no value to the equipment tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            start_record = equipment_map.get("start_record")
            end_record = equipment_map.get("end_record")
            asorting_cols = equipment_map.get("asorting_cols")
            searchable_columns = equipment_map.get("searchable_columns")
            custom_search = equipment_map.get("custom_search")

            name = equipment_map.get("nome")
            iexact = equipment_map.get("exato")
            environment = equipment_map.get("ambiente")
            equip_type = equipment_map.get("tipo_equipamento")
            group = equipment_map.get("grupo")
            ip = equipment_map.get("ip")

            # Business Rules

            # Start with alls
            equip = Equipamento.objects.select_related().all()

            if name is not None:
                # If name is valid, add to filter
                if not is_valid_string_minsize(name, 3, False):
                    raise InvalidValueError(None, 'nome', name)
                else:
                    # Iexact must be valid to add name to filter
                    if not is_valid_boolean_param(iexact, False):
                        raise InvalidValueError(None, 'exato', iexact)
                    else:
                        if (iexact is None) or (iexact == "False") or (iexact == "0"):
                            iexact = False

                        if iexact:
                            equip = equip.filter(nome=name)
                        else:
                            equip = equip.filter(nome__icontains=name)

            # If environment is valid, add to filter
            if environment is not None:
                if not is_valid_int_greater_zero_param(environment, False):
                    raise InvalidValueError(None, 'ambiente', environment)
                else:
                    equip = equip.filter(
                        equipamentoambiente__ambiente__pk=environment)

            if equip_type is not None:
                # If equip_type is valid, add to filter
                if not is_valid_int_greater_zero_param(equip_type, False):
                    raise InvalidValueError(
                        None, 'tipo_equipamento', equip_type)
                else:
                    equip = equip.filter(tipo_equipamento__pk=equip_type)

            if group is not None:
                # If equip_type is valid, add to filter
                if not is_valid_int_greater_zero_param(group, False):
                    raise InvalidValueError(None, 'grupo', group)
                else:
                    equip = equip.filter(grupos__pk=group)

            if ip is not None:
                # If ip is valid
                if not is_valid_string_minsize(ip, 1, False):
                    raise InvalidValueError(None, 'ip', ip)
                else:
                    blocks, ip, version = break_ip(ip)
                    try:
                        IPAddress(ip)
                    except ValueError, e:
                        raise InvalidValueError(None, 'ip', ip)

                    # Filter octs
                    if version == IP_VERSION.IPv4[0]:
                        # IP v4
                        oct1 = oct2 = oct3 = oct4 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ipequipamento__ip__oct1=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ipequipamento__ip__oct2=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ipequipamento__ip__oct3=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ipequipamento__ip__oct4=blocks[3])

                        equip = equip.filter(oct1 & oct2 & oct3 & oct4)
                    else:
                        # IP v6
                        oct1 = oct2 = oct3 = oct4 = oct5 = oct6 = oct7 = oct8 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(
                                ipv6equipament__ip__block1__iexact=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(
                                ipv6equipament__ip__block2__iexact=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(
                                ipv6equipament__ip__block3__iexact=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(
                                ipv6equipament__ip__block4__iexact=blocks[3])
                        if len(blocks[4]) != 0:
                            oct5 = Q(
                                ipv6equipament__ip__block5__iexact=blocks[4])
                        if len(blocks[5]) != 0:
                            oct6 = Q(
                                ipv6equipament__ip__block6__iexact=blocks[5])
                        if len(blocks[6]) != 0:
                            oct7 = Q(
                                ipv6equipament__ip__block7__iexact=blocks[6])
                        if len(blocks[7]) != 0:
                            oct8 = Q(
                                ipv6equipament__ip__block8__iexact=blocks[7])

                        equip = equip.filter(
                            oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8)

            equip = equip.distinct()

            # Datatable paginator
            equip, total = build_query_to_datatable(
                equip, asorting_cols, custom_search, searchable_columns, start_record, end_record)

            itens = get_equips(equip)

            equipment_map = dict()
            equipment_map["equipamento"] = itens
            equipment_map["total"] = total

            return self.response(dumps_networkapi(equipment_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all Equipments by search parameters.

        URLs: /equipment/find/
        """

        self.log.info('Find all Equipments')

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data, ['searchable_columns', 'asorting_cols'])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            equipment_map = networkapi_map.get('equipamento')
            if equipment_map is None:
                msg = u'There is no value to the equipment tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            start_record = equipment_map.get('start_record')
            end_record = equipment_map.get('end_record')
            asorting_cols = equipment_map.get('asorting_cols')
            searchable_columns = equipment_map.get('searchable_columns')
            custom_search = equipment_map.get('custom_search')

            name = equipment_map.get('nome')
            iexact = equipment_map.get('exato')
            environment = equipment_map.get('ambiente')
            equip_type = equipment_map.get('tipo_equipamento')
            group = equipment_map.get('grupo')
            ip = equipment_map.get('ip')

            # Business Rules

            # Start with alls
            equip = Equipamento.objects.all()

            if name is not None:
                # If name is valid, add to filter
                if not is_valid_string_minsize(name, 3, False):
                    raise InvalidValueError(None, 'nome', name)
                else:
                    # Iexact must be valid to add name to filter
                    if not is_valid_boolean_param(iexact, False):
                        raise InvalidValueError(None, 'exato', iexact)
                    else:
                        if (iexact is None) or (iexact == 'False') or (iexact == '0'):
                            iexact = False

                        if iexact:
                            equip = equip.filter(nome=name)
                        else:
                            equip = equip.filter(nome__icontains=name)

            # If environment is valid, add to filter
            if environment is not None:
                if not is_valid_int_greater_zero_param(environment, False):
                    raise InvalidValueError(None, 'ambiente', environment)
                else:
                    equip = equip.filter(
                        equipamentoambiente__ambiente__pk=environment)

            if equip_type is not None:
                # If equip_type is valid, add to filter
                if not is_valid_int_greater_zero_param(equip_type, False):
                    raise InvalidValueError(
                        None, 'tipo_equipamento', equip_type)
                else:
                    equip = equip.filter(tipo_equipamento__pk=equip_type)

            if group is not None:
                # If equip_type is valid, add to filter
                if not is_valid_int_greater_zero_param(group, False):
                    raise InvalidValueError(None, 'grupo', group)
                else:
                    equip = equip.filter(grupos__pk=group)

            if ip is not None:
                # If ip is valid
                if not is_valid_string_minsize(ip, 1, False):
                    raise InvalidValueError(None, 'ip', ip)
                else:
                    blocks, ip, version = break_ip(ip)
                    try:
                        IPAddress(ip)
                    except ValueError, e:
                        raise InvalidValueError(None, 'ip', ip)

                    # Filter octs
                    if version == IP_VERSION.IPv4[0]:
                        # IP v4
                        oct1 = oct2 = oct3 = oct4 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ipequipamento__ip__oct1=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ipequipamento__ip__oct2=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ipequipamento__ip__oct3=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ipequipamento__ip__oct4=blocks[3])

                        equip = equip.filter(oct1 & oct2 & oct3 & oct4)
                    else:
                        # IP v6
                        oct1 = oct2 = oct3 = oct4 = oct5 = oct6 = oct7 = oct8 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(
                                ipv6equipament__ip__block1__iexact=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(
                                ipv6equipament__ip__block2__iexact=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(
                                ipv6equipament__ip__block3__iexact=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(
                                ipv6equipament__ip__block4__iexact=blocks[3])
                        if len(blocks[4]) != 0:
                            oct5 = Q(
                                ipv6equipament__ip__block5__iexact=blocks[4])
                        if len(blocks[5]) != 0:
                            oct6 = Q(
                                ipv6equipament__ip__block6__iexact=blocks[5])
                        if len(blocks[6]) != 0:
                            oct7 = Q(
                                ipv6equipament__ip__block7__iexact=blocks[6])
                        if len(blocks[7]) != 0:
                            oct8 = Q(
                                ipv6equipament__ip__block8__iexact=blocks[7])

                        equip = equip.filter(
                            oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8)

            equip = equip.distinct()

            # Datatable paginator
            equip, total = build_query_to_datatable(
                equip, asorting_cols, custom_search, searchable_columns, start_record, end_record)

            itens = get_equips(equip)

            equipment_map = dict()
            equipment_map['equipamento'] = itens
            equipment_map['total'] = total

            return self.response(dumps_networkapi(equipment_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all logs by search parameters.

        URLs: /eventlog/find/
        """

        self.log.info('find all logs')

        try:
            # Common validations

            # User permission
            if not has_perm(user, AdminPermission.USER_ADMINISTRATION,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    'User does not have permission to perform this operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data,
                                       ["searchable_columns", "asorting_cols"])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            eventlog_map = networkapi_map.get('eventlog')
            if eventlog_map is None:
                msg = u'There is no value to the eventlog tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            start_record = eventlog_map.get("start_record")
            end_record = eventlog_map.get("end_record")
            asorting_cols = eventlog_map.get("asorting_cols")
            searchable_columns = eventlog_map.get("searchable_columns")
            custom_search = eventlog_map.get("custom_search")

            usuario = eventlog_map.get('usuario')
            data_inicial = eventlog_map.get('data_inicial')
            hora_inicial = eventlog_map.get('hora_inicial')
            data_final = eventlog_map.get('data_final')
            hora_final = eventlog_map.get('hora_final')
            acao = eventlog_map.get('acao')
            funcionalidade = eventlog_map.get('funcionalidade')
            parametro = eventlog_map.get('parametro')

            # Start with all

            eventlog = EventLog.objects.all()
            eventlog = eventlog.order_by('-id')

            if usuario != "0":
                eventlog = eventlog.filter(usuario=usuario)

            if acao is not None:
                eventlog = eventlog.filter(acao=acao)

            if funcionalidade != "0":
                eventlog = eventlog.filter(funcionalidade=funcionalidade)

            if data_inicial is not None:
                if data_final is not None:
                    # Concatenate strings
                    data_inicial = data_inicial + ' ' + hora_inicial + ':00'
                    data_final = data_final + ' ' + hora_final + ':59'

                    # Parse to datetime format
                    data_inicial = datetime.strptime(data_inicial,
                                                     '%d/%m/%Y %H:%M:%S')
                    data_final = datetime.strptime(data_final,
                                                   '%d/%m/%Y %H:%M:%S')

                    eventlog = eventlog.filter(hora_evento__gte=data_inicial,
                                               hora_evento__lte=data_final)
            else:
                # Concatenate strings
                hora_inicial = hora_inicial + ':00'
                hora_final = hora_final + ':59'

                # Filter by time, ignoring the date
                eventlog = eventlog.extra(where=[
                    "time(hora_evento) >= '" + hora_inicial +
                    "' and time(hora_evento) <= '" + hora_final + "'"
                ])

            if parametro is not None:
                eventlog = eventlog.filter(
                    parametro_atual__contains=parametro) | eventlog.filter(
                        parametro_anterior__contains=parametro)
                pass

            eventlog, total = build_query_to_datatable(eventlog, asorting_cols,
                                                       custom_search,
                                                       searchable_columns,
                                                       start_record,
                                                       end_record)

            itens = get_logs(eventlog)

            eventlog_map = dict()
            eventlog_map["eventlog"] = itens
            eventlog_map["total"] = total

            return self.response(dumps_networkapi(eventlog_map))

        except InvalidValueError, e:
            self.log.error(u'Parameter %s is invalid. Value: %s.', e.param,
                           e.value)
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all Vip Requests by search parameters.

        URLs: /requestvip/get_by_ip_id/
        """

        self.log.info("Find all Vip Requests")

        try:

            # Commons Validations
            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION):
                self.log.error(u"User does not have permission to perform the operation.")
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data, ["searchable_columns", "asorting_cols"])

            # XML data format
            networkapi_map = xml_map.get("networkapi")
            if networkapi_map is None:
                msg = u"There is no value to the networkapi tag of XML request."
                self.log.error(msg)
                return self.response_error(3, msg)

            vip_map = networkapi_map.get("vip")
            if vip_map is None:
                msg = u"There is no value to the vip tag of XML request."
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            start_record = vip_map.get("start_record")
            end_record = vip_map.get("end_record")
            asorting_cols = vip_map.get("asorting_cols")
            searchable_columns = vip_map.get("searchable_columns")
            custom_search = vip_map.get("custom_search")

            id_vip = vip_map.get("id_vip")
            ip = vip_map.get("ip")
            created_vip = vip_map.get("create")
            if created_vip == "True":
                create = True
            elif created_vip == "False":
                create = None
            else:
                create = created_vip

            # Business Rules

            # Start with all

            vip = RequisicaoVips.objects.all()

            if id_vip is not None and ip is not None:
                raise InvalidValueError(None, "id_vip - ip", "%s - %s" % (id_vip, ip))

            if id_vip is not None:
                # If id_vip is valid, add to filter
                if not is_valid_int_greater_zero_param(id_vip, False):
                    raise InvalidValueError(None, "id_vip", id_vip)
                else:
                    vip = vip.filter(id=id_vip)

            if create is not None:
                # if create is valid, add to filter
                if not is_valid_boolean_param(create, False):
                    raise InvalidValueError(None, "vip_criado", create)
                else:
                    vip = vip.filter(vip_criado=create)

            if ip is not None:
                # If ip is valid
                if not is_valid_string_minsize(ip, 1, False):
                    raise InvalidValueError(None, "ip", ip)
                else:
                    blocks, ip, version = break_ip(ip)
                    try:
                        IPAddress(ip)
                    except ValueError, e:
                        raise InvalidValueError(None, "ip", ip)

                    # Filter octs
                    if version == IP_VERSION.IPv4[0]:
                        # IP v4
                        oct1 = oct2 = oct3 = oct4 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ip__oct1=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ip__oct2=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ip__oct3=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ip__oct4=blocks[3])

                        vip = vip.filter(oct1 & oct2 & oct3 & oct4)
                    else:
                        # IP v6
                        oct1 = oct2 = oct3 = oct4 = oct5 = oct6 = oct7 = oct8 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ipv6__block1__iexact=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ipv6__block2__iexact=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ipv6__block3__iexact=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ipv6__block4__iexact=blocks[3])
                        if len(blocks[4]) != 0:
                            oct5 = Q(ipv6__block5__iexact=blocks[4])
                        if len(blocks[5]) != 0:
                            oct6 = Q(ipv6__block6__iexact=blocks[5])
                        if len(blocks[6]) != 0:
                            oct7 = Q(ipv6__block7__iexact=blocks[6])
                        if len(blocks[7]) != 0:
                            oct8 = Q(ipv6__block8__iexact=blocks[7])

                        vip = vip.filter(oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8)

            vip = vip.distinct()

            vip = vip.order_by("-pk")

            # Datatable paginator
            vip, total = build_query_to_datatable(
                vip, asorting_cols, custom_search, searchable_columns, start_record, end_record
            )

            itens = get_vips(vip)

            vip_map = dict()
            vip_map["vips"] = itens
            vip_map["total"] = total

            return self.response(dumps_networkapi(vip_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all logs by search parameters.

        URLs: /eventlog/find/
        """

        self.log.info('find all logs')

        try:
            # Common validations

            # User permission
            if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.READ_OPERATION):
                self.log.error(
                    'User does not have permission to perform this operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data, ["searchable_columns", "asorting_cols"])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            eventlog_map = networkapi_map.get('eventlog')
            if eventlog_map is None:
                msg = u'There is no value to the eventlog tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            start_record = eventlog_map.get("start_record")
            end_record = eventlog_map.get("end_record")
            asorting_cols = eventlog_map.get("asorting_cols")
            searchable_columns = eventlog_map.get("searchable_columns")
            custom_search = eventlog_map.get("custom_search")

            usuario = eventlog_map.get('usuario')
            data_inicial = eventlog_map.get('data_inicial')
            hora_inicial = eventlog_map.get('hora_inicial')
            data_final = eventlog_map.get('data_final')
            hora_final = eventlog_map.get('hora_final')
            acao = eventlog_map.get('acao')
            funcionalidade = eventlog_map.get('funcionalidade')
            parametro = eventlog_map.get('parametro')

            # Start with all

            eventlog = EventLog.objects.all()
            eventlog = eventlog.order_by('-id')

            if usuario != "0":
                eventlog = eventlog.filter(usuario=usuario)

            if acao is not None:
                eventlog = eventlog.filter(acao=acao)

            if funcionalidade != "0":
                eventlog = eventlog.filter(funcionalidade=funcionalidade)

            if data_inicial is not None:
                if data_final is not None:
                    # Concatenate strings
                    data_inicial = data_inicial + ' ' + hora_inicial + ':00'
                    data_final = data_final + ' ' + hora_final + ':59'

                    # Parse to datetime format
                    data_inicial = datetime.strptime(
                        data_inicial, '%d/%m/%Y %H:%M:%S')
                    data_final = datetime.strptime(
                        data_final, '%d/%m/%Y %H:%M:%S')

                    eventlog = eventlog.filter(
                        hora_evento__gte=data_inicial, hora_evento__lte=data_final)
            else:
                # Concatenate strings
                hora_inicial = hora_inicial + ':00'
                hora_final = hora_final + ':59'

                # Filter by time, ignoring the date
                eventlog = eventlog.extra(
                    where=["time(hora_evento) >= '" + hora_inicial + "' and time(hora_evento) <= '" + hora_final + "'"])

            if parametro is not None:
                eventlog = eventlog.filter(parametro_atual__contains=parametro) | eventlog.filter(
                    parametro_anterior__contains=parametro)
                pass

            eventlog, total = build_query_to_datatable(
                eventlog, asorting_cols, custom_search, searchable_columns, start_record, end_record)

            itens = get_logs(eventlog)

            eventlog_map = dict()
            eventlog_map["eventlog"] = itens
            eventlog_map["total"] = total

            return self.response(dumps_networkapi(eventlog_map))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all Vip Requests by search parameters.

        URLs: /requestvip/get_by_ip_id/
        """

        self.log.info('Find all Vip Requests')

        try:

            # Commons Validations
            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data,
                                       ["searchable_columns", "asorting_cols"])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            vip_map = networkapi_map.get('vip')
            if vip_map is None:
                msg = u'There is no value to the vip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            start_record = vip_map.get("start_record")
            end_record = vip_map.get("end_record")
            asorting_cols = vip_map.get("asorting_cols")
            searchable_columns = vip_map.get("searchable_columns")
            custom_search = vip_map.get("custom_search")

            id_vip = vip_map.get("id_vip")
            ip = vip_map.get("ip")
            created_vip = vip_map.get("create")
            if created_vip == 'True':
                create = True
            elif created_vip == 'False':
                create = None
            else:
                create = created_vip

            # Business Rules

            # Start with all

            vip = RequisicaoVips.objects.all()

            if id_vip is not None and ip is not None:
                raise InvalidValueError(None, 'id_vip - ip',
                                        "%s - %s" % (id_vip, ip))

            if id_vip is not None:
                # If id_vip is valid, add to filter
                if not is_valid_int_greater_zero_param(id_vip, False):
                    raise InvalidValueError(None, 'id_vip', id_vip)
                else:
                    vip = vip.filter(id=id_vip)

            if create is not None:
                # if create is valid, add to filter
                if not is_valid_boolean_param(create, False):
                    raise InvalidValueError(None, 'vip_criado', create)
                else:
                    vip = vip.filter(vip_criado=create)

            if ip is not None:
                # If ip is valid
                if not is_valid_string_minsize(ip, 1, False):
                    raise InvalidValueError(None, 'ip', ip)
                else:
                    blocks, ip, version = break_ip(ip)
                    try:
                        IPAddress(ip)
                    except ValueError, e:
                        raise InvalidValueError(None, 'ip', ip)

                    # Filter octs
                    if version == IP_VERSION.IPv4[0]:
                        # IP v4
                        oct1 = oct2 = oct3 = oct4 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ip__oct1=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ip__oct2=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ip__oct3=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ip__oct4=blocks[3])

                        vip = vip.filter(oct1 & oct2 & oct3 & oct4)
                    else:
                        # IP v6
                        oct1 = oct2 = oct3 = oct4 = oct5 = oct6 = oct7 = oct8 = Q(
                        )

                        if len(blocks[0]) != 0:
                            oct1 = Q(ipv6__block1__iexact=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ipv6__block2__iexact=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ipv6__block3__iexact=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ipv6__block4__iexact=blocks[3])
                        if len(blocks[4]) != 0:
                            oct5 = Q(ipv6__block5__iexact=blocks[4])
                        if len(blocks[5]) != 0:
                            oct6 = Q(ipv6__block6__iexact=blocks[5])
                        if len(blocks[6]) != 0:
                            oct7 = Q(ipv6__block7__iexact=blocks[6])
                        if len(blocks[7]) != 0:
                            oct8 = Q(ipv6__block8__iexact=blocks[7])

                        vip = vip.filter(oct1 & oct2 & oct3 & oct4 & oct5
                                         & oct6 & oct7 & oct8)

            vip = vip.distinct()

            vip = vip.order_by("-pk")

            # Datatable paginator
            vip, total = build_query_to_datatable(vip, asorting_cols,
                                                  custom_search,
                                                  searchable_columns,
                                                  start_record, end_record)

            itens = get_vips(vip)

            vip_map = dict()
            vip_map["vips"] = itens
            vip_map["total"] = total

            return self.response(dumps_networkapi(vip_map))