"""Connector for the ows-permissions service.""" from json.decoder import JSONDecodeError from typing import TYPE_CHECKING from werkzeug.exceptions import HTTPException from abacus_common_logic.utils.log import log if TYPE_CHECKING: from owsclient import OwsClient SERVICE = 'ows-permissions' def get_accounts_for_profile( ows_client: 'OwsClient', profile_type: str, profile_id: int ) -> list[int]: """Call ows-permissions to get the list of accounts the profile has access to. Args: ows_client (OwsClient): The OwsClient instance to call ows-permissions. profile_type (str): The type of the profile. profile_id (int): The ID of the profile. Returns: owsresponse.Response: A Response containing the list of account IDs the profile has access to. """ path = f'/admin/profile-type/{profile_type}/profile/{profile_id}/resource/all' permissions_response = ows_client.get(SERVICE, path) if permissions_response.status_code != 200: _raise_http_exception(permissions_response) result = permissions_response.json() account_ids = [item.get('vendorId') for item in result.get('items')] return account_ids def _raise_http_exception(httpx_response): """Raise a HTTPException based on a non-200 HTTPX response. Args: httpx_response (httpx.Response): The non-200 HTTPX response. Raises: HTTPException: The HTTPException with the same status code and error message as the HTTPX response. """ try: message = httpx_response.json() except JSONDecodeError: message = httpx_response.text e = HTTPException() e.code = httpx_response.status_code e.description = message log( 'error', 'Error calling ows-permissions', resources={'status_code': httpx_response.status_code, 'message': message}, ) raise e