(20241127) Testing GMail auth.
This commit is contained in:
+105
-33
@@ -6,12 +6,12 @@
|
||||
|
||||
DATE:
|
||||
|
||||
Thursday, 24th Oct., 2024
|
||||
Wednesday, 27th Nov., 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.
|
||||
To define the interaction between the UI layer and the database connectivity in one place. Here we shall handle
|
||||
all the activities for OAuth2.0 authorization requests for all the users of our service.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
@@ -35,18 +35,19 @@ 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
|
||||
from utils_v2.date_time import date_time
|
||||
from utils_v2.database.async_mongo_v2 import AsyncMongo
|
||||
|
||||
# The data models:
|
||||
from models.data.user.user import (
|
||||
IsSessionRequest
|
||||
)
|
||||
# To work with MongoDB:
|
||||
from bson import ObjectId
|
||||
|
||||
# To work with datatypes:
|
||||
from typing import Literal
|
||||
|
||||
# To make deep-copies:
|
||||
import copy
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
@@ -86,35 +87,106 @@ from models.data.user.user import (
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class UserModel(BaseModel):
|
||||
class MailOAuthModel:
|
||||
|
||||
async def is_session(
|
||||
self,
|
||||
db_conn: AsyncMySQL,
|
||||
request: IsSessionRequest,
|
||||
cache: AsyncRedisCache,
|
||||
cache_expiry: int = 3_600
|
||||
):
|
||||
AUTH_COLLECTION = "_authTokens"
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
async def get_id(
|
||||
db_conn: AsyncMongo,
|
||||
user_info: dict,
|
||||
service_type: Literal["email", "chat"],
|
||||
service_client: Literal["gmail"],
|
||||
auth_type: Literal["oauth"]
|
||||
) -> ObjectId:
|
||||
|
||||
"""
|
||||
Fetches information about the current user from his session.
|
||||
Stores params from the session info and gives an identifier to use in the authorization URL. Use this when the
|
||||
user requests an authorization URL to link your service to another service (like GMail).
|
||||
: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).
|
||||
:param user_info: The dictionary that has the user's session information.
|
||||
:param service_type: The type of service being provided.
|
||||
: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.
|
||||
:return: An ObjectId to later store the granted tokens.
|
||||
"""
|
||||
|
||||
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
|
||||
# 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:
|
||||
db_json = await db_conn.find_one_and_update(
|
||||
collection = MailOAuthModel.AUTH_COLLECTION,
|
||||
filter = {
|
||||
"serviceType": service_type,
|
||||
"client": service_client,
|
||||
"authType": auth_type,
|
||||
"user": user_info,
|
||||
},
|
||||
update = {
|
||||
"$set": {
|
||||
"lastRequestTs": request_ts
|
||||
},
|
||||
"$setOnInsert": {
|
||||
"version": "1.0.0",
|
||||
"serviceType": service_type,
|
||||
"client": service_client,
|
||||
"authType": auth_type,
|
||||
"user": user_info,
|
||||
"token": None,
|
||||
"firstRefreshTs": None,
|
||||
"lastRefreshTs": None,
|
||||
"firstRequestTs": request_ts,
|
||||
}
|
||||
},
|
||||
projection = {
|
||||
"_id": True
|
||||
},
|
||||
upsert = True,
|
||||
return_updated = True
|
||||
)
|
||||
|
||||
# Done here:
|
||||
return db_json["_id"] if db_json else None
|
||||
|
||||
@staticmethod
|
||||
async def set_token(
|
||||
db_conn: AsyncMongo,
|
||||
user_identifier: ObjectId | str,
|
||||
token: dict
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
This method is to be called when the end user authorizes your service to connect to his third-party account. For
|
||||
example, when the end user allows you to access his GMail account.
|
||||
:param db_conn: The database connection to use to perform the action.
|
||||
:param user_identifier: The identifier granted by the 'get_id' method.
|
||||
:param token: The token granted by the third-party service.
|
||||
:return:
|
||||
"""
|
||||
|
||||
# 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 the database:
|
||||
token_saved = await db_conn.update_one(
|
||||
collection = MailOAuthModel.AUTH_COLLECTION,
|
||||
filter = {"_id": ObjectId(user_identifier)},
|
||||
update = {
|
||||
"$set": {
|
||||
"token": token,
|
||||
"firstRefreshTs": request_ts,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# Done here:
|
||||
return token_saved
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
|
||||
+37
-12
@@ -51,7 +51,8 @@ from utils_v2.string import regex
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
# RegEx Patterns:
|
||||
REGEX_SESSION_TOKEN = r"^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$"
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
@@ -71,20 +72,35 @@ from utils_v2.string import regex
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
class OAuthMailAuthorizationRequestHeaders(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"
|
||||
sessionToken: str = Field(
|
||||
description = "the session token of the user who is requesting the service",
|
||||
pattern = REGEX_SESSION_TOKEN,
|
||||
frozen = True,
|
||||
alias = "X-Session-Token"
|
||||
)
|
||||
|
||||
remoteIp: Optional[str] = Field(
|
||||
description = "the ip addr of the client",
|
||||
default = "N/A"
|
||||
# ┏┓ ┏•
|
||||
# ┃ ┏┓┏┓╋┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┗┫
|
||||
# ┛
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
def model_dump(self, *args, **kwargs):
|
||||
return super().model_dump(*args, by_alias = True, **kwargs)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
class OAuthMailAuthorizationRequestData(BaseModel):
|
||||
|
||||
mailClient: Literal["gmail"] = Field(
|
||||
description = "the e-mail provider like 'gmail'",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
# ┏┓ ┏•
|
||||
@@ -95,6 +111,15 @@ class LoginRequest(BaseModel):
|
||||
class Config:
|
||||
extra = "forbid"
|
||||
|
||||
# ┓┏ ┓• ┓ •
|
||||
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
|
||||
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
|
||||
|
||||
@field_validator("mailClient", mode = "before")
|
||||
def to_lowercase(cls, value):
|
||||
if isinstance(value, str): value = value.strip().lower()
|
||||
return value
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
"""
|
||||
|
||||
AUTHOR:
|
||||
|
||||
Khushal P Soonderji
|
||||
|
||||
DATE:
|
||||
|
||||
Friday, 22nd Nov., 2024.
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To provide the data model for the structure of each message.
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user