示例#1
0
    def execute_rule(self, rule, context):
        """
        Check if rule applied over context param is executed,
        that means the rule operand applied on the input param
        of context for the rule value is matched:
               input operand value is True
        :param rule a dict with operand, input_context_param and value
        :param context a dict with input context params value

        :return True if the rule can be executed for the context
        """
        try:

            left_operand = context[rule['input_context_param']]
            right_operand = rule['value']
            if rule['operation'] == 'eq':
                left_operand = convert_str_to_type(left_operand,
                                                   type(right_operand[0]))
                return left_operand == right_operand[0]
            elif rule['operation'] == 'regex':
                pattern = re.compile(right_operand[0])
                return pattern.match(left_operand)
            elif rule['operation'] == 'range':
                if type(right_operand[0]) != type(right_operand[1]):
                    logger.error(
                        "Bad rule definition for range, min and max must be of same type"
                    )
                    raise GenericServiceError("Range rule defined is invalid")
                else:
                    left_operand_c = convert_str_to_type(
                        left_operand, type(right_operand[0]))
                    if left_operand_c is None:
                        raise UnsupportedParameterValueException(
                            left_operand, pretty_type(right_operand[0]))
                    return left_operand_c >= right_operand[
                        0] and left_operand_c <= right_operand[1]
            elif rule['operation'] == 'in':
                left_operand_c = convert_str_to_type(left_operand,
                                                     type(right_operand[0]))
                if left_operand_c is None:
                    raise UnsupportedParameterValueException(
                        left_operand, pretty_type(right_operand[0]))
                return left_operand_c in right_operand
            else:
                msg = "Unsupported operand for rule {0}".format(
                    rule['operation'])
                logger.error(msg)
                raise GenericServiceError(msg)

        except (AttributeError, KeyError) as e:
            logger.debug(str(e))

        return False
示例#2
0
    def delete(self, class_name):
        class_obj = self.class_dao.find(class_name)
        if class_obj:
            try:
                self.instance_dao.delete_by_class_name(class_name)
            except OperationFailure:
                raise GenericServiceError('The class delete process failed.')
            if self.class_dao.delete(class_name):
                return
            else:
                raise GenericServiceError('The class delete process failed.')

        raise NotFoundException(class_name)
示例#3
0
 def get_schema(self, schema_name):
     try:
         return self._schemas[schema_name]
     except KeyError:
         msg = 'The json schema {0} is not found.'.format(schema_name)
         logger.critical(msg)
         raise GenericServiceError(msg)
示例#4
0
    def _redirect2_https(self, request, secure):
        newurl = "https://{}{}".format(request.get_host(), request.get_full_path())
        if request.method == 'POST':
            raise GenericServiceError(u"Can not redirect to https in POST method. Make call with https")

        logger.debug("redirecting request to %s", newurl)
        return HttpResponsePermanentRedirect(newurl)
示例#5
0
    def __init__(self, **dbconfig):
        self.dbconfig = dbconfig or settings.MONGODB
        try:
            if self.dbconfig["slave_ok"]:
                read_preference = ReadPreference.NEAREST
            else:
                read_preference = ReadPreference.PRIMARY

            # Initialize MongoClient connection
            self._db_connection = MongoClient(
                self.dbconfig["hosts"],
                w=self.dbconfig["replicaset_number"],
                replicaset=self.dbconfig["replicaset"],
                read_preference=read_preference,
                auto_start_request=self.dbconfig["autostart"])
            logger.info("Connection to the mongodb started")
        except AutoReconnect as e:
            logger.warning(
                "It has not been possible to connect to all the hosts %s",
                str(e))
        except ConnectionFailure as es:
            logger.critical(
                "It has not been possible to start the connection to the hosts %s",
                str(es))
            raise GenericServiceError("Internal error. Try again later")
示例#6
0
    def update(self, obj):
        # raise not found if not existing class

        if self.class_dao.update(
                obj):  # When OperationFailure, Exception mapper will translate
            return obj
        else:
            raise GenericServiceError('Class update failed')
示例#7
0
    def delete(self, username, auth_username):
        # Ensure user exists
        self.get_user(username)
        if username == settings.SD_USERNAME:
            raise PermissionDenied('default user can not be deleted.')
        elif username == auth_username:
            raise PermissionDenied('Admin user can not delete himself.')

        if self.dao.delete(username) is False:
            raise GenericServiceError('User update failed')
