from typing import Tuple from aiohttp import web from apollo_utils.core.constants.headers import AUTH_HEADER from apollo_utils.service.exceptions import Unauthorized NO_AUTHORIZE = "_no_authorize" def no_authorize(obj, no_auth_key: str = NO_AUTHORIZE): """View function decorator to skip authorization for.""" setattr(obj, no_auth_key, True) return obj def check_authorization( request: web.Request, api_key: str, is_debug: bool = False, no_auth_view_key: str = NO_AUTHORIZE, auth_header_key: str = AUTH_HEADER, service_routes: Tuple[str] = ( "/api/doc", "/static" ) ): """Check api key if view function is not marked as not_authorized. Raises: Unauthorized: if api key is not set or not matched. """ if getattr(request.match_info.handler, no_auth_view_key, False): return if is_debug: for route in service_routes or []: if request.path.startswith(route): return request_api_key = request.headers.get(auth_header_key) if not request_api_key: raise Unauthorized("Authorization key is not provided.") if request_api_key != api_key: raise Unauthorized("Invalid authorization key.")