(20241209) Standardizing the data models for the database. Started with mail authentication.

This commit is contained in:
2024-12-09 12:05:12 +05:30
parent 30088dcea4
commit e2c9200941
11 changed files with 262 additions and 244 deletions
+47 -61
View File
@@ -6,7 +6,8 @@
DATE:
Monday, 2nd Dec., 2024
ORIGINAL: Monday, 2nd Dec., 2024
UPGRADE: Monday, 9th Dec., 2024
OBJECTIVE:
@@ -44,6 +45,9 @@ from utils_v2.database.async_mongo_v2 import AsyncMongo
# Base model:
from models.behaviour.base import BaseModel
# Data models:
from models.data.core.auth_token import CoreAuthTokenModel
# To work with MongoDB:
from bson import ObjectId
@@ -99,12 +103,7 @@ class MailOAuthModel(BaseModel):
self,
db_conn: AsyncMySQL,
mongo_conn: AsyncMongo,
user_info: dict,
client_user_id: dict,
auth: dict,
service_client: Literal["gmail"],
auth_type: Literal["oauth"],
sync_freq: Literal[60, 300, 900] = 300,
auth_token: CoreAuthTokenModel,
session_token: str = None
) -> ObjectId:
@@ -113,13 +112,7 @@ class MailOAuthModel(BaseModel):
user requests an authorization URL to link your service to another service (like GMail).
:param db_conn: The database connection (MariaDB) to use to perform the action.
:param mongo_conn: The database connection (MongoDB) to use to perform the action.
:param user_info: The dictionary that has the user's session information.
:param client_user_id: The way the third-party client recognizes your user.
:param auth: The authentication details of the account.
:param service_client: The name of the company or brand that is providing this service that is being integrated.
:param auth_type: To identify the type of authentication being done here. This could indicate simple password
authentication, more advance OAuth2.0 authentication, etc.
:param sync_freq: The time interval in which mails need to be sync'd. Specify this in seconds.
:param auth_token: An instance of the core auth-token model that holds data in the database.
:param session_token: The session token of the user who requested this service.
:return: An ObjectId to later store the granted tokens.
"""
@@ -127,35 +120,36 @@ class MailOAuthModel(BaseModel):
# Note down the timestamp at which this event occurred:
request_ts = date_time.get_current_utc_date_time(as_string = False)
# Get the identifier from the database:
# Get the identifier from the database.
# BE CAREFUL WITH THE KEYS HERE, THEY SHOULD MATCH THE FIELDS OF THE CORE AUTH-TOKEN MODEL:
mongo_json = await mongo_conn.find_one_and_update(
collection = MailOAuthModel.AUTH_COLLECTION,
filter = mongo_conn.dict_to_dot_notation({
"serviceType": "email",
"user": {
"entityId": user_info["entityId"],
"billingAccountId": user_info["billingAccountId"]
"entityId": auth_token.user.entityId,
"billingAccountId": auth_token.user.billingAccountId
},
"clientUserId": client_user_id
"clientUserId": auth_token.clientUserId
}),
update = {
"$set": {
"lastRequestTs": request_ts,
"status": "active",
"syncFreq": max(sync_freq, 60)
"status": auth_token.status,
"syncFreq": max(auth_token.syncFreq, 60)
},
"$setOnInsert": {
"version": "1.1.1",
"serviceType": "email",
"client": service_client,
"authType": auth_type,
"user": user_info,
"clientUserId": client_user_id,
"auth": auth,
"token": None,
"firstRefreshTs": None,
"lastRefreshTs": None,
"firstRequestTs": request_ts,
"version": auth_token.version,
"serviceType": auth_token.serviceType,
"client": auth_token.client,
"authType": auth_token.authType,
"user": auth_token.user.model_dump(),
"clientUserId": auth_token.clientUserId,
"auth": auth_token.auth,
"token": auth_token.token,
"firstRefreshTs": auth_token.firstRefreshTs,
"lastRefreshTs": auth_token.lastRefreshTs,
"firstRequestTs": auth_token.firstRequestTs,
}
},
projection = {
@@ -172,15 +166,15 @@ class MailOAuthModel(BaseModel):
db_conn = db_conn,
proc_name = "entity_integration_save",
proc_args = (
user_info["entityId"], # ............................................ 'p_entity_id'
service_client, # ................................................... 'p_provider'
auth_token.user.entityId, # ......................................... 'p_entity_id'
auth_token.client, # ................................................ 'p_provider'
"Pending", # ........................................................ 'p_current_status'
"Auth Requested", # ................................................. 'p_last_action'
None, # ............................................................. 'p_display_name'
None, # ............................................................. 'p_display_picture'
str(mongo_json["_id"]), # ........................................... 'p_token_id'
json.to_string(python_data = {"email": None}, no_space = True), # ... 'p_notes'
user_info["userId"] # ............................................... 'p_created_by'
auth_token.user.userId # ............................................ 'p_created_by'
),
session_token = session_token
)
@@ -193,8 +187,7 @@ class MailOAuthModel(BaseModel):
db_conn: AsyncMySQL,
mongo_conn: AsyncMongo,
token_id: ObjectId | str,
client_user_id: dict,
token: dict,
auth_token: CoreAuthTokenModel,
session_token: str = None
) -> bool:
@@ -205,9 +198,7 @@ class MailOAuthModel(BaseModel):
:param db_conn: The database connection (MariaDB) to use to perform the action.
:param mongo_conn: The database connection (MongoDB) to use to perform the action.
:param token_id: The identifier granted by the 'get_token_id' method.
:param client_user_id: The way the third-party client recognizes your user. These details should match the
details furnished while requesting the authorization through 'get_token_id' method.
:param token: The token granted by the third-party service.
:param auth_token: The actual auth/token data to be saved to the database.
:param session_token: The session token of the user who requested this service.
:return: True if saved, False if failed.
"""
@@ -218,17 +209,18 @@ class MailOAuthModel(BaseModel):
# Note down the timestamp at which this event occurred:
request_ts = date_time.get_current_utc_date_time(as_string = False)
# Save the token to MongoDB:
# Save the token to MongoDB.
# BE CAREFUL WITH THE KEYS HERE, THEY SHOULD MATCH THE FIELDS OF THE CORE AUTH-TOKEN MODEL:
mongo_json = await mongo_conn.find_one_and_update(
collection = MailOAuthModel.AUTH_COLLECTION,
filter = mongo_conn.dict_to_dot_notation({
"_id": ObjectId(token_id),
"clientUserId": client_user_id
"clientUserId": auth_token.clientUserId
}),
update = [{
"$set": {
"token": token,
"status": "active",
"token": auth_token.token,
"status": auth_token.status,
"lastRefreshTs": request_ts,
"firstRefreshTs": {
"$cond": {
@@ -252,9 +244,9 @@ class MailOAuthModel(BaseModel):
# Tell MariaDB that the token was saved:
if mongo_json is not None:
token_notes = {
"email": token["email"],
"displayName": token.get("displayName"),
"displayPictureUrl": token.get("displayPictureUrl"),
"email": auth_token.token["email"],
"displayName": auth_token.token.get("displayName"),
"displayPictureUrl": auth_token.token.get("displayPictureUrl"),
}
db_json = await self.call_procedure(
db_conn = db_conn,
@@ -264,11 +256,11 @@ class MailOAuthModel(BaseModel):
mongo_json["client"], # ......................................... 'p_provider'
"Active", # ..................................................... 'p_current_status'
"Auth Granted", # ............................................... 'p_last_action'
token["displayName"], # ......................................... 'p_display_name'
token["displayPictureUrl"], # ................................... 'p_display_picture'
auth_token.token.get("displayName"), # .......................... 'p_display_name'
auth_token.token.get("displayPictureUrl"), # .................... 'p_display_picture'
token_id, # ..................................................... 'p_token_id'
json.to_string(python_data = token_notes, no_space = True), # ... 'p_notes'
mongo_json["user"]["userId"] # .................................. 'p_created_by'
auth_token.user.userId # ........................................ 'p_created_by'
),
session_token = session_token
)
@@ -282,7 +274,7 @@ class MailOAuthModel(BaseModel):
mongo_conn: AsyncMongo,
token_id: ObjectId | str = None,
**kwargs
) -> dict | None:
) -> CoreAuthTokenModel | None:
"""
To retrieve stored tokens from the database.
@@ -301,21 +293,15 @@ class MailOAuthModel(BaseModel):
# If there is no search criteria, we exit with failure:
if not filter_json: return None
# If there is some filtering possible,
# we fetch and return the token:
return await mongo_conn.find_one(
# If there is some filtering possible, we fetch the token:
token = await mongo_conn.find_one(
collection = self.AUTH_COLLECTION,
filter = filter_json,
projection = {
"_id": True,
"serviceType": True,
"authType": True,
"client": True,
"clientUserId": True,
"token": True
}
)
# Done here:
return CoreAuthTokenModel(**token) if token else None
# *****************************************************************************************************************
# ***** ****