コード例 #1
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Access Type.

        URL: /tipoacesso/

        """

        try:
            if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3, u'There is no networkapi tag in request XML.')

            tipo_acesso_map = networkapi_map.get('tipo_acesso')
            if tipo_acesso_map is None:
                return self.response_error(
                    3, u'There is no tipo_acesso tag in request XML.')

            # Valid protocol
            protocol = tipo_acesso_map.get('protocolo')
            if not is_valid_string_minsize(
                    protocol, 3) or not is_valid_string_maxsize(
                        protocol, 45) or not is_valid_regex(
                            protocol, r'^[- a-zA-Z0-9]+$'):
                self.log.error(u'Parameter protocol is invalid. Value: %s',
                               protocol)
                raise InvalidValueError(None, 'protocol', protocol)

            access_type = TipoAcesso()
            access_type.protocolo = protocol

            try:
                TipoAcesso.objects.get(protocolo__iexact=access_type.protocolo)
                raise DuplicateProtocolError(
                    None,
                    u'Access Type with protocol %s already exists' % protocol)
            except TipoAcesso.DoesNotExist:
                pass

            try:
                # save access type
                access_type.save()
            except Exception, e:
                self.log.error(u'Failed to save TipoAcesso.')
                raise TipoAcessoError(e, u'Failed to save TipoAcesso.')

            return self.response(
                dumps_networkapi({'tipo_acesso': {
                    'id': access_type.id
                }}))
コード例 #2
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir uma informação de acesso a equipamento

        URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/

        """

        # Verifica acesso e obtém dados do request
        try:
            # Obtém argumentos passados na URL
            id_equipamento = kwargs.get('id_equipamento')

            # Valid ID Equipment
            if not is_valid_int_greater_zero_param(id_equipamento):
                self.log.error(
                    u'The id_equipamento parameter is not a valid value: %s.',
                    id_equipamento)
                raise InvalidValueError(None, 'id_equipamento', id_equipamento)

            id_tipo_acesso = kwargs.get('id_tipo_acesso')

            # Valid ID Equipment
            if not is_valid_int_greater_zero_param(id_tipo_acesso):
                self.log.error(
                    u'The id_tipo_acesso parameter is not a valid value: %s.',
                    id_tipo_acesso)
                raise InvalidValueError(None, 'id_tipo_acesso', id_tipo_acesso)

            Equipamento.get_by_pk(id_equipamento)

            TipoAcesso.get_by_pk(id_tipo_acesso)

            # Após obtenção do id_equipamento podemos verificar a permissão
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION, None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_ACCESS % id_tipo_acesso):

                # Remove a informação de acesso a equipamento
                EquipamentoAcesso.remove(user, id_equipamento, id_tipo_acesso)

                # Retorna response vazio em caso de sucesso
                return self.response(dumps_networkapi({}))
        except InvalidValueError as e:
            return self.response_error(269, e.param, e.value)
        except EquipamentoNotFoundError:
            return self.response_error(117, id_equipamento)
        except AccessTypeNotFoundError:
            return self.response_error(171, id_tipo_acesso)
        except EquipamentoAcesso.DoesNotExist:
            return self.response_error(209, id_equipamento, id_tipo_acesso)
        except (EquipamentoError, GrupoError):
            return self.response_error(1)
