"""JSON Draft3 Schema Validator Wrapper. A Wrapper for a JSON Draft3 schema validation library which allows us to transform the results into an internal Response() format. """ import re from jsonschema import Draft3Validator from owsresponse import response from blacklist_manager.constants import error def json_validator(schema): """Make validator from schema json. Args: schema (dict): Loaded json file """ return Draft3Validator(schema) def _format_error(validator, validator_value, message): return { 'validator': validator, 'validator_value': validator_value, 'message': message } def add_error_to_errors(errors, field, validator, validator_value, message): """Standardize validation error format. Args: errors (dict): errors to add error to field (string): field to add error for validator (string): type of validator that generated the error validator_value (any): type of value the validator expected message (string): a description of the error """ errors[field] = _format_error(validator, validator_value, message) return errors def validate(data, validator): """Validate Generic JSON Draft3 Schema. Args: data (dict): the JSON to be validated. validator (Draft3Validator): the JSON Draft3 Schema to validate against Returns: Response: the response of the operation. """ errors = {} for e in sorted(validator.iter_errors(data), key=str): field = None if e.relative_path: field = e.relative_path.pop() elif e.absolute_schema_path: field = e.absolute_schema_path.pop() add_error_to_errors( errors, field, e.validator, e.validator_value, e.message) if errors: return response.create_error_response( code=error.VALIDATION_ERROR, message=errors, status=500) return response.Response(message={'status': 'ok'}, status=200) def remove_zero_width_space_characters(data): r"""Remove hidden zero width space characters such as '\u200b'.""" data['word'] = re.compile('[\u200b-\u200d\uFEFF\u180e\u2060]', re.U).sub('', data['word']) return data def detect_excel_formula(data): """Check if the 'word' or 'notes' fields contain an Excel formula. Args: data (dict): Input data to check for formulas. Returns: Response: The response of the operation. """ keys_to_validate = ['word', 'notes'] for key in keys_to_validate: if key in data and isinstance(data[key], str): if '=' in data[key]: words = data[key].split() if any(word.startswith('=') and len(word) > 1 for word in words): return response.create_error_response( code=error.VALIDATION_ERROR, message='Formulas are not allowed in blacklist word data.', status=500) return response.Response(message={'status': 'ok'}, status=200)