"""Module for requests validation.""" import copy from functools import wraps from flask import request from jsonschema import validate from jsonschema import ValidationError from oto import response from oto.adaptors.flask import flaskify as oto_flaskify from salessheets.constants import error from salessheets.constants import field_const from salessheets.validation.schema import header def validate_headers(schema): """A decorator to call when validating HTTP request headers. Args: schema (Draft4Validator): the JSON Draft4 Schema to validate against. Returns: callable: the wrapped function. """ def wrap(function): @wraps(function) def wrapped_f(*args, **kwargs): validation_schema = schema if (field_const.GRASS_ACCOUNT_ID in request.headers or field_const.GRASS_ACCOUNT_TYPE in request.headers): validation_schema = header.alw_schema elif field_const.ORCHARD_USER_ID in request.headers: pass else: return function(*args, **kwargs) try: validate(dict(request.headers), validation_schema) except ValidationError as err: return oto_flaskify( response.create_error_response( code=error.HEADER_VALIDATION_ERROR, message=str(err))) return function(*args, **kwargs) return wrapped_f return wrap def validate_body(schema, schema_tweaks=None): """A decorator to call when validating HTTP request body. Args: schema (Draft4Validator): the JSON Draft4 Schema to validate against. schema_tweaks(callable): the function choosing the schema depending on feature flag. Returns: callable: the wrapped function. """ def wrap(function): @wraps(function) def wrapped_f(*args, **kwargs): body_schema = schema if schema_tweaks: body_schema = copy.deepcopy(schema) schema_tweaks(body_schema) try: validate(request.get_json(), body_schema) except ValidationError as err: return oto_flaskify( response.create_error_response( code=error.BODY_VALIDATION_ERROR, message=str(err))) return function(*args, **kwargs) return wrapped_f return wrap