from oto import response from product.constants import error from product.models import ows_permissions, product as product_model # All vendors ID ALL_VENDORS_ID = '*' RESOURCE_TYPE_VENDOR = 'Vendor' RESOURCE_TYPE_SUBACCOUNT = 'Subaccount' def check_profile_access( profile_id: int, profile_type: str, vendor_id: int, subaccount_id: int | None = None, ) -> response.Response: """Check if profile has access to any of vendor or subaccount (if defined). Args: profile_id (int): Profile id to verify access for. profile_type (str): Profile type to verify access for. vendor_id (int): Vendor id to verify access to. subaccount_id (int): Subaccount id to verify access to. If passed it checks if profile has access to any of the subaccount or vendor Returns: Response: Response 200 if the check has passed, 403 - failed. """ resources_response = ows_permissions.get_profile_resources( profile_id, profile_type, resource_type=ows_permissions.ResourceType.LABEL ) if not resources_response: return resources_response resources = resources_response.message.get("items", []) for resource in resources: _resource_id = resource.get("id") _resource_type = resource.get("type") if ( (_resource_id == vendor_id or _resource_id == ALL_VENDORS_ID) and _resource_type == RESOURCE_TYPE_VENDOR ) or ( subaccount_id and _resource_id == subaccount_id and _resource_type == RESOURCE_TYPE_SUBACCOUNT ): return response.Response(status=200) return response.create_error_response( code=error.ERROR_CODE_AUTHORIZATION, message=error.ERROR_MESSAGE_FORBIDDEN_PROFILE, status=403, ) def check_profile_access_to_product( profile_id: int, profile_type: str, product_id: int ) -> response.Response: """Check if a profile has access to a product. Args: profile_id (int): Profile id to verify access for. profile_type (str): Profile type to verify access for. product_id (int): Product id to verify access to. Returns: Response: Response 200 if the check has passed, 403 - failed. """ product_response = product_model.get_product_by_id(product_id) if not product_response: return product_response product = product_response.message return check_profile_access( profile_id, profile_type, product.get("vendor_id"), product.get("subaccount_id") )