""" AUTHOR: Khushal P Soonderji DATE: Thursday, 16th Jan., 2025. OBJECTIVE: To receive callbacks (webhooks). REFERENCES: N/A DOWNLOADS: N/A NOTES: N/A """ # ***************************************************************************************************************** # ***** **** # *** IMPORT *** # ***** **** # ***************************************************************************************************************** # To make sibling directories accessible for imports: import sys sys.path.append(".") sys.path.append("..") # For using Quart: from quart import Blueprint, current_app, g, request, render_template # My utils: from utils_v2.string import json from utils_v2.logging.context import AsyncLoggerContext from utils_v2.api.codes import StatusCodes, HttpCodes from utils_v2.api.response import ResponseModel from utils_v2.api.async_quart import ( set_api_version, read_input, get_session_info, log_request_to_mongo, log_chain_to_mongo, should_not_be_under_maintenance, only_whitelisted_ips, limit_rate, validate_input, handle_cancelled_request ) # GMail-related utils: from utils_v2.goog.controllers.gmail.gmail_client import SCOPES_GMAIL_MAIL_MANAGEMENT # Data Models: from models.core.auth_token import CoreAuthTokenModel from models.software.places.oauth import OAuthPlacesHandleCallbackResponse # Common: from shared import constants # For asynchronous activities: import asyncio # ***************************************************************************************************************** # ***** **** # *** MACROS / ONE-TIME INIT *** # ***** **** # ***************************************************************************************************************** # Related to Quart: places_oauth_callback_bp = Blueprint("places_cb", __name__) # ***************************************************************************************************************** # ***** **** # *** VARIABLES *** # ***** **** # ***************************************************************************************************************** # --- Nothing Yet # ***************************************************************************************************************** # ***** **** # *** FUNCTIONS *** # ***** **** # ***************************************************************************************************************** @places_oauth_callback_bp.record_once def init(blueprint_setup_state): # This gets called when the blueprint is registered. # Consider this to be a one-time setup for the whole blueprint: pass # --------------------------------------------------------------------------------------------------------------------- @AsyncLoggerContext.log_it( api_version = "1.0.0", project = constants.PROJECT_NAME, log_type = constants.MODULE_NAME, operation = "googleplacesOAuthClbk", log_input = 2, log_output = 1, sensitive_keys = ["sessionToken", "X-Session-Token"] ) async def handle_places_callback( client_controller, client_connector, request_url: str, inbound_data: dict, ) -> OAuthPlacesHandleCallbackResponse: """ This function has been kept separate only for convenience of logging. :param client_controller: The mail controller instance. :param client_connector: The instance of the third-party client to send to the mail controller. :param request_url: The full request URL that came in. :param inbound_data: The data received in the request. :return: The client's response. """ return await client_controller.handle_authorization_callback( sql_conn = current_app.sql_writer, mongo_data_conn = current_app.data_mongo, client = client_connector, request_url = request_url, inbound_data = inbound_data, session_token = None ) # --------------------------------------------------------------------------------------------------------------------- @places_oauth_callback_bp.route("/callback/", methods = ["POST", "GET"]) @set_api_version(api_version = "1.0.0") @read_input(sanitize_headers = False, sanitize_data = False) @log_request_to_mongo( attr_name = "logs_mongo", project = constants.PROJECT_NAME, log_type = constants.MODULE_NAME, operation = "googlePlacesOAuthClbkApi", log_input = True, log_output = True, sensitive_keys = None ) @log_chain_to_mongo(attr_name = "logs_mongo") @should_not_be_under_maintenance(attr_name = "is_under_maintenance") @handle_cancelled_request() async def places_auth_callback( places_client: str = None, inbound_headers: dict = None, inbound_data: dict = None, inbound_files: dict = None, **kwargs ): """ This is the callback received when authorizing someone's mail client. :param places_client: The mail company/brand that you want the authorization from. :param inbound_headers: auto-extracted by the decorators. :param inbound_data: auto-extracted by the decorators. :param inbound_files: auto-extracted by the decorators. :param kwargs: Any number of extra inputs supplied by the decorators. :return: A standard response structure. """ # ┳┓ ┳┳┓ •┓ ┏┓┓• # ┣┫┏┓┓┏╋┏┓ ╋┏┓ ┃┃┃┏┓┓┃ ┃ ┃┓┏┓┏┓╋ # ┛┗┗┛┗┻┗┗ ┗┗┛ ┛ ┗┗┻┗┗ ┗┛┗┗┗ ┛┗┗ # Start by assuming failure: client_controller = None client_connector = None client_response = None exception = None places_client = { "googleplaces": "googlePlaces" }.get(places_client.lower(), places_client) # Figure out the client connector: match places_client: case "googlePlaces": client_controller, client_connector = current_app.places_controller, current_app.google_places_client case _: client_controller, client_connector = None, None # Invoke the mail client: if client_controller is not None and client_connector is not None: try: client_response = await handle_places_callback( client_controller, client_connector, request_url = request.url, inbound_data = inbound_data ) except Exception as excp: exception = excp # ┳┓ # ┣┫┏┓┏┏┓┏┓┏┓┏┏┓ # ┛┗┗ ┛┣┛┗┛┛┗┛┗ # ┛ # Make the mail client a label: places_client = { "googlePlaces": "Google Places" }.get(places_client, places_client) # If there was some exception: if exception: return await render_template( "/software/places/oauth/oauth_failure_v2.html", client = places_client, failure_hint = ( f"An internal server error occurred. " f"Please use log-id '{kwargs.get('log_id')}' to check with the support team." ) ) # For an invalid client: if client_controller is None or client_connector is None: return await render_template( "/software/places/oauth/oauth_failure_v2.html", client = places_client, failure_hint = ( f"Invalid client '{places_client}' selected. " f"Please use log-id '{kwargs.get('log_id')}' to check with the support team." ) ) # For a valid client whose authorization was denied/cancelled: if client_response.action in ["denied", "cancelled"]: return await render_template( "/software/places/oauth/oauth_cancelled_v2.html", client = places_client ) # For successful authorization: if client_response.success: return await render_template( "/software/places/oauth/oauth_success_v2.html", client = places_client ) # For failed authorization: return await render_template( "/software/places/oauth/oauth_failure_v2.html", client = places_client, failure_hint = ( f"{client_response.message} " f"Please use log-id '{kwargs.get('log_id')}' to check with the support team.".strip() ) ) # ***************************************************************************************************************** # ***** **** # *** MAIN PROGRAM *** # ***** **** # ***************************************************************************************************************** if __name__ == "__main__": pass