コード例 #3
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Access Type.

        URL: /tipoacesso/

        """

        try:
            if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(u"User does not have permission to perform the operation.")
                raise UserNotAuthorizedError(None)

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get("networkapi")
            if networkapi_map is None:
                return self.response_error(3, u"There is no networkapi tag in request XML.")

            tipo_acesso_map = networkapi_map.get("tipo_acesso")
            if tipo_acesso_map is None:
                return self.response_error(3, u"There is no tipo_acesso tag in request XML.")

            # Valid protocol
            protocol = tipo_acesso_map.get("protocolo")
            if (
                not is_valid_string_minsize(protocol, 3)
                or not is_valid_string_maxsize(protocol, 45)
                or not is_valid_regex(protocol, r"^[- a-zA-Z0-9]+$")
            ):
                self.log.error(u"Parameter protocol is invalid. Value: %s", protocol)
                raise InvalidValueError(None, "protocol", protocol)

            access_type = TipoAcesso()
            access_type.protocolo = protocol

            try:
                TipoAcesso.objects.get(protocolo__iexact=access_type.protocolo)
                raise DuplicateProtocolError(None, u"Access Type with protocol %s already exists" % protocol)
            except TipoAcesso.DoesNotExist:
                pass

            try:
                # save access type
                access_type.save(user)
            except Exception, e:
                self.log.error(u"Failed to save TipoAcesso.")
                raise TipoAcessoError(e, u"Failed to save TipoAcesso.")

            return self.response(dumps_networkapi({"tipo_acesso": {"id": access_type.id}}))
コード例 #4
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir uma informação de acesso a equipamento

        URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/ 

        """

        # Verifica acesso e obtém dados do request
        try:
            # Obtém argumentos passados na URL
            id_equipamento = kwargs.get('id_equipamento')

            # Valid ID Equipment
            if not is_valid_int_greater_zero_param(id_equipamento):
                self.log.error(
                    u'The id_equipamento parameter is not a valid value: %s.', id_equipamento)
                raise InvalidValueError(None, 'id_equipamento', id_equipamento)

            id_tipo_acesso = kwargs.get('id_tipo_acesso')

            # Valid ID Equipment
            if not is_valid_int_greater_zero_param(id_tipo_acesso):
                self.log.error(
                    u'The id_tipo_acesso parameter is not a valid value: %s.', id_tipo_acesso)
                raise InvalidValueError(None, 'id_tipo_acesso', id_tipo_acesso)

            Equipamento.get_by_pk(id_equipamento)

            TipoAcesso.get_by_pk(id_tipo_acesso)

            # Após obtenção do id_equipamento podemos verificar a permissão
            if not has_perm(user,
                            AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_ACCESS % id_tipo_acesso):

                # Remove a informação de acesso a equipamento
                EquipamentoAcesso.remove(user, id_equipamento, id_tipo_acesso)

                # Retorna response vazio em caso de sucesso
                return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
コード例 #5
0
    def test_alter_unique(self):
        tpa = model_to_dict(TipoAcesso.get_by_pk(self.ID_VALID))

        mock = self.mock_valid()
        mock[self.KEY_ATTR] = tpa[self.KEY_ATTR]
        self.process_alter_attr_invalid(
            self.ID_ALTER_VALID, mock, CodeError.ACCESS_TYPE_DUPLICATE)
