def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to dissociate User and Group.

        URL: usergroup/user/<id_user>/ugroup/<id_group>/dissociate/
        """

        try:

            self.log.info('Dissociate User and Group.')

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

            id_user = kwargs.get('id_user')
            id_group = kwargs.get('id_group')

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

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

            # Find User by ID to check if it exist
            Usuario.get_by_pk(id_user)

            # Find Group by ID to check if it exist
            UGrupo.get_by_pk(id_group)

            # Find UserGroup by ID to check if it exist
            user_group = UsuarioGrupo.get_by_user_group(id_user, id_group)

            with distributedlock(LOCK_USER_GROUP % (id_user, id_group)):

                try:

                    # remove UserGroup
                    user_group.delete()

                except Exception, e:
                    self.log.error(u'Failed to remove the UserGroup.')
                    raise GrupoError(e, u'Failed to remove the UserGroup.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para alterar a senha de um Usuario.

        URL: user-change-pass/
        """

        try:
            xml_map, attrs_map = loads(request.raw_post_data)
            self.log.info('Change user password')

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

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

            user_map = networkapi_map.get('user')
            if user_map is None:
                return self.response_error(3, u'Não existe valor para a tag usuario do XML de requisição.')

            # Get XML data
            id_user = user_map.get('user_id')
            password = user_map.get('password')

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

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

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            with distributedlock(LOCK_USER % id_user):

                # set variable
                usr.pwd = Usuario.encode_password(password)

                try:
                    # update User
                    usr.save()
                except Exception, e:
                    self.log.error(u'Failed to update the user.')
                    raise UsuarioError(e, u'Failed to update the user.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to dissociate User and Group.

        URL: usergroup/user/<id_user>/ugroup/<id_group>/dissociate/
        """

        try:

            self.log.info('Dissociate User and Group.')

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

            id_user = kwargs.get('id_user')
            id_group = kwargs.get('id_group')

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

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

            # Find User by ID to check if it exist
            Usuario.get_by_pk(id_user)

            # Find Group by ID to check if it exist
            UGrupo.get_by_pk(id_group)

            # Find UserGroup by ID to check if it exist
            user_group = UsuarioGrupo.get_by_user_group(id_user, id_group)

            with distributedlock(LOCK_USER_GROUP % (id_user, id_group)):

                try:

                    # remove UserGroup
                    user_group.delete()

                except Exception, e:
                    self.log.error(u'Failed to remove the UserGroup.')
                    raise GrupoError(e, u'Failed to remove the UserGroup.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
def authenticate(username, password, user_ldap=None):
    '''Busca o usuário com ativo com o login e senha informados.

    @raise UsuarioError: Falha ao pesquisar o usuário.
    '''
    if username is None or password is None:
        return None

    if user_ldap is None:
        return Usuario().get_enabled_user(username, password)
    else:
        return Usuario().get_by_ldap_user(user_ldap, True)
Example #5
0
    def after_return(self, status, retval, task_id, args, kwargs, einfo):

        user = Usuario.get_by_pk(args[1])

        task = celery_app.AsyncResult(task_id)
        if status == 'FAILURE':
            if hasattr(task.result, "exc_message"):
                result = task.result.exc_message
            else:
                result = task.result.message
        else:
            result = task.result

        queue_name = 'tasks.%s' % user.user.lower()
        routing_key = '%s.%s' % (queue_name, task_id)
        queue_manager = QueueManager(broker_vhost='tasks',
                                     queue_name=queue_name,
                                     exchange_name=queue_name,
                                     routing_key=routing_key)
        queue_manager.append({
            'task_id': task_id,
            'status': status,
            'result': result
        })
        queue_manager.send()
Example #6
0
    def after_return(self, status, retval, task_id, args, kwargs, einfo):

        user = Usuario.get_by_pk(args[1])

        task = celery_app.AsyncResult(task_id)
        if status == 'FAILURE':
            if hasattr(task.result, "exc_message"):
                result = task.result.exc_message
            else:
                result = task.result.message
        else:
            result = task.result

        queue_name = 'tasks.%s' % user.user.lower()
        routing_key = '%s.%s' % (queue_name, task_id)
        queue_manager = QueueManager(broker_vhost='tasks',
                                     queue_name=queue_name,
                                     exchange_name=queue_name,
                                     routing_key=routing_key)
        queue_manager.append({
            'task_id': task_id,
            'status': status,
            'result': result
        })
        queue_manager.send()
Example #7
0
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to get User Ldap by the username.

        URL: user/get/ldap/<user_name>/
        """
        try:

            self.log.info("Get User Ldap by the identifier")

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

            user_name = kwargs.get('user_name')

            # Find User by Username to check if it exist
            usr = Usuario.get_by_ldap_user(user_name)

            user_map = dict()
            user_map['usuario'] = model_to_dict(usr)
            user_map['usuario']['grupos'] = user_map['usuario'][
                'grupos'] if user_map['usuario']['grupos'] is not None and len(
                    user_map['usuario']['grupos']) > 0 else [None]

            return self.response(dumps_networkapi(user_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def test_task_id_create_in_put_deploy_one_server_pool_success(self, *args):
        """Test success of id task generate for server pool put deploy success."""

        mock_get_user = args[1]
        mock_get_pool = args[2]
        mock_update_real_pool = args[3]

        user = Usuario(id=1, nome='test')

        divisaodc = DivisaoDc(id=1, nome='test')
        amblog = AmbienteLogico(id=1, nome='test')
        gl3 = GrupoL3(id=1, nome='test')
        ambiente = Ambiente(id=1,
                            grupo_l3=gl3,
                            divisao_dc=divisaodc,
                            ambiente_logico=amblog)

        pool = ServerPool(id=1, identifier='test', environment=ambiente)

        mock_update_real_pool.return_value = pool
        mock_get_pool.return_value = pool
        mock_get_user.return_value = user

        redeploy({'id': pool.id}, user.id)

        mock_update_real_pool.assert_called_with([{'id': pool.id}], user)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to get User by the identifier.

        URL: user/get/<id_user>/
        """
        try:

            self.log.info("Get User by the identifier")

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

            id_user = kwargs.get('id_user')

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

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            user_map = dict()
            user_map['usuario'] = model_to_dict(usr)
            user_map['usuario']['grupos'] = user_map['usuario']['grupos'] if user_map['usuario'][
                'grupos'] is not None and len(user_map['usuario']['grupos']) > 0 else [None]

            return self.response(dumps_networkapi(user_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Example #10
0
    def test_task_id_create_in_delete_deploy_one_server_pool_success(
            self, *args):
        """Test success of id task generate for server pool delete deploy success."""

        mock_get_user = args[1]
        mock_get_pool = args[2]
        mock_delete_real_pool = args[3]

        user = Usuario(id=1, nome='test')

        divisaodc = DivisaoDc(id=1, nome='test')
        amblog = AmbienteLogico(id=1, nome='test')
        gl3 = GrupoL3(id=1, nome='test')
        ambiente = Ambiente(id=1,
                            grupo_l3=gl3,
                            divisao_dc=divisaodc,
                            ambiente_logico=amblog)

        optionpool = OptionPool(id=1, type='test', name='test')
        healthcheck = Healthcheck(id=1)
        pool = ServerPool(id=1,
                          identifier='test',
                          environment=ambiente,
                          servicedownaction=optionpool,
                          healthcheck=healthcheck)

        pool_serializer = serializers.PoolV3Serializer(pool)

        mock_delete_real_pool.return_value = pool
        mock_get_pool.return_value = pool
        mock_get_user.return_value = user

        undeploy(pool.id, user.id)

        mock_delete_real_pool.assert_called_with([pool_serializer.data], user)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to get User Ldap by the username.

        URL: user/get/ldap/<user_name>/
        """
        try:

            self.log.info("Get User Ldap by the identifier")

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

            user_name = kwargs.get('user_name')

            # Find User by Username to check if it exist
            usr = Usuario.get_by_ldap_user(user_name)

            user_map = dict()
            user_map['usuario'] = model_to_dict(usr)
            user_map['usuario']['grupos'] = user_map['usuario']['grupos'] if user_map['usuario'][
                'grupos'] is not None and len(user_map['usuario']['grupos']) > 0 else [None]

            return self.response(dumps_networkapi(user_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def setUp(self):
        self.user = Usuario()
        self.vlan = Vlan(id=1, ambiente=Ambiente(id=1))
        self.network_type = TipoRede(id=1)
        self.vip_env = EnvironmentVip(id=1)
        self.network = NetworkIPv4(oct1=10, oct2=126, oct3=1, oct4=0, block=24)

        self.mock_distributed_lock()
        self.mock_transaction()
    def test_get_by_equip_name_valid(self):
        data = self.dict_for_get_by_equip_name()
        response = self.client_autenticado().postXML(
            self.URL_GET_BY_EQUIP_NAME, data)
        valid_response(response)
        content = valid_content(
            response, "equipamento_roteiro", force_list=True)

        # Verify
        user = Usuario.get_by_user('TEST')
        from_db = EquipamentoRoteiro.objects.filter(equipamento__nome__iexact="Balanceador de Teste", equipamento__grupos__direitosgrupoequipamento__ugrupo__in=user.grupos.all(
        ), equipamento__grupos__direitosgrupoequipamento__escrita='1')
        assert len(from_db) == len(content)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to remove user.

        URL: user/<id_user>/
        """
        try:

            self.log.info('Remove User')

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

            id_user = kwargs.get('id_user')

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

            # Find Permission by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            with distributedlock(LOCK_USER % id_user):

                try:

                    if usr.eventlog_set.count() != 0:
                        raise UsuarioHasEventOrGrupoError(
                            None, u'Existe event_log associado ao usuario %s' %
                            user.id)

                    if usr.usuariogrupo_set.count() != 0:
                        raise UsuarioHasEventOrGrupoError(
                            None,
                            u'Existe grupo associado ao usuario %s' % user.id)

                    # remove User
                    usr.delete()

                except UsuarioHasEventOrGrupoError, e:
                    raise e
                except Exception, e:
                    self.log.error(u'Failed to remove the user.')
                    raise GrupoError(e, u'Failed to remove the user.')
    def test_task_id_create_in_delete_one_netipv4_success(self, *args):
        """Test success of id task generate for netipv4 delete success."""

        mock_get_netv4 = args[1]
        mock_delete_netv4 = args[2]

        net = NetworkIPv4(id=1)
        user = Usuario(id='1', nome='test')

        mock_delete_netv4.return_value = net
        mock_get_netv4.return_value = net

        delete_networkv4(1, user.id)

        mock_delete_netv4.assert_called_with(1)
    def test_task_id_create_in_post_one_vlan_success(self, *args):
        """Test success of id task generate for vlan post success."""

        mock_get_user = args[1]
        mock_create_vlan = args[2]

        user = Usuario(id=1, nome='test')
        vlan = Vlan(id=1)

        mock_create_vlan.return_value = vlan
        mock_get_user.return_value = user

        create_vlan({}, user.id)

        mock_create_vlan.assert_called_with({}, user)
Example #17
0
    def test_task_id_create_in_post_one_ipv4_success(self, *args):
        """V4 Test success of id task generate for ipv4 post success."""

        mock_get_user = args[1]
        mock_create_ipv4 = args[2]

        ipv4 = Ip(id=1)
        user = Usuario(id=1, nome='test')

        mock_create_ipv4.return_value = ipv4
        mock_get_user.return_value = user

        create_ipv4({}, user.id)

        mock_create_ipv4.assert_called_with({}, user)
    def test_task_id_create_in_delete_one_vlan_success(self, *args):
        """Test success of id task generate for vlan delete success."""

        mock_get_vlan = args[1]
        mock_delete_vlan = args[2]

        vlan = Vlan(id=1)
        user = Usuario(id='1', nome='test')

        mock_delete_vlan.return_value = vlan
        mock_get_vlan.return_value = vlan

        delete_vlan(1, user.id)

        mock_delete_vlan.assert_called_with(1)
Example #19
0
    def test_task_id_create_in_delete_one_ipv6_success(self, *args):
        """V4 Test success of id task generate for ipv6 delete success."""

        mock_get_ipv6 = args[1]
        mock_delete_ipv6 = args[2]

        ipv6 = Ip(id=1)
        user = Usuario(id='1', nome='test')

        mock_delete_ipv6.return_value = ipv6
        mock_get_ipv6.return_value = ipv6

        delete_ipv6(1, user.id)

        mock_delete_ipv6.assert_called_with(1)
Example #20
0
    def test_task_id_create_in_delete_deploy_one_netipv6_success(self, *args):
        """Test success of id task generate for netipv6 delete deploy success."""

        mock_get_user = args[1]
        mock_get_netv6 = args[2]
        mock_undeploy_netv6 = args[3]

        net = NetworkIPv6(id=1)
        user = Usuario(id='1', nome='test')

        mock_undeploy_netv6.return_value = net
        mock_get_netv6.return_value = net
        mock_get_user.return_value = user

        undeploy_networkv6(net.id, user.id)

        mock_undeploy_netv6.assert_called_with(net.id, user)
Example #21
0
    def test_task_id_create_in_put_one_ipv6_success(self, *args):
        """V4 Test success of id task generate for ipv6 put success."""

        mock_get_user = args[1]
        mock_get_ipv6 = args[2]
        mock_update_ipv6 = args[3]

        ipv6 = Ip(id=1)
        user = Usuario(id=1, nome='test')

        mock_update_ipv6.return_value = ipv6
        mock_get_ipv6.return_value = ipv6
        mock_get_user.return_value = user

        update_ipv6({'id': 1}, user.id)

        mock_update_ipv6.assert_called_with({'id': 1}, user)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to remove user.

        URL: user/<id_user>/
        """
        try:

            self.log.info('Remove User')

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

            id_user = kwargs.get('id_user')

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

            # Find Permission by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            with distributedlock(LOCK_USER % id_user):

                try:

                    if usr.eventlog_set.count() != 0:
                        raise UsuarioHasEventOrGrupoError(
                            None, u'Existe event_log associado ao usuario %s' % user.id)

                    if usr.usuariogrupo_set.count() != 0:
                        raise UsuarioHasEventOrGrupoError(
                            None, u'Existe grupo associado ao usuario %s' % user.id)

                    # remove User
                    usr.delete()

                except UsuarioHasEventOrGrupoError, e:
                    raise e
                except Exception, e:
                    self.log.error(u'Failed to remove the user.')
                    raise GrupoError(e, u'Failed to remove the user.')
    def test_task_id_create_in_put_deploy_one_vip_request_success(self, *args):
        """Test success of id task generate for vip request put deploy success."""

        mock_get_user = args[1]
        mock_get_vip = args[2]
        mock_update_real_vip = args[3]

        user = Usuario(id=1, nome='test')

        vip = VipRequest(id=1)

        mock_update_real_vip.return_value = vip
        mock_get_vip.return_value = vip
        mock_get_user.return_value = user

        redeploy({'id': vip.id}, user.id)

        mock_update_real_vip.assert_called_with([{'id': vip.id}], user)
Example #24
0
    def test_task_id_create_in_put_one_netipv4_success(self, *args):
        """Test success of id task generate for netipv4 put success."""

        mock_get_user = args[1]
        mock_get_netv4 = args[2]
        mock_update_netv4 = args[3]

        user = Usuario(id=1, nome='test')

        net = NetworkIPv4(id=1)

        mock_update_netv4.return_value = net
        mock_get_netv4.return_value = net
        mock_get_user.return_value = user

        update_networkv4({'id': 1}, user.id)

        mock_update_netv4.assert_called_with({'id': 1}, user)
Example #25
0
    def test_task_id_create_in_post_one_netipv6_success(self, *args):
        """Test success of id task generate for netipv6 post success."""

        mock_get_user = args[1]
        mock_get_netv6 = args[2]
        mock_create_netv6 = args[3]

        user = Usuario(id=1, nome='test')

        net = NetworkIPv6(id=1)

        mock_create_netv6.return_value = net
        mock_get_netv6.return_value = net
        mock_get_user.return_value = user

        create_networkv6({}, user.id)

        mock_create_netv6.assert_called_with({}, user)
Example #26
0
    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

            # Here starts the stuff

            functionalities = Functionality.objects

            acoes = ['Alterar', 'Cadastrar', 'Remover']
            usuarios = Usuario.uniqueUsers()

            funcionalidades = functionalities.all()

            usuarios = UsersList(usuarios)
            funcionalidades = FunctionalitiesList(funcionalidades)

            choices_map = dict()

            choices_map['usuario'] = usuarios
            choices_map['acao'] = acoes
            choices_map['funcionalidade'] = funcionalidades

            return self.response(dumps_networkapi(choices_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 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

            # Here starts the stuff

            functionalities = Functionality.objects

            acoes = ['Alterar', 'Cadastrar', 'Remover']
            usuarios = Usuario.uniqueUsers()

            funcionalidades = functionalities.all()

            usuarios = UsersList(usuarios)
            funcionalidades = FunctionalitiesList(funcionalidades)

            choices_map = dict()

            choices_map['usuario'] = usuarios
            choices_map['acao'] = acoes
            choices_map['funcionalidade'] = funcionalidades

            return self.response(dumps_networkapi(choices_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 test_task_id_create_in_delete_deploy_one_vip_request_success(self, *args):
        """Test success of id task generate for vip request delete deploy success."""
        mock_get_user = args[1]
        mock_get_vip = args[2]
        mock_delete_real_vip = args[3]

        user = Usuario(id=1, nome='test')

        vip = VipRequest(id=1)
        vip_serializer = VipRequestV3Serializer(
            vip, include=('ports__identifier',))

        mock_delete_real_vip.return_value = vip
        mock_get_vip.return_value = vip
        mock_get_user.return_value = user

        undeploy(vip.id, user.id)

        mock_delete_real_vip.assert_called_with(
            [vip_serializer.data], user)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to get User by the identifier.

        URL: user/get/<id_user>/
        """
        try:

            self.log.info('Get User by the identifier')

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

            id_user = kwargs.get('id_user')

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

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            user_map = dict()
            user_map['usuario'] = model_to_dict(usr)
            user_map['usuario']['grupos'] = user_map['usuario'][
                'grupos'] if user_map['usuario']['grupos'] is not None and len(
                    user_map['usuario']['grupos']) > 0 else [None]

            return self.response(dumps_networkapi(user_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def setUp(self):
        self.user = Usuario()
        self.equipment_list = [Equipamento(id=1, nome='router')]
        self.ambiente = Ambiente()
        self.vlan = Vlan(id=1, ambiente=self.ambiente)
        self.networkv4 = NetworkIPv4(id=1,
                                     vlan=self.vlan,
                                     oct1=192,
                                     oct2=168,
                                     oct3=0,
                                     oct4=0,
                                     mask_oct1=255,
                                     mask_oct2=255,
                                     mask_oct3=255,
                                     mask_oct4=0)

        self.networkv6 = NetworkIPv6(id=1,
                                     vlan=self.vlan,
                                     block1='fff',
                                     block2='fff',
                                     block3='fff',
                                     block4='fff',
                                     block5='fff',
                                     block6='fff',
                                     block7='fff',
                                     block8='fff',
                                     mask1='fff',
                                     mask2='fff',
                                     mask3='fff',
                                     mask4='fff',
                                     mask5='fff',
                                     mask6='fff',
                                     mask7='fff',
                                     mask8='fff')

        self.mock_distributed_lock()
        self.mock_transaction()
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add user.

        URL: user/
        """

        try:

            self.log.info('Add User')

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

            # 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:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            user_map = networkapi_map.get('user')
            if user_map is None:
                return self.response_error(3, u'There is no value to the user tag  of XML request.')

            # Get XML data
            username = user_map.get('user')
            password = user_map.get('password')
            name = user_map.get('name')
            email = user_map.get('email')
            user_ldap = user_map.get('user_ldap')

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

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

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

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

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

            try:
                Usuario.get_by_user(username)
                raise UsuarioNameDuplicatedError(
                    None, u'Já existe um usuário com o valor user %s.' % username)
            except UsuarioNotFoundError:
                pass

            usr = Usuario()

            # set variables
            usr.user = username
            usr.pwd = Usuario.encode_password(password)
            usr.nome = name
            usr.email = email
            usr.ativo = True
            usr.user_ldap = user_ldap

            try:
                # save User
                usr.save()
            except Exception, e:
                self.log.error(u'Failed to save the user.')
                raise UsuarioError(e, u'Failed to save the user.')

            perm_map = dict()
            perm_map['usuario'] = model_to_dict(
                usr, exclude=['user', 'nome', 'pwd', 'name', 'email'])

            return self.response(dumps_networkapi(perm_map))
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to associate User and Group.

        URL: usergroup/user/<id_user>/ugroup/<id_group>/associate/
        """

        try:

            self.log.info("Associate User and Group.")

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

            id_user = kwargs.get('id_user')
            id_group = kwargs.get('id_group')

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

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

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            # Find Group by ID to check if it exist
            group = UGrupo.get_by_pk(id_group)

            try:

                # Find UserGroup by ID to check if it exist
                user_group = UsuarioGrupo.get_by_user_group(id_user, id_group)
                raise UsuarioGrupoDuplicatedError(
                    None, u'Usuário já está associado ao Grupo.')
            except UserGroupNotFoundError:
                pass

            user_group = UsuarioGrupo()

            # set variables
            user_group.usuario = usr
            user_group.ugrupo = group

            try:
                # save UserGroup
                user_group.save(user)
            except Exception, e:
                self.log.error(u'Failed to save the UserGroup.')
                raise UsuarioError(e, u'Failed to save the UserGroup.')

            usr_grp_map = dict()
            usr_grp_map['user_group'] = model_to_dict(
                usr, exclude=["usuario", "ugrupo"])

            return self.response(dumps_networkapi(usr_grp_map))
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit User.

        URL: user/<id_user>/
        """
        try:

            self.log.info('Edit User')

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

            id_user = kwargs.get('id_user')

            # 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:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            user_map = networkapi_map.get('user')
            if user_map is None:
                return self.response_error(3, u'There is no value to the user tag  of XML request.')

            # Get XML data
            username = user_map.get('user')
            password = user_map.get('password')
            name = user_map.get('name')
            email = user_map.get('email')
            active = user_map.get('active')
            user_ldap = user_map.get('user_ldap')

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

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

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

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

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

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

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

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            with distributedlock(LOCK_USER % id_user):

                try:
                    if usr.user.lower() != username.lower():
                        Usuario.get_by_user(username)
                        raise UsuarioNameDuplicatedError(
                            None, u'Já existe um usuário com o valor user %s.' % username)
                except UsuarioNotFoundError:
                    pass

                # set variables
                usr.user = username
                usr.pwd = password
                usr.nome = name
                usr.email = email
                usr.ativo = convert_string_or_int_to_boolean(active)
                usr.user_ldap = user_ldap

                try:
                    # update User
                    usr.save()
                except Exception, e:
                    self.log.error(u'Failed to update the user.')
                    raise UsuarioError(e, u'Failed to update the user.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Example #34
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add user.

        URL: user/
        """

        try:

            self.log.info('Add User')

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

            # 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:
                return self.response_error(
                    3,
                    u'There is no value to the networkapi tag  of XML request.'
                )

            user_map = networkapi_map.get('user')
            if user_map is None:
                return self.response_error(
                    3, u'There is no value to the user tag  of XML request.')

            # Get XML data
            username = user_map.get('user')
            password = user_map.get('password')
            name = user_map.get('name')
            email = user_map.get('email')
            user_ldap = user_map.get('user_ldap')

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

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

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

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

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

            try:
                Usuario.get_by_user(username)
                raise UsuarioNameDuplicatedError(
                    None,
                    u'Já existe um usuário com o valor user %s.' % username)
            except UsuarioNotFoundError:
                pass

            usr = Usuario()

            # set variables
            usr.user = username
            usr.pwd = Usuario.encode_password(password)
            usr.nome = name
            usr.email = email
            usr.ativo = True
            usr.user_ldap = user_ldap

            try:
                # save User
                usr.save()
            except Exception, e:
                self.log.error(u'Failed to save the user.')
                raise UsuarioError(e, u'Failed to save the user.')

            perm_map = dict()
            perm_map['usuario'] = model_to_dict(
                usr, exclude=['user', 'nome', 'pwd', 'name', 'email'])

            return self.response(dumps_networkapi(perm_map))
Example #35
0
 def setUp(self):
     self.client = Client()
     self.user = Usuario(id=1, nome='test')
Example #36
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to associate User and Group.

        URL: usergroup/user/<id_user>/ugroup/<id_group>/associate/
        """

        try:

            self.log.info("Associate User and Group.")

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

            id_user = kwargs.get('id_user')
            id_group = kwargs.get('id_group')

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

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

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            # Find Group by ID to check if it exist
            group = UGrupo.get_by_pk(id_group)

            try:

                # Find UserGroup by ID to check if it exist
                user_group = UsuarioGrupo.get_by_user_group(id_user, id_group)
                raise UsuarioGrupoDuplicatedError(
                    None, u'Usuário já está associado ao Grupo.')
            except UserGroupNotFoundError:
                pass

            user_group = UsuarioGrupo()

            # set variables
            user_group.usuario = usr
            user_group.ugrupo = group

            try:
                # save UserGroup
                user_group.save()
            except Exception, e:
                self.log.error(u'Failed to save the UserGroup.')
                raise UsuarioError(e, u'Failed to save the UserGroup.')

            usr_grp_map = dict()
            usr_grp_map['user_group'] = model_to_dict(
                usr, exclude=["usuario", "ugrupo"])

            return self.response(dumps_networkapi(usr_grp_map))
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit User.

        URL: user/<id_user>/
        """
        try:

            self.log.info('Edit User')

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

            id_user = kwargs.get('id_user')

            # 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:
                return self.response_error(
                    3,
                    u'There is no value to the networkapi tag  of XML request.'
                )

            user_map = networkapi_map.get('user')
            if user_map is None:
                return self.response_error(
                    3, u'There is no value to the user tag  of XML request.')

            # Get XML data
            username = user_map.get('user')
            password = user_map.get('password')
            name = user_map.get('name')
            email = user_map.get('email')
            active = user_map.get('active')
            user_ldap = user_map.get('user_ldap')

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

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

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

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

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

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

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

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            with distributedlock(LOCK_USER % id_user):

                try:
                    if usr.user.lower() != username.lower():
                        Usuario.get_by_user(username)
                        raise UsuarioNameDuplicatedError(
                            None,
                            u'Já existe um usuário com o valor user %s.' %
                            username)
                except UsuarioNotFoundError:
                    pass

                # set variables
                usr.user = username
                usr.pwd = password
                usr.nome = name
                usr.email = email
                usr.ativo = convert_string_or_int_to_boolean(active)
                usr.user_ldap = user_ldap

                try:
                    # update User
                    usr.save()
                except Exception, e:
                    self.log.error(u'Failed to update the user.')
                    raise UsuarioError(e, u'Failed to update the user.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Example #38
0
 def setUp(self):
     self.user = Usuario(id=1, nome='users')
     self.mock_transaction()
Example #39
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to authenticate to user.

        URL: authenticate/
        """

        try:

            self.log.info('Authenticate user')

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

            # 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:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            user_map = networkapi_map.get('user')
            if user_map is None:
                return self.response_error(3, u'There is no value to the user tag  of XML request.')

            # Get XML data
            username = user_map.get('username')
            password = user_map.get('password')
            is_ldap_user = user_map.get('is_ldap_user')

            # Username can NOT be less 3 and greater than 45
            if not is_valid_string_minsize(username, 3) or not is_valid_string_maxsize(username, 45):
                self.log.error(
                    u'Parameter username is invalid. Value: %s.', username)
                raise InvalidValueError(None, 'username', username)

            if not is_valid_boolean_param(is_ldap_user):
                self.log.error(
                    u'Parameter is_ldap_user is invalid. Value: %s.', is_ldap_user)
                raise InvalidValueError(None, 'is_ldap_user', is_ldap_user)
            else:
                is_ldap_user = convert_string_or_int_to_boolean(is_ldap_user)

            if is_ldap_user:
                user = Usuario().get_by_ldap_user(username, True)
                password = user.pwd
            else:
                # Password can NOT be less 3 and greater than 45
                if not is_valid_string_minsize(password, 3) or not is_valid_string_maxsize(password, 45):
                    self.log.error(
                        u'Parameter password is invalid. Value: %s.', '****')
                    raise InvalidValueError(None, 'password', '****')

                # Find user by username, password to check if it exist
                user = Usuario().get_enabled_user(username.upper(), password)

            # Valid user
            if user is None:
                return self.response(dumps_networkapi({}))

            perms = {}
            for ugroup in user.grupos.all():

                for perm in ugroup.permissaoadministrativa_set.all():

                    function = perm.permission.function

                    if function in perms:

                        write = False
                        read = False

                        if perms.get(function).get('write') is True or perm.escrita is True:
                            write = True

                        if perms.get(function).get('read') is True or perm.leitura is True:
                            read = True

                        perms[function] = {'write': write, 'read': read}

                    else:
                        perms[function] = {
                            'write': perm.escrita, 'read': perm.leitura}

            user_map = {}
            user_dict = model_to_dict(
                user, fields=['id', 'user', 'nome', 'email', 'ativo', 'user_ldap'])
            user_dict['pwd'] = password
            user_dict['permission'] = perms
            user_map['user'] = user_dict

            return self.response(dumps_networkapi(user_map))

        except UsuarioNotFoundError:
            return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)