(20241127) GMail work updated.

This commit is contained in:
2024-11-27 20:13:25 +05:30
parent 7b08e37d2f
commit 269e36ec27
11 changed files with 532 additions and 1 deletions
+184
View File
@@ -0,0 +1,184 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Monday, 25th Nov., 2024
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, request
# My utils:
from utils_v2.string import json
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
)
# Common:
from shared import constants
# For asynchronous activities:
import asyncio
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# Related to Quart:
mail_callback_bp = Blueprint("mail_cb", __name__)
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
@mail_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
# ---------------------------------------------------------------------------------------------------------------------
@mail_callback_bp.route("/callback/gmail", 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 = "gmailCllBckApi",
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 mail_callback(
inbound_headers: dict = None,
inbound_data: dict = None,
inbound_files: dict = None,
**kwargs
):
"""
Use this when authorizing access to someone's GMail account. This can be used to capture the authentication token.
: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.
"""
# Construct a message:
message = "🪝 *WEBHOOK/CALLBACK ALERT!* 🪝\n\n"
message += f"Method: *{request.method}*\nLog Id.: `{kwargs.get('log_id')}`\n\n"
message += "*Headers:*\n```json\n"
message += json.to_string({k: v for k, v in request.headers.items()})
message += "\n```\n"
message += "*Query Args:*\n```json\n"
message += json.to_string(request.args.to_dict())
message += "\n```\n"
message += "*JSON:*\n```json\n"
message += json.to_string(await request.get_json())
message += "\n```\n"
message += "*Form-Data:*\n```json\n"
message += json.to_string((await request.form).to_dict())
message += "\n```\n"
message += "*Form-Files:*\n```json\n"
message += json.to_string(inbound_files, default = str)
message += "\n```\n"
# Send a message on Telegram:
api_response = await current_app.http_client.post(
url = current_app.script_data["alerts"]["url"],
json = {
"message": message,
"type": "info",
"chatId": "1275560043" # ... KPS
}
)
# Return a success response:
return ResponseModel(
status_code = StatusCodes.OK,
data = {"accepted": True}
)
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
View File
View File
+110
View File
@@ -0,0 +1,110 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Tuesday, 12th Nov., 2024
OBJECTIVE:
To get the session information from the session token for a given user.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# To use Quart:
from quart import current_app
# The data models:
from models.data.user import (
IsSessionRequest
)
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** CLASSES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
async def get_session(session_token):
"""
Gets the session's info from the session token.
:param session_token: The identifier of the session.
:return: The info or None.
"""
session_info = await current_app.user.is_session(
db_conn = current_app.sql_reader,
request = IsSessionRequest(sessionToken = session_token),
cache = current_app.module_cache,
)
if isinstance(session_info, dict): return session_info.get("data")
else: return None
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
View File
View File
+128
View File
@@ -0,0 +1,128 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Thursday, 24th Oct., 2024
OBJECTIVE:
To define the interaction between the UI layer and the database connectivity in one place. Here we will handle
all user-related interactions.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# The base model:
from models.behaviour.base import BaseModel
# My async utils:
from utils_v2.string import json
from utils_v2.cache.async_redis_cache_v2 import AsyncRedisCache
from utils_v2.database.async_mysql_v2 import AsyncMySQL
# The data models:
from models.data.user.user import (
IsSessionRequest
)
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** CLASSES ***
# ***** ****
# *****************************************************************************************************************
class UserModel(BaseModel):
async def is_session(
self,
db_conn: AsyncMySQL,
request: IsSessionRequest,
cache: AsyncRedisCache,
cache_expiry: int = 3_600
):
"""
Fetches information about the current user from his session.
:param db_conn: The database connection to use to perform the action.
:param request: The instance of the data model that defines the structure of the request.
:param cache: The caching object to use to set the session in cache memory.
:param cache_expiry: The no. of seconds after which this information will be deleted from the cache.
:return: The raw response from the database call (SQL).
"""
return await self.call_cached_procedure(
cache = cache,
cache_key = "usr_is_" + str(request.sessionToken),
cache_expiry = cache_expiry,
db_conn = db_conn,
proc_name = "isSession",
proc_args = (request.sessionToken,),
session_token = request.sessionToken
)
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
View File
+108
View File
@@ -0,0 +1,108 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Wednesday, 27th Nov., 2024.
OBJECTIVE:
To provide the structure for the request and response of the APIs that will be used to request OAuth2.0
authorization for mail services.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator
from typing import Optional, Literal
# My utils:
from utils_v2.string import regex
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class LoginRequest(BaseModel):
username: str = Field(description = "the username of the user")
password: str = Field(description = "the password of the user")
mode: Optional[str] = Field(
description = "the mode through which this request came in",
default = "N/A"
)
remoteIp: Optional[str] = Field(
description = "the ip addr of the client",
default = "N/A"
)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
+1 -1
View File
@@ -707,7 +707,7 @@ class AsyncMongo(AsyncMongoBase):
:param upsert: If you want to insert if the document doesn't already exist.
:param session: The session if you need to do this in a transaction.
:param raise_exception: Whether, or not, you want to raise an exception when something fails.
:return: True or False based on the success of the operation.
:return: The fetched document.
"""
# Ensure you are connected:
+1
View File
@@ -89,6 +89,7 @@ class GoogleAuthTokens(BaseModel):
refreshToken: str = Field(description = "token to be used to refresh the access token")
expiresAt: AwareDatetime = Field(description = "the time (utc) at which the token will expire")
scopes: List[str] = Field(description = "the list of permissions", default = [])
email: str | None = Field(description = "the email id of the user", default = None)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