コード例 #6
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to edit Access Type.

        URL: /tipoacesso/<id_tipo_acesso>/

        """

        try:
            if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(u"User does not have permission to perform the operation.")
                raise UserNotAuthorizedError(None)

            # Valid Access Type ID
            tipo_acesso_id = kwargs.get("id_tipo_acesso")
            if not is_valid_int_greater_zero_param(tipo_acesso_id):
                self.log.error(u"The tipo_acesso_id parameter is not a valid value: %s.", tipo_acesso_id)
                raise InvalidValueError(None, "tipo_acesso_id", tipo_acesso_id)

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get("networkapi")
            if networkapi_map is None:
                return self.response_error(3, u"There is no networkapi tag in request XML.")

            tipo_acesso_map = networkapi_map.get("tipo_acesso")
            if tipo_acesso_map is None:
                return self.response_error(3, u"There is no tipo_acesso tag in request XML.")

            # Valid protocol
            protocol = tipo_acesso_map.get("protocolo")
            if (
                not is_valid_string_minsize(protocol, 3)
                or not is_valid_string_maxsize(protocol, 45)
                or not is_valid_regex(protocol, r"^[- a-zA-Z0-9]+$")
            ):
                self.log.error(u"Parameter protocol is invalid. Value: %s", protocol)
                raise InvalidValueError(None, "protocol", protocol)

            # Verify existence
            tpa = TipoAcesso.get_by_pk(tipo_acesso_id)

            tpa.protocolo = protocol

            try:
                if len(TipoAcesso.objects.filter(protocolo__iexact=protocol).exclude(id=tpa.id)) > 0:
                    raise DuplicateProtocolError(None, u"Access Type with protocol %s already exists" % protocol)
            except TipoAcesso.DoesNotExist:
                pass

            with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id):

                try:
                    # save access type
                    tpa.save(user)
                except Exception, e:
                    self.log.error(u"Failed to update TipoAcesso.")
                    raise TipoAcessoError(e, u"Failed to update TipoAcesso.")

            return self.response(dumps_networkapi({}))
コード例 #7
0
    def test_alter_valid(self):
        mock = self.mock_valid()
        mock["protocolo"] = "protocolo-alter-valido"
        response = self.alter(self.ID_ALTER_VALID, {self.XML_KEY: mock})
        valid_response(response)

        tpa = TipoAcesso.get_by_pk(self.ID_ALTER_VALID)
        self.valid_attr(mock, model_to_dict(tpa))
コード例 #8
0
    def test_save_valid(self):
        mock = self.mock_valid()
        response = self.save({self.XML_KEY: mock})
        valid_response(response)
        content = valid_content(response, self.XML_KEY)

        tpa = TipoAcesso.get_by_pk(content["id"])
        self.valid_attr(mock, model_to_dict(tpa))
コード例 #9
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to remove Access Type.

        URL: /tipoacesso/<id_tipo_acesso>/ 

        """

        try:
            if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Valid Access Type ID
            tipo_acesso_id = kwargs.get('id_tipo_acesso')
            if not is_valid_int_greater_zero_param(tipo_acesso_id):
                self.log.error(
                    u'The tipo_acesso_id parameter is not a valid value: %s.',
                    tipo_acesso_id)
                raise InvalidValueError(None, 'tipo_acesso_id', tipo_acesso_id)

            # Verify existence
            tpa = TipoAcesso.get_by_pk(tipo_acesso_id)

            with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id):

                # Verifica se o tipo de acesso não é utilizado por algum
                # equipamento
                if tpa.equipamentoacesso_set.count() > 0:
                    self.log.error(u'Access Type in use by equipment.')
                    raise AccessTypeUsedByEquipmentError(
                        None, u'Access Type in use by equipment.')

                tpa.delete()

            return self.response(dumps_networkapi({}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except AccessTypeNotFoundError:
            return self.response_error(171, tipo_acesso_id)
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
コード例 #10
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to remove Access Type.

        URL: /tipoacesso/<id_tipo_acesso>/ 

        """

        try:
            if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Valid Access Type ID
            tipo_acesso_id = kwargs.get('id_tipo_acesso')
            if not is_valid_int_greater_zero_param(tipo_acesso_id):
                self.log.error(
                    u'The tipo_acesso_id parameter is not a valid value: %s.', tipo_acesso_id)
                raise InvalidValueError(None, 'tipo_acesso_id', tipo_acesso_id)

            # Verify existence
            tpa = TipoAcesso.get_by_pk(tipo_acesso_id)

            with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id):

                # Verifica se o tipo de acesso não é utilizado por algum
                # equipamento
                if tpa.equipamentoacesso_set.count() > 0:
                    self.log.error(u'Access Type in use by equipment.')
                    raise AccessTypeUsedByEquipmentError(
                        None, u'Access Type in use by equipment.')

                tpa.delete()

            return self.response(dumps_networkapi({}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except AccessTypeNotFoundError:
            return self.response_error(171, tipo_acesso_id)
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
コード例 #11
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to edit Access Type.

        URL: /tipoacesso/<id_tipo_acesso>/

        """

        try:
            if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Valid Access Type ID
            tipo_acesso_id = kwargs.get('id_tipo_acesso')
            if not is_valid_int_greater_zero_param(tipo_acesso_id):
                self.log.error(
                    u'The tipo_acesso_id parameter is not a valid value: %s.',
                    tipo_acesso_id)
                raise InvalidValueError(None, 'tipo_acesso_id', tipo_acesso_id)

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3, u'There is no networkapi tag in request XML.')

            tipo_acesso_map = networkapi_map.get('tipo_acesso')
            if tipo_acesso_map is None:
                return self.response_error(
                    3, u'There is no tipo_acesso tag in request XML.')

            # Valid protocol
            protocol = tipo_acesso_map.get('protocolo')
            if not is_valid_string_minsize(
                    protocol, 3) or not is_valid_string_maxsize(
                        protocol, 45) or not is_valid_regex(
                            protocol, r'^[- a-zA-Z0-9]+$'):
                self.log.error(u'Parameter protocol is invalid. Value: %s',
                               protocol)
                raise InvalidValueError(None, 'protocol', protocol)

            # Verify existence
            tpa = TipoAcesso.get_by_pk(tipo_acesso_id)

            tpa.protocolo = protocol

            try:
                if len(
                        TipoAcesso.objects.filter(
                            protocolo__iexact=protocol).exclude(
                                id=tpa.id)) > 0:
                    raise DuplicateProtocolError(
                        None, u'Access Type with protocol %s already exists' %
                        protocol)
            except TipoAcesso.DoesNotExist:
                pass

            with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id):

                try:
                    # save access type
                    tpa.save()
                except Exception, e:
                    self.log.error(u'Failed to update TipoAcesso.')
                    raise TipoAcessoError(e, u'Failed to update TipoAcesso.')

            return self.response(dumps_networkapi({}))
