"""Utility Functions for Handlers.""" from functools import wraps from flask import request from oto.adaptors.flask import flaskify from owsrequest import flask_request from backend.constants import field from backend.validation import json_schema def get_headers(function): """Grab headers from request object. Args: Function (func): the function to be called after grabbing the headers. Returns: Function: The decorated function. """ @wraps(function) def call_function_with_headers(*args, **kwargs): kwargs['correlation_id'] = \ request.headers.get(field.CORRELATION_ID_FIELD) kwargs['account_type'], kwargs['account_id'] = \ flask_request.get_grass_headers(request) function_return = function(*args, **kwargs) return function_return return call_function_with_headers def validate_header(request, validator): """A decorator to call when validating HTTP request headers. Args: request (werkzeug.local.LocalProxy): the request object from the handler. validator (Draft3Validator): the JSON Draft3 Schema to validate against. Returns: callable: the wrapped function. """ def decorator(f): @wraps(f) def _validate_header(*args, **kwargs): """Validate the request headers against a validator. Args: request (werkzeug.local.LocalProxy): the request object from the handler. validator (Draft3Validator): the JSON Draft3 Schema to validate against. Returns: Response: error HTTP response, or continue to the calling function if successful. """ validation_response = json_schema.validate( dict(request.headers), validator) if validation_response.status != 200: return flaskify(validation_response) return f(*args, **kwargs) return _validate_header return decorator def validate_body(request, validator): """A decorator to call when validating HTTP request body. Args: request (werkzeug.local.LocalProxy): the request object from the handler. validator (Draft3Validator): the JSON Draft3 Schema to validate against. Returns: callable: the wrapped function. """ def decorator(f): """Decorator for validate_body method.""" @wraps(f) def _validate_body(*args, **kwargs): """Validate the request body against a validator. Args: request (werkzeug.local.LocalProxy): the request object from the handler. validator (Draft3Validator): the JSON Draft3 Schema to validate against. Returns: Response: error HTTP response, or continue to the calling function if successful. """ validation_response = json_schema.validate( request.get_json(), validator) if validation_response.status != 200: return flaskify(validation_response) return f(*args, **kwargs) return _validate_body return decorator