"""Utility Functions for Handlers.""" import datetime import json from oto import response from product.constants import error, header from product.models import ows_account def check_ownership( account_type_param, account_id_param, account_type=None, account_id=None): """Check whether given subccount_id is owned by vendor_id. Args: account_type_param (string): type of account (vendor or subaccount) account_id_param (int): unique identifier of the vendor / subaccount. account_type (str): Grass Account Type (vendor / subaccount). account_id (int): Grass Account Id (vendor_id / subaccount_id) Returns: response.Response: status code 200 if owner, 403 if not owner """ unauthorized_access_response = response.create_error_response( code=error.ERROR_CODE_AUTHORIZATION, message='No authorization', status=403) if account_type == header.GRASS_ACCOUNT_TYPE_VENDOR and \ account_type_param == header.GRASS_ACCOUNT_TYPE_SUBACCOUNT: result = ows_account.check_subaccount_ownership( int(account_id), account_id_param) if result.status == 403: return unauthorized_access_response else: result = account_type_param == account_type and \ account_id_param == int(account_id) if not result: return unauthorized_access_response return result class DatetimeEncoder(json.JSONEncoder): """Custom JSON encoder.""" def default(self, o): """Method converting datetime to string.""" if isinstance(o, datetime.datetime): return o.isoformat() return super().default(o) def is_jwt_identity_authorized(jwt_identity_id): """Check if the given JWT identity UUID is authorized. Args: jwt_identity_id (str): The identity UUID. """ return jwt_identity_id in header.AUTHORIZED_IDENTITIES