from python_pdp_sdk import UnauthenticatedException, UnauthorizedException, ForwardKwargsGetter from owsclient import OwsClient from pydantic import BaseModel from python_pdp_sdk.backends.authorization_backend import PdpAuthorizationBackend from python_pdp_sdk.connectors.ows_pdp.ows_pdp import OwsPdpClient import logging import sys from environs import Env # Load environment variables from .env file env = Env() env.read_env() # Read .env file if it exists logging.basicConfig( level=logging.WARNING, stream=sys.stdout, format='%(asctime)s - %(levelname)s - %(message)s' # Optional: set a custom format ) logger = logging.getLogger(__name__) class MyRequestContext(BaseModel): """MyRequestContext implements what OwsClient wants.""" authorization: str | None = None identity_id: str | None = None profile_id: int | None = None profile_type: str | None = None def main(token: str | None = None, raise_when_unauthorized:bool = False): def my_getter() -> MyRequestContext: """Get a RequestContext containing authorization token.""" return MyRequestContext( authorization=token ) try: ows_client = OwsClient( environment='qa', service_name='pp-1384-uat', request_context_getter=my_getter, ) ows_pdp_client = OwsPdpClient(ows_client=ows_client) pdp_backend = PdpAuthorizationBackend(ows_pdp_client) # Attempt authorization check response = pdp_backend.is_authorized( action="rock", resource_id="123", resource_type="casbah", resource_getter=ForwardKwargsGetter(), tenant={ "tenant_uuid": "7c8b382c-fc37-4179-9115-2165b1a93bed", "tenant_type": "company_brand", }, raise_when_unauthorized=raise_when_unauthorized, ) print(f"Is authorized: {response}") except UnauthenticatedException as e: # ... authentication errors are still raised! logger.warning("Got a 401 error!! '%s'", str(e)) except UnauthorizedException as e: # This is raised when user is not authorized (only if raise_when_unauthorized=True) logger.warning(f"Not authorized: {e}") # Handle by showing "access denied" message except Exception as e: # Other errors print(f"Unexpected error: {e}") if __name__ == '__main__': print("\n --- raise_when_unauthorized=False ---") main() main("bad-token") # Read REAL_TOKEN from environment variable or .env file REAL_TOKEN = env.str('REAL_TOKEN', default=None) if REAL_TOKEN: main(REAL_TOKEN) else: print("\n--- Skipping valid token test (REAL_TOKEN not set) ---") print("\n --- raise_when_unauthorized=True ---") main(raise_when_unauthorized=True) main("bad-token", raise_when_unauthorized=True) if REAL_TOKEN: main(REAL_TOKEN, raise_when_unauthorized=True) else: print("\n--- Skipping valid token test with raise_when_unauthorized=True (REAL_TOKEN not set) ---")