示例#8
0
    def get_service(self):
        """
        Returns a new instance of the service_class defined in the view.
        When no service_class attribute is defined a GenericServiceError is raised.
        """
        if not hasattr(self, 'service_class'):
            logger.critical('%s must define a service_class attribute',
                            self.__class__.__name__)
            raise GenericServiceError('Internal server error. Try again later')

        return self.service_class()
示例#9
0
 def update(self, obj):
     # if not instance is found, not found would be raised in serializers
     try:
         if self.instance_dao.update(obj):
             return obj
         else:
             raise GenericServiceError(
                 'The instance update process failed.')
     except DuplicateKeyError:
         raise UnsupportedParameterValueException(
             '{0}-{1}-{2}'.format(obj['class_name'], obj['uri'],
                                  obj['version']),
             'non-duplicated-instance')
示例#10
0
    def update(self, user, auth_username):
        # user exist validation in serializer
        # Can not update himself
        if user['_id'] == auth_username:
            raise PermissionDenied('Admin user can not update himself.')

        self.validate_classes(user.get('classes', ()))
        if self.dao.update(
                user
        ):  # if OperationFailure is raised, the exception mapper will translate
            return user
        else:
            raise GenericServiceError('User update failed')
示例#11
0
 def update_binding(self, binding):
     if not self.class_dao.find(binding['class_name']):
         raise NotFoundException(binding['class_name'])
     # if not binding is found, not found is already launched in serializers
     try:
         self.check_binding_rules_in_class(binding)
         if self.binding_dao.update_binding(binding):
             return binding
         else:
             raise GenericServiceError('The binding update process failed.')
     except DuplicateKeyError:
         raise UnsupportedParameterValueException(
             '{0}-{1}'.format(binding['class_name'], binding['origin']),
             'non-duplicated-origin')
示例#12
0
def handle_default_500(request):
    """
    Generic function based view for deal with default 500 error
    launched by django
    """

    exc_info = ExceptionMapper().get_exception_info(
        GenericServiceError('Internal error'))
    exc_data = {
        'exceptionId': exc_info['code'],
        'exceptionText': exc_info['details']
    }
    return HttpResponse(content=dumps(exc_data),
                        mimetype='application/json',
                        status=exc_info['status_code'])
示例#13
0
 def delete(self, class_name, instance_id):
     class_obj = self.class_dao.find(class_name)
     if class_obj:
         instance = self.instance_dao.find(instance_id)
         if instance:
             if instance['class_name'] == class_name:
                 if self.instance_dao.delete(instance_id):
                     return
                 else:
                     raise GenericServiceError(
                         'The instance delete process failed.')
             else:
                 raise UnsupportedParameterValueException(
                     '{0}-{1}'.format(class_name, instance_id),
                     'instances-of-class')
         else:
             raise NotFoundException(instance_id)
     raise NotFoundException(class_name)
示例#14
0
    def to_native(self, obj):
        """
        Override to_native:
          add fields to serializer dynamically
          exclude fields with null value
          not all elements in serialization are provided
        """
        try:
            self.create_dynamic_fields(obj)
        except ValidationError:
            raise GenericServiceError('Attributes of class invalid')
        ret = self._dict_class()
        ret.fields = {}

        for field_name, field in self.fields.items():
            field.initialize(parent=self, field_name=field_name)
            key = self.get_field_key(field_name)
            if key not in obj:  # TODO when obj does not have optional key don't fill
                continue
            value = field.field_to_native(obj, field_name)
            ret[key] = value
            ret.fields[key] = field
        return ret
示例#15
0
    def _get_all_schemas(self):
        """
        Reads json schemas folder, validate json schemas and sets
        internal _schemas variable for further use.
        """
        try:
            filePattern = normpath(join(settings.JSON_SCHEMAS_FOLDER,
                                        '*.json'))
        except AttributeError:
            logger.critical("Schemas path not found")
            raise GenericServiceError("Internal error. Try again later")
        files = glob.glob(filePattern)

        for filename in files:
            result = ''.join(open(filename).readlines())
            schema = json.loads(result)
            try:
                Draft4Validator.check_schema(schema)
                self._schemas[schema['title']] = schema
                logger.info("%s loaded.", filename)
            except SchemaError as e:
                logger.info(''.join([filename, " not loaded."]))
                logger.debug(str(e))
        logger.info("All schemas files loaded")
示例#16
0
 def delete_binding(self, binding_id):
     if not self.binding_dao.delete(binding_id, ):
         raise GenericServiceError('The binding delete process failed.')