コード例 #12
0
    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para criar Informações de Acesso a Equipamentos.

        URL: /equipamentoacesso

        """

        # Obtém dados do request e verifica acesso
        try:
            # Obtém os dados do xml do request
            xml_map, attrs_map = loads(request.raw_post_data)

            # Obtém o mapa correspondente ao root node do mapa do XML
            # (networkapi)
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag networkapi do XML de requisição.'
                )

            # Verifica a existência do node "equipamento_acesso"
            equipamento_acesso_map = networkapi_map.get('equipamento_acesso')
            if equipamento_acesso_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag equipamento_acesso do XML de requisição.'
                )

            # Verifica a existência do valor "id_equipamento"
            id_equipamento = equipamento_acesso_map.get('id_equipamento')

            # Valid ID Equipment
            if not is_valid_int_greater_zero_param(id_equipamento):
                self.log.error(
                    u'The id_equipamento parameter is not a valid value: %s.',
                    id_equipamento)
                raise InvalidValueError(None, 'id_equipamento', id_equipamento)

            try:
                id_equipamento = int(id_equipamento)
            except (TypeError, ValueError):
                self.log.error(u'Valor do id_equipamento inválido: %s.',
                               id_equipamento)
                return self.response_error(117, id_equipamento)

            # Após obtenção do id_equipamento podemos verificar a permissão
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION, None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            # Verifica a existência do valor "fqdn"
            fqdn = equipamento_acesso_map.get('fqdn')

            # Valid fqdn
            if not is_valid_string_maxsize(
                    fqdn, 100) or not is_valid_string_minsize(fqdn, 4):
                self.log.error(u'Parameter fqdn is invalid. Value: %s', fqdn)
                raise InvalidValueError(None, 'fqdn', fqdn)

            # Verifica a existência do valor "user"
            username = equipamento_acesso_map.get('user')

            # Valid username
            if not is_valid_string_maxsize(
                    username, 20) or not is_valid_string_minsize(username, 3):
                self.log.error(u'Parameter username is invalid. Value: %s',
                               username)
                raise InvalidValueError(None, 'username', username)

            # Verifica a existência do valor "pass"
            password = equipamento_acesso_map.get('pass')

            # Valid password
            if not is_valid_string_maxsize(
                    password, 150) or not is_valid_string_minsize(password, 3):
                self.log.error(u'Parameter password is invalid.')
                raise InvalidValueError(None, 'password', '****')

            # Verifica a existência do valor "id_tipo_acesso"
            id_tipo_acesso = equipamento_acesso_map.get('id_tipo_acesso')

            # Valid ID Equipment
            if not is_valid_int_greater_zero_param(id_tipo_acesso):
                self.log.error(
                    u'The id_tipo_acesso parameter is not a valid value: %s.',
                    id_tipo_acesso)
                raise InvalidValueError(None, 'id_tipo_acesso', id_tipo_acesso)

            try:
                id_tipo_acesso = int(id_tipo_acesso)
            except (TypeError, ValueError):
                self.log.error(u'Valor do id_tipo_acesso inválido: %s.',
                               id_tipo_acesso)
                return self.response_error(171, id_tipo_acesso)

            # Obtém o valor de "enable_pass"
            enable_pass = equipamento_acesso_map.get('enable_pass')

            # Valid enable_pass
            if not is_valid_string_maxsize(enable_pass,
                                           150) or not is_valid_string_minsize(
                                               enable_pass, 3):
                self.log.error(u'Parameter enable_pass is invalid.')
                raise InvalidValueError(None, 'enable_pass', '****')

            # Cria acesso ao equipamento conforme dados recebidos no XML
            equipamento_acesso = EquipamentoAcesso(
                equipamento=Equipamento(id=id_equipamento),
                fqdn=fqdn,
                user=username,
                password=password,
                tipo_acesso=TipoAcesso(id=id_tipo_acesso),
                enable_pass=enable_pass)
            equipamento_acesso.create(user)

            # Monta dict para response
            networkapi_map = dict()
            equipamento_acesso_map = dict()

            equipamento_acesso_map['id'] = equipamento_acesso.id
            networkapi_map['equipamento_acesso'] = equipamento_acesso_map

            return self.response(dumps_networkapi(networkapi_map))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
コード例 #13
0
    def handle_post(self, request, auth, *args, **kwargs):
        """Handles POST requests to update Equipment Access by id.

        URLs: /equipmentaccess/edit/
        """

        self.log.info('Update EquipmentAccess by id')

        try:

            # Commons Validations

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # 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)
            equipmentaccess_map = networkapi_map.get('equipamento_acesso')
            if equipmentaccess_map is None:
                msg = u'There is no value to the equipamento_acesso tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            user = equipmentaccess_map.get('user')
            password = equipmentaccess_map.get('pass')
            fqdn = equipmentaccess_map.get('fqdn')
            enable_pass = equipmentaccess_map.get('enable_pass')
            type_access = equipmentaccess_map.get('id_tipo_acesso')
            equip_access = equipmentaccess_map.get('id_equip_acesso')

            # Password must NOT be none and 20 is the maxsize and 3 is the
            # minsize
            if not is_valid_string_maxsize(password, 150) or not is_valid_string_minsize(password, 3):
                self.log.error(u'Parameter pass is invalid.')
                raise InvalidValueError(None, 'pass', '****')

            # Enable Pass must NOT be none and 20 is the maxsize and 3 is the
            # minsize
            if not is_valid_string_maxsize(enable_pass, 150) or not is_valid_string_minsize(enable_pass, 3):
                self.log.error(u'Parameter enable_pass is invalid.')
                raise InvalidValueError(None, 'enable_pass', '****')

            # User must NOT be none and 20 is the maxsize and 3 is the minsize
            if not is_valid_string_maxsize(user, 20) or not is_valid_string_minsize(user, 3):
                self.log.error(u'Parameter user is invalid. Value: %s.', user)
                raise InvalidValueError(None, 'user', user)

            # Host must NOT be none and 100 is the maxsize and 4 is the minsize
            if not is_valid_string_maxsize(fqdn, 100) or not is_valid_string_minsize(fqdn, 4):
                self.log.error(u'Parameter fqdn is invalid. Value: %s.', fqdn)
                raise InvalidValueError(None, 'fqdn', fqdn)

            # Type Access
            # Valid type access ID
            if not is_valid_int_greater_zero_param(type_access):
                self.log.error(
                    u'Parameter type_access_id is invalid. Value: %s.', type_access)
                raise InvalidValueError(None, 'type_access_id', type_access)

            type_access = TipoAcesso.get_by_pk(type_access)

            # Business Rules
            equip_access = EquipamentoAcesso.get_by_pk(equip_access)

            # User permission
            if not has_perm(auth, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, equip_access.equipamento.id, AdminPermission.EQUIP_WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_ACCESS % type_access.id):

                # valid duplicate association
                if not (int(type_access.id) == int(equip_access.tipo_acesso.id)):
                    if EquipamentoAcesso.objects.filter(equipamento=equip_access.equipamento, tipo_acesso=type_access).count() > 0:
                        raise EquipamentoAccessDuplicatedError(
                            None, u'Já existe esta associação de equipamento e tipo de acesso cadastrada.')

                equip_access.__dict__.update(
                    fqdn=fqdn, user=user, password=password, enable_pass=enable_pass)
                equip_access.tipo_acesso = type_access

                equip_access.save(auth)

                # update
                equipmentaccess_map = dict()
                equipmentaccess_map[
                    'equipamento_acesso'] = model_to_dict(equip_access)

                # Return XML
                return self.response(dumps_networkapi(equipmentaccess_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
コード例 #14
0
    def handle_post(self, request, auth, *args, **kwargs):
        """Handles POST requests to update Equipment Access by id.

        URLs: /equipmentaccess/edit/
        """

        self.log.info('Update EquipmentAccess by id')

        try:

            # Commons Validations

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # 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)
            equipmentaccess_map = networkapi_map.get('equipamento_acesso')
            if equipmentaccess_map is None:
                msg = u'There is no value to the equipamento_acesso tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            user = equipmentaccess_map.get('user')
            password = equipmentaccess_map.get('pass')
            fqdn = equipmentaccess_map.get('fqdn')
            enable_pass = equipmentaccess_map.get('enable_pass')
            type_access = equipmentaccess_map.get('id_tipo_acesso')
            equip_access = equipmentaccess_map.get('id_equip_acesso')

            # Password must NOT be none and 20 is the maxsize and 3 is the
            # minsize
            if not is_valid_string_maxsize(
                    password, 150) or not is_valid_string_minsize(password, 3):
                self.log.error(u'Parameter pass is invalid.')
                raise InvalidValueError(None, 'pass', '****')

            # Enable Pass must NOT be none and 20 is the maxsize and 3 is the
            # minsize
            if not is_valid_string_maxsize(enable_pass,
                                           150) or not is_valid_string_minsize(
                                               enable_pass, 3):
                self.log.error(u'Parameter enable_pass is invalid.')
                raise InvalidValueError(None, 'enable_pass', '****')

            # User must NOT be none and 20 is the maxsize and 3 is the minsize
            if not is_valid_string_maxsize(
                    user, 20) or not is_valid_string_minsize(user, 3):
                self.log.error(u'Parameter user is invalid. Value: %s.', user)
                raise InvalidValueError(None, 'user', user)

            # Host must NOT be none and 100 is the maxsize and 4 is the minsize
            if not is_valid_string_maxsize(
                    fqdn, 100) or not is_valid_string_minsize(fqdn, 4):
                self.log.error(u'Parameter fqdn is invalid. Value: %s.', fqdn)
                raise InvalidValueError(None, 'fqdn', fqdn)

            # Type Access
            # Valid type access ID
            if not is_valid_int_greater_zero_param(type_access):
                self.log.error(
                    u'Parameter type_access_id is invalid. Value: %s.',
                    type_access)
                raise InvalidValueError(None, 'type_access_id', type_access)

            type_access = TipoAcesso.get_by_pk(type_access)

            # Business Rules
            equip_access = EquipamentoAcesso.get_by_pk(equip_access)

            # User permission
            if not has_perm(auth, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION, None,
                            equip_access.equipamento.id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_ACCESS % type_access.id):

                # valid duplicate association
                if not (int(type_access.id) == int(
                        equip_access.tipo_acesso.id)):
                    if EquipamentoAcesso.objects.filter(
                            equipamento=equip_access.equipamento,
                            tipo_acesso=type_access).count() > 0:
                        raise EquipamentoAccessDuplicatedError(
                            None,
                            u'Já existe esta associação de equipamento e tipo de acesso cadastrada.'
                        )

                equip_access.__dict__.update(fqdn=fqdn,
                                             user=user,
                                             password=password,
                                             enable_pass=enable_pass)
                equip_access.tipo_acesso = type_access

                equip_access.save(auth)

                # update
                equipmentaccess_map = dict()
                equipmentaccess_map['equipamento_acesso'] = model_to_dict(
                    equip_access)

                # Return XML
                return self.response(dumps_networkapi(equipmentaccess_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)