"""Utility Functions for Handlers.""" import functools from flask import request from oto import response from oto.adaptors.flask import flaskify from owsrequest import flask_request from werkzeug.exceptions import BadRequest from product_digital_marketing.constants import error from product_digital_marketing.constants import header from product_digital_marketing.exceptions import RequestError from product_digital_marketing.exceptions import ValidationError from product_digital_marketing.models import ows_product def parse_request_json(schema=None, partial=False): """Parse and optionally validate request JSON. Args: schema (type): marshmallow schema to validate request partial (bool): parial validation flag Returns: dict: Validated request """ try: request_json = request.get_json() except BadRequest: raise RequestError('Invalid JSON') # Verify request data is enveloped in dict (Marshmallow doesn't catch this) if not isinstance(request_json, dict): raise RequestError('Request envelope must be an object.') if not schema: return request_json result = schema().load(request_json, partial=partial) if result.errors: raise ValidationError(result.errors) return result.data def no_grass_access(func): """Decorate function to check that request is not made from GRASS.""" @functools.wraps(func) def wrapper(*args, **kwargs): account_type, account_id = flask_request.get_grass_headers(request) user_id = request.headers.get(header.ORCHARD_USER_ID) if any((account_type, account_id, user_id)): return flaskify(response.create_error_response( code=error.ERROR_CODE_BAD_GRASS_REQUEST, message=error.ERROR_GRASS_FORBIDDEN)) return func(*args, **kwargs) return wrapper def check_product_ownership(product_id, account_type, account_id): """Check if product is owned by the given account. Args: product_id (int): the id of the product to check account_type (str): type of account (vendor or subaccount) account_id (int): id of the account to check Returns: response.Response: status code 200 if owner, 403 if not owner """ return ows_product.check_ownership(product_id, account_type, account_id)