(20250704) - Created Oauth Authentication for google places api with all files
This commit is contained in:
@@ -0,0 +1,266 @@
|
||||
"""
|
||||
|
||||
AUTHOR:
|
||||
|
||||
Omkar Khandare
|
||||
|
||||
DATE:
|
||||
|
||||
Friday, 27th Jun., 2025.
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To handle ecommerce authentication.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
N/A
|
||||
|
||||
DOWNLOADS:
|
||||
|
||||
N/A
|
||||
|
||||
"""
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** IMPORT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# To make sibling directories accessible for imports:
|
||||
import sys
|
||||
sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# My async utils:
|
||||
from utils_v2.string import json
|
||||
from utils_v2.date_time import date_time
|
||||
from utils_v2.database.async_mysql_v2 import AsyncMySQL
|
||||
from utils_v2.database.async_mongo_v2 import AsyncMongo
|
||||
from utils_v2.cache.async_redis_cache_v2 import AsyncRedisCache
|
||||
|
||||
# Controllers:
|
||||
from controllers_v2.core.software import CoreSoftwareController
|
||||
|
||||
# To make very controlled API calls:
|
||||
from utils_v2.rest.controllers.async_base import AsyncREST
|
||||
from utils_v2.rest.models.api_call import ApiResponse
|
||||
|
||||
# Models:
|
||||
# Models:
|
||||
from models.core.user import CoreUserInfoModel
|
||||
from models.core.auth_token import CoreAuthTokenModel
|
||||
from models.core.user import CoreUserInfoModel
|
||||
from models.api.message.mail.oauth import (
|
||||
OAuthMailAuthorizationRequestHeaders,
|
||||
OAuthMailAuthorizationRequestData
|
||||
)
|
||||
from models.message.mail.oauth import OAuthMailGetAuthorizationURLResponse, OAuthMailHandleCallbackResponse
|
||||
from models.core.message import CoreMessageModel
|
||||
# To make HTTP requests:
|
||||
import httpx
|
||||
|
||||
# to work with MongoDB:
|
||||
from bson.objectid import ObjectId
|
||||
|
||||
# Mail Client(s):
|
||||
from utils_v2.goog.controllers.places.places_client import AsyncPlacesClient
|
||||
|
||||
# To make abstract classes:
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MACROS / ONE-TIME INIT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** VARIABLES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** FUNCTIONS ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** CLASSES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class GooglePlacesController(CoreSoftwareController, ABC):
|
||||
|
||||
# ┏┓┓ ┓┏
|
||||
# ┃ ┃┏┓┏┏ ┃┃┏┓┏┓┏
|
||||
# ┗┛┗┗┻┛┛ ┗┛┗┻┛ ┛
|
||||
|
||||
SERVICE_TYPE = "software"
|
||||
|
||||
# ┏┓
|
||||
# ┃ ┏┓┏┓┏╋┏┓┓┏┏╋┏┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┛ ┗┻┗┗┗┛┛
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache: AsyncRedisCache = None,
|
||||
http_client: httpx.AsyncClient = None,
|
||||
alert_url: str = None,
|
||||
base_filter: dict = None,
|
||||
debug: bool = True,
|
||||
debug_prefix: str = "Google Places (C) | ",
|
||||
debug_only_errors: bool = True
|
||||
):
|
||||
|
||||
"""
|
||||
This is the foundational controller for generate an authentication key for ecommerce integration,
|
||||
To Validate user from ecommerce webhooks
|
||||
:param cache: The object to use for caching results from database calls.
|
||||
:param http_client: The HTTP client to use to make REST-ful API calls.
|
||||
:param base_filter: The basic filter that will be applied to all fetching/updating queries. WARNING: THE BASE
|
||||
FILTER WILL ALWAYS BE APPLIED AUTOMATICALLY. SET THIS UP WISELY.
|
||||
:param debug: Whether, or not, you would like to print debugging messages:
|
||||
:param debug_prefix: The prefix to print with the debugging messages.
|
||||
:param debug_only_errors: Whether you would like to print only error messages or all messages.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
# Prepare the combined base filter:
|
||||
shopify_filter = {}
|
||||
for k, v in (base_filter or {}).items(): shopify_filter[k] = v
|
||||
shopify_filter["serviceType"] = self.SERVICE_TYPE
|
||||
|
||||
# Invoke the parent's constructor:
|
||||
CoreSoftwareController.__init__(
|
||||
self,
|
||||
cache = cache,
|
||||
alert_url = alert_url,
|
||||
http_client = http_client,
|
||||
base_filter = shopify_filter,
|
||||
debug = debug,
|
||||
debug_prefix = debug_prefix,
|
||||
debug_only_errors = debug_only_errors
|
||||
)
|
||||
|
||||
# Init a variable in a parent:
|
||||
self._service_type = self.SERVICE_TYPE
|
||||
|
||||
# For controlled REST-ful calls:
|
||||
self._rest = AsyncREST(
|
||||
http_client = http_client,
|
||||
debug = debug,
|
||||
debug_prefix = debug_prefix,
|
||||
debug_only_errors = debug_only_errors
|
||||
)
|
||||
|
||||
# ┏┓┏┓ ┓ ┏┓ ┏┓
|
||||
# ┃┃┣┫┓┏╋┣┓┏┛ ┃┫
|
||||
# ┗┛┛┗┗┻┗┛┗┗━•┗┛
|
||||
|
||||
@abstractmethod
|
||||
async def get_authorization_url(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
mail_client: AsyncPlacesClient,
|
||||
user_info: CoreUserInfoModel,
|
||||
inbound_data: OAuthMailAuthorizationRequestData,
|
||||
session_token: str
|
||||
) -> OAuthMailGetAuthorizationURLResponse:
|
||||
"""
|
||||
To accept an incoming request for mail integration and provide a URL that the user can use to authorize your
|
||||
service to access his mail inbox.
|
||||
:param sql_conn: The database connection to use to perform this task.
|
||||
:param mongo_data_conn: The database connection to use to perform this task.
|
||||
:param mail_client: The instance of the third-party mail client that will be used to get the URL.
|
||||
:param user_info: The information about your user who is trying to use this system.
|
||||
:param inbound_data: The data that came in with the request (API call).
|
||||
:param session_token: The session token of the user.
|
||||
:return: A structure response with details about the URL generation process.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def handle_authorization_callback(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
mail_client: AsyncPlacesClient,
|
||||
request_url: str,
|
||||
inbound_data: dict,
|
||||
session_token: str = None
|
||||
) -> OAuthMailHandleCallbackResponse:
|
||||
"""
|
||||
To handle the authorization callback for the mail client. The user may grant or deny authorization.
|
||||
:param sql_conn: The database connection to use to perform this task.
|
||||
:param mongo_data_conn: The database connection to use to perform this task.
|
||||
:param mail_client: The instance of the third-party mail client that will be used to get the URL.
|
||||
:param request_url: The full callback URL invoked by the third-party client.
|
||||
:param inbound_data: The data that came in with the request (API call).
|
||||
:param session_token: The session token of the user. It is expected that this will be null in all cases.
|
||||
:return: A structured response of the process of handling the mail callback.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def refresh_authorization(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
mail_client: AsyncPlacesClient,
|
||||
http_client: httpx.AsyncClient,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
force_refresh: bool = False,
|
||||
session_token: str = None
|
||||
) -> CoreAuthTokenModel:
|
||||
"""
|
||||
To refresh the third-party client's access/authorization token(s) before use.
|
||||
:param sql_conn: The database connection to use when storing the refreshed tokens.
|
||||
:param mongo_data_conn: The database connection to use when storing the refreshed tokens.
|
||||
:param mail_client: The connection of the third-party mail client.
|
||||
:param http_client: The HTTP client to use to make the token refresh request.
|
||||
:param auth_token: The auth-token model of the existing integration. This may get updated if a refresh is needed
|
||||
(or forced).
|
||||
:param force_refresh: Whether, or not, you would like to force a refresh even if the token hasn't expired yet.
|
||||
:param session_token: The session token of the user. This will be null if this method is invoked by a cron
|
||||
script in the background. Needed only to identify the user in case of a failure to send a timely alert.
|
||||
:return: The same auth-token model instance, but maybe with updated tokens.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MAIN PROGRAM ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
pass
|
||||
@@ -0,0 +1,458 @@
|
||||
"""
|
||||
|
||||
AUTHOR:
|
||||
|
||||
Khushal P Soonderji
|
||||
|
||||
DATE:
|
||||
|
||||
Thursday, 16th Jan., 2025.
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To handle all mail-related behaviour for Gmail from one place.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
N/A
|
||||
|
||||
DOWNLOADS:
|
||||
|
||||
N/A
|
||||
|
||||
"""
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** IMPORT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# To make sibling directories accessible for imports:
|
||||
import sys
|
||||
sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# My async utils:
|
||||
from utils_v2.string import json
|
||||
from utils_v2.mail import mail_parser
|
||||
from utils_v2.date_time import date_time
|
||||
from utils_v2.database.async_mysql_v2 import AsyncMySQL
|
||||
from utils_v2.database.async_mongo_v2 import AsyncMongo
|
||||
from utils_v2.cache.async_redis_cache_v2 import AsyncRedisCache
|
||||
from utils_v2.logging.context import AsyncLoggerContext
|
||||
|
||||
# Controllers:
|
||||
from controllers_v2.software.google_places.base import GooglePlacesController
|
||||
|
||||
# Models:
|
||||
from models.core.user import CoreUserInfoModel
|
||||
from models.core.auth_token import CoreAuthTokenModel
|
||||
from models.core.message import CoreMessageModel
|
||||
from models.api.software.places.oauth import (
|
||||
OAuthPlacesAuthorizationRequestHeaders,
|
||||
OAuthPlacesAuthorizationRequestData
|
||||
)
|
||||
from models.software.places.oauth import OAuthPlacesGetAuthorizationURLResponse, OAuthPlacesHandleCallbackResponse
|
||||
|
||||
# Mail Client(s):
|
||||
from utils_v2.goog.controllers.places.places_client import AsyncPlacesClient, SCOPES_PLACES_FULL
|
||||
from utils_v2.goog.models.auth_tokens import GoogleAuthTokens
|
||||
|
||||
# Shared:
|
||||
from shared import constants
|
||||
|
||||
# To work with datatypes:
|
||||
from typing import List, Any
|
||||
|
||||
# To work with MongoDB:
|
||||
from bson import ObjectId
|
||||
from pymongo import InsertOne, UpdateOne, ReplaceOne
|
||||
|
||||
# To work with LLMs:
|
||||
from controllers.core.ai.llm import CoreLLMController
|
||||
from models.core.ai.llm import LLMInput, LLMOutput
|
||||
|
||||
# To make HTTP requests:
|
||||
import httpx
|
||||
|
||||
# To work with date and time:
|
||||
import datetime
|
||||
|
||||
# For asynchronous activities:
|
||||
import asyncio
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MACROS / ONE-TIME INIT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** VARIABLES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** FUNCTIONS ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** CLASSES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class PlacesController(GooglePlacesController):
|
||||
|
||||
# ┏┓┓ ┓┏
|
||||
# ┃ ┃┏┓┏┏ ┃┃┏┓┏┓┏
|
||||
# ┗┛┗┗┻┛┛ ┗┛┗┻┛ ┛
|
||||
|
||||
CLIENT_NAME = "googlePlaces"
|
||||
|
||||
# ┏┓
|
||||
# ┃ ┏┓┏┓┏╋┏┓┓┏┏╋┏┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┛ ┗┻┗┗┗┛┛
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache: AsyncRedisCache = None,
|
||||
http_client: httpx.AsyncClient = None,
|
||||
alert_url: str = None,
|
||||
debug: bool = True,
|
||||
debug_prefix: str = "G Places (C) | ",
|
||||
debug_only_errors: bool = True
|
||||
):
|
||||
|
||||
"""
|
||||
This is the controller specifically built for Gmail's services. It is built on top of the base mail controller.
|
||||
:param cache: The object to use for caching results from database calls.
|
||||
:param http_client: The HTTP client
|
||||
:param debug: Whether, or not, you would like to print debugging messages:
|
||||
:param debug_prefix: The prefix to print with the debugging messages.
|
||||
:param debug_only_errors: Whether you would like to print only error messages or all messages.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
# Invoke the parent's constructor:
|
||||
super().__init__(
|
||||
cache = cache,
|
||||
alert_url = alert_url,
|
||||
http_client = http_client,
|
||||
base_filter = {"client": self.CLIENT_NAME},
|
||||
debug = debug,
|
||||
debug_prefix = debug_prefix,
|
||||
debug_only_errors = debug_only_errors
|
||||
)
|
||||
|
||||
# Init a variable in a parent:
|
||||
self._client = self.CLIENT_NAME
|
||||
|
||||
# ┏┓┏┓ ┓ ┏┓ ┏┓
|
||||
# ┃┃┣┫┓┏╋┣┓┏┛ ┃┫
|
||||
# ┗┛┛┗┗┻┗┛┗┗━•┗┛
|
||||
|
||||
async def get_authorization_url(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
client: AsyncPlacesClient,
|
||||
user_info: CoreUserInfoModel,
|
||||
inbound_data: OAuthPlacesAuthorizationRequestData,
|
||||
session_token: str
|
||||
) -> OAuthPlacesGetAuthorizationURLResponse:
|
||||
|
||||
"""
|
||||
To accept an incoming request for mail integration and provide a URL that the user can use to authorize your
|
||||
service to access his mail inbox.
|
||||
:param sql_conn: The database connection to use to perform this task.
|
||||
:param mongo_data_conn: The database connection to use to perform this task.
|
||||
:param client: The instance of the third-party mail client that will be used to get the URL.
|
||||
:param user_info: The information about your user who is trying to use this system.
|
||||
:param inbound_data: The data that came in with the request (API call).
|
||||
:param session_token: The session token of the user.
|
||||
:return: A structure response with details about the URL generation process.
|
||||
"""
|
||||
|
||||
# Start by assuming failure:
|
||||
response = OAuthPlacesGetAuthorizationURLResponse()
|
||||
|
||||
# First, we create/update a record for this integration request:
|
||||
token_key = await self.generate_token_key(
|
||||
sql_conn = sql_conn,
|
||||
mongo_data_conn = mongo_data_conn,
|
||||
auth_token = CoreAuthTokenModel(
|
||||
serviceType = "software",
|
||||
client = inbound_data.client,
|
||||
authType = "oauth",
|
||||
user = user_info,
|
||||
clientUserId = {"email": inbound_data.mailId},
|
||||
status = "pending",
|
||||
# syncFreq = inbound_data.syncFreq,
|
||||
),
|
||||
token_notes = {
|
||||
"email": inbound_data.mailId
|
||||
},
|
||||
display_name = inbound_data.mailId,
|
||||
display_picture = None,
|
||||
session_token = session_token
|
||||
)
|
||||
|
||||
# If generating the token key fails:
|
||||
if token_key is None:
|
||||
response.message = "Failed to generate token key."
|
||||
return response
|
||||
|
||||
# Now we create the URL:
|
||||
response.url = await client.get_authorization_url(
|
||||
scopes = SCOPES_PLACES_FULL,
|
||||
state = str(token_key),
|
||||
access_type = "offline",
|
||||
approval_prompt = "force",
|
||||
include_granted_scopes = "true",
|
||||
user_email = inbound_data.mailId
|
||||
)
|
||||
response.success = True
|
||||
response.message = "Please use the URL to integrate your Places account."
|
||||
|
||||
# Done here:
|
||||
return response
|
||||
|
||||
async def handle_authorization_callback(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
client: AsyncPlacesClient,
|
||||
request_url: str,
|
||||
inbound_data: dict,
|
||||
session_token: str = None
|
||||
) -> OAuthPlacesHandleCallbackResponse:
|
||||
|
||||
"""
|
||||
To handle the authorization callback for the mail client. The user may grant or deny authorization.
|
||||
:param sql_conn: The database connection to use to perform this task.
|
||||
:param mongo_data_conn: The database connection to use to perform this task.
|
||||
:param client: The instance of the third-party mail client that will be used to get the URL.
|
||||
:param request_url: The full callback URL invoked by the third-party client.
|
||||
:param inbound_data: The data that came in with the request (API call).
|
||||
:param session_token: The session token of the user. It is expected that this will be null in all cases.
|
||||
:return: A structured response of the process of handling the mail callback.
|
||||
"""
|
||||
|
||||
# Start by assuming failure:
|
||||
response = OAuthPlacesHandleCallbackResponse()
|
||||
|
||||
# In case the user denied access:
|
||||
if inbound_data.get("error") == "access_denied":
|
||||
response.action = "denied"
|
||||
response.message = "The user denied authorization."
|
||||
return response
|
||||
|
||||
# Otherwise we know that the user authorized access:
|
||||
else:
|
||||
response.action = "authorized"
|
||||
response.message = "The user has given authorization."
|
||||
|
||||
# We fetch the auth-token associated with this authorization loop:
|
||||
auth_token = await self.get_token_from_key(
|
||||
mongo_data_conn = mongo_data_conn,
|
||||
token_key = inbound_data["state"],
|
||||
must_be_active = False
|
||||
)
|
||||
if not auth_token:
|
||||
response.action = "unknown"
|
||||
response.message = "Failed to load the auth-token for this flow."
|
||||
return response
|
||||
|
||||
# Generate the tokens from the callback. Google sends all the needed params in the callback as the URL's query
|
||||
# params. We can simply use the exact URL that was hit to generate the tokens. In Quart (and Flask) this can be
|
||||
# achieved by 'request.url' like this:
|
||||
google_tokens = await client.get_authorization_tokens(
|
||||
redirect_url = request_url,
|
||||
scopes = None
|
||||
)
|
||||
|
||||
# If no tokens were generated:
|
||||
if not google_tokens:
|
||||
response.message = "Failed to get access token(s) from Places."
|
||||
return response
|
||||
|
||||
# Try getting the user's profile from Gmail:
|
||||
user_profile = await client.get_user_profile(tokens=google_tokens)
|
||||
if user_profile.success:
|
||||
google_tokens.email = user_profile.data["emailAddress"]
|
||||
google_tokens.displayName = user_profile.data["displayName"]
|
||||
google_tokens.displayPictureUrl = user_profile.data["displayPictureUrl"]
|
||||
else:
|
||||
response.message = "Failed to get the user's profile from Gmail."
|
||||
return response
|
||||
|
||||
# We confirm if the expected email account and the one that gave authorization are the same:
|
||||
if auth_token.clientUserId["email"] != str(google_tokens.email):
|
||||
response.message = (
|
||||
f"We were expecting authorization from '{auth_token.clientUserId['email']}', "
|
||||
f"but got authorization from '{google_tokens.email}' instead."
|
||||
)
|
||||
return response
|
||||
|
||||
# Now that we have passed the check,
|
||||
# we save the tokens to the database:
|
||||
auth_token.clientUserId = google_tokens.client_user_id
|
||||
auth_token.token = google_tokens.model_dump()
|
||||
auth_token.status = "active"
|
||||
tokens_saved = await self.set_token(
|
||||
sql_conn = sql_conn,
|
||||
mongo_data_conn = mongo_data_conn,
|
||||
token_key = inbound_data["state"],
|
||||
auth_token = auth_token,
|
||||
token_notes = {
|
||||
"email": google_tokens.email
|
||||
},
|
||||
display_name = google_tokens.displayName,
|
||||
display_picture = google_tokens.displayPictureUrl,
|
||||
session_token = session_token
|
||||
)
|
||||
|
||||
# Note down the final result:
|
||||
if tokens_saved:
|
||||
response.success = True
|
||||
response.message = "Authorization flow completed successfully."
|
||||
else: response.message = "Failed to save the token(s)."
|
||||
|
||||
# Done here:
|
||||
return response
|
||||
|
||||
async def refresh_authorization(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
mail_client: AsyncPlacesClient,
|
||||
http_client: httpx.AsyncClient,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
force_refresh: bool = False,
|
||||
session_token: str = None
|
||||
) -> CoreAuthTokenModel:
|
||||
"""
|
||||
To refresh the third-party client's access/authorization token(s) before use.
|
||||
:param sql_conn: The database connection to use when storing the refreshed tokens.
|
||||
:param mongo_data_conn: The database connection to use when storing the refreshed tokens.
|
||||
:param mail_client: The connection of the third-party mail client.
|
||||
:param http_client: The HTTP client to use to make the token refresh request.
|
||||
:param auth_token: The auth-token model of the existing integration. This may get updated if a refresh is needed
|
||||
(or forced).
|
||||
:param force_refresh: Whether, or not, you would like to force a refresh even if the token hasn't expired yet.
|
||||
:param session_token: The session token of the user. This will be null if this method is invoked by a cron
|
||||
script in the background. Needed only to identify the user in case of a failure to send a timely alert.
|
||||
:return: The same auth-token model instance, but maybe with updated tokens.
|
||||
"""
|
||||
|
||||
raise NotImplementedError
|
||||
|
||||
# @AsyncLoggerContext.log_it(
|
||||
# api_version = "1.0.0",
|
||||
# project = constants.PROJECT_NAME,
|
||||
# log_type = constants.MODULE_NAME,
|
||||
# operation = "gmailTokRefresh",
|
||||
# log_input = False,
|
||||
# log_output = False,
|
||||
# sensitive_keys = ["session_token"]
|
||||
# )
|
||||
# async def refresh_authorization(
|
||||
# self,
|
||||
# sql_conn: AsyncMySQL,
|
||||
# mongo_data_conn: AsyncMongo,
|
||||
# mail_client: AsyncGmailClient,
|
||||
# http_client: httpx.AsyncClient,
|
||||
# auth_token: CoreAuthTokenModel,
|
||||
# force_refresh: bool = False,
|
||||
# session_token: str = None
|
||||
# ) -> CoreAuthTokenModel:
|
||||
#
|
||||
# """
|
||||
# To refresh the third-party client's access/authorization token(s) before use.
|
||||
# :param sql_conn: The database connection to use when storing the refreshed tokens.
|
||||
# :param mongo_data_conn: The database connection to use when storing the refreshed tokens.
|
||||
# :param mail_client: The connection of the third-party mail client.
|
||||
# :param http_client: The HTTP client to use to make the token refresh request.
|
||||
# :param auth_token: The auth-token model of the existing integration. This may get updated if a refresh is needed
|
||||
# (or forced).
|
||||
# :param force_refresh: Whether, or not, you would like to force a refresh even if the token hasn't expired yet.
|
||||
# :param session_token: The session token of the user. This will be null if this method is invoked by a cron
|
||||
# script in the background. Needed only to identify the user in case of a failure to send a timely alert.
|
||||
# :return: The same auth-token model instance, but maybe with updated tokens.
|
||||
# """
|
||||
#
|
||||
# # Extract the client's tokens from the full token payload given by the database:
|
||||
# google_tokens = GoogleAuthTokens(**auth_token.token)
|
||||
#
|
||||
# # Refresh the tokens (if/as needed):
|
||||
# tokens_refreshed = await google_tokens.arefresh(
|
||||
# http_client = http_client,
|
||||
# client_id = mail_client.client_id,
|
||||
# client_secret = mail_client.client_secret,
|
||||
# force_refresh = force_refresh
|
||||
# )
|
||||
#
|
||||
# # If the tokens were refreshed:
|
||||
# if tokens_refreshed:
|
||||
#
|
||||
# # Try getting the user's profile from Gmail:
|
||||
# user_profile = await mail_client.get_user_profile(tokens = google_tokens)
|
||||
# if user_profile.success:
|
||||
# google_tokens.email = user_profile.data["emailAddress"]
|
||||
# google_tokens.displayName = user_profile.data["displayName"]
|
||||
# google_tokens.displayPictureUrl = user_profile.data["displayPictureUrl"]
|
||||
#
|
||||
# # Update the existing auth-token model:
|
||||
# auth_token.token = google_tokens.model_dump()
|
||||
# auth_token.lastRefreshTs = date_time.get_current_utc_date_time(as_string = True)
|
||||
#
|
||||
# # Try to update the record in the database:
|
||||
# await self.set_token(
|
||||
# sql_conn = sql_conn,
|
||||
# mongo_data_conn = mongo_data_conn,
|
||||
# token_key = auth_token.key,
|
||||
# auth_token = auth_token,
|
||||
# token_notes = {
|
||||
# "email": auth_token.clientUserId.get("email"),
|
||||
# "client": auth_token.client
|
||||
# },
|
||||
# display_name = google_tokens.email,
|
||||
# display_picture = google_tokens.displayPictureUrl,
|
||||
# session_token = session_token,
|
||||
# )
|
||||
#
|
||||
# # Whether refreshed, or not, return the auth-token model:
|
||||
# return auth_token
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MAIN PROGRAM ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
pass
|
||||
Reference in New Issue
Block a user