2016-10-25 14:53:31 +01:00
|
|
|
import json
|
2016-11-09 14:56:54 +00:00
|
|
|
|
2016-11-14 13:56:09 +00:00
|
|
|
from jsonschema import (Draft4Validator, ValidationError, FormatChecker)
|
|
|
|
|
from notifications_utils.recipients import (validate_phone_number, validate_email_address)
|
2016-10-25 14:53:31 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def validate(json_to_validate, schema):
|
2016-11-14 13:56:09 +00:00
|
|
|
format_checker = FormatChecker()
|
|
|
|
|
|
|
|
|
|
@format_checker.checks('phone_number')
|
|
|
|
|
def validate_schema_phone_number(instance):
|
|
|
|
|
return validate_phone_number(instance)
|
|
|
|
|
|
|
|
|
|
@format_checker.checks('email_address')
|
|
|
|
|
def validate_schema_email_address(instance):
|
|
|
|
|
return validate_email_address(instance)
|
|
|
|
|
|
|
|
|
|
validator = Draft4Validator(schema, format_checker=format_checker)
|
2016-10-25 14:53:31 +01:00
|
|
|
errors = list(validator.iter_errors(json_to_validate))
|
|
|
|
|
if errors.__len__() > 0:
|
|
|
|
|
raise ValidationError(build_error_message(errors, schema))
|
|
|
|
|
return json_to_validate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def build_error_message(errors, schema):
|
|
|
|
|
fields = []
|
|
|
|
|
for e in errors:
|
|
|
|
|
field = "'{}' {}".format(e.path[0], e.schema.get('validationMessage')) if e.schema.get(
|
|
|
|
|
'validationMessage') else e.message
|
2016-11-02 09:13:48 +00:00
|
|
|
s = field.split("'")
|
2016-11-11 10:50:38 +00:00
|
|
|
field = {"error": "ValidationError", "message": "{}{}".format(s[1], s[2])}
|
2016-10-25 14:53:31 +01:00
|
|
|
fields.append(field)
|
|
|
|
|
message = {
|
2016-11-02 14:58:39 +00:00
|
|
|
"status_code": 400,
|
2016-11-09 14:56:54 +00:00
|
|
|
"errors": fields
|
2016-10-25 14:53:31 +01:00
|
|
|
}
|
|
|
|
|
|
2016-10-25 18:04:03 +01:00
|
|
|
return json.dumps(message)
|