(20250220)

This commit is contained in:
2025-02-20 16:26:43 +05:30
parent 2435760ea3
commit d16fa61ec3
7 changed files with 475 additions and 195 deletions
+204 -136
View File
@@ -26,8 +26,7 @@
N/A
"""
import copy
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
@@ -53,15 +52,31 @@ from utils_v2.security.otp import HashedOTP
from utils_v2.api.response import ResponseModel
from utils_v2.api.codes import StatusCodes, HttpCodes
from utils_v2.api.async_quart import (
log_request_to_mongo,
only_whitelisted_ips,
should_not_be_under_maintenance,
set_api_version,
read_input,
limit_rate, validate_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,
messages_from_pydantic_exception
)
# Data models:
from models.core.user import CoreUserInfoModel
from models.api.common.otp.timed_otp import (
TimedOTPRequestHeaders,
SendTimedOTPSMSFromSavvyBulkSMSKenyaRequestData,
VerifyTimedOTPRequestData
)
from models.common.otp.timed_otp import GenerateTimedOTP, VerifyTimedOTP
from models.message.sms.send import SavvyBulkSMSKenyaMessage
# Helpers:
from api.helpers.user import token_check
# For asynchronous activities:
import asyncio
@@ -76,7 +91,6 @@ import asyncio
# Related to Quart:
timed_otp_bp = Blueprint("timed_otp", __name__)
api_version = "2.0.0"
# *****************************************************************************************************************
@@ -107,177 +121,231 @@ def init(blueprint_setup_state):
# ---------------------------------------------------------------------------------------------------------------------
@timed_otp_bp.route("/generate", methods = ["POST", "GET"])
@timed_otp_bp.route("/send/sms/kenya/savvybulksms", methods = ["POST"])
@set_api_version(api_version = "1.0.0")
@read_input(sanitize_headers = True, sanitize_data = True)
@get_session_info(key = "X-Session-Token", session_coro = "get_session")
@log_request_to_mongo(
attr_name = "mongo",
log_type = "otp",
operation = "generateOtp",
api_version = api_version,
attr_name = "logs_mongo",
project = constants.PROJECT_NAME,
log_type = constants.MODULE_NAME,
operation = "otpSmsSendApi",
log_input = True,
log_output = True
log_output = True,
sensitive_keys = ["sessionToken", "X-Session-Token", "tokenKey"]
)
@log_chain_to_mongo(attr_name = "logs_mongo")
@should_not_be_under_maintenance(attr_name = "is_under_maintenance")
# @only_whitelisted_ips(attr_name = "whitelisted_ips")
@validate_input(data_validator = lambda x: GenerateTimedOTP(**x))
# @limit_rate(
# attr_name = "redis_cache",
# rate_limit = 1,
# seconds = 2,
# data_keys = ["id"],
# allow_if_exception = False
# )
@validate_input(
header_validator = lambda x: TimedOTPRequestHeaders(**x).model_dump(),
data_validator = lambda x: SendTimedOTPSMSFromSavvyBulkSMSKenyaRequestData(**x)
)
@handle_cancelled_request()
async def generate_otp(
inbound_headers: dict = None,
inbound_data: dict | GenerateTimedOTP = None,
inbound_headers: dict | TimedOTPRequestHeaders = None,
inbound_data: dict | SendTimedOTPSMSFromSavvyBulkSMSKenyaRequestData = None,
inbound_files: dict = None,
log_id: str = None
**kwargs
):
"""
Generates one OTP for the amount of time specified in the request.
:param inbound_headers: auto-extracted by the decorators from 'async_quart.py'.
:param inbound_data: auto-extracted by the decorators from 'async_quart.py'.
:param inbound_files: auto-extracted by the decorators from 'async_quart.py'.
:param log_id: An identifier for the logs (if logging is enabled).
:return: A standard response structure from the function in 'async_quart.py'.
: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.
"""
try:
# ┏┓ ┓ ┏┓┓ ┓
# ┣┫┓┏╋┣┓ ┃ ┣┓┏┓┏┃┏
# ┛┗┗┻┗┛┗ ┗┛┛┗┗ ┗┛┗
# Generate the OTP:
otp_key = current_app.redis_cache.make_key(str(inbound_data.id))
otp_client = HashedOTP(secret = HashedOTP.generate_secret())
otp = otp_client.generate_otp(count = 0)
# Delete any existing OTP with the same identifiers:
await current_app.redis_cache.delete(key = otp_key)
# Store the OTP in Redis:
otp_stored = await current_app.redis_cache.set(
key = otp_key,
value = {
"otp": otp,
"att": inbound_data.attempts,
"iat": date_time.get_current_utc_date_time().timestamp(),
"sec": inbound_data.seconds
},
expiry = inbound_data.seconds
)
# Done here:
# Either the session must be valid, or
# the IP address requesting the service must be whitelisted:
if (
kwargs.get("session_info") is None and
inbound_headers["Remote-IP"] not in current_app.whitelisted_ips
):
return ResponseModel(
api_version = api_version,
status_code = StatusCodes.OK if otp_stored else StatusCodes.FAILED,
data = {"otp": otp} if otp_stored else None
status_code = StatusCodes.FAILED,
http_code = HttpCodes.UNAUTHORIZED,
message = "Invalid session and/or bad IP addr."
)
# In case the client terminates the connection prematurely:
except asyncio.CancelledError as exception:
current_app.printer(exception)
return ResponseModel(api_version = api_version, status_code = StatusCodes.CLIENT_CLOSED_REQUEST)
# Get the user's info:
user_info = CoreUserInfoModel(**kwargs["session_info"])
# ┏┓ ┏┓┳┳┓┏┓ ┏┓
# ┃┓┏┓╋ ┏┓┏┓ ┗┓┃┃┃┗┓ ┣┫┏┏┏┓┓┏┏┓╋
# ┗┛┗ ┗ ┗┻┛┗ ┗┛┛ ┗┗┛ ┛┗┗┗┗┛┗┻┛┗┗
sms_auth_token = None
# If a token key has been given, we retrieve that account:
if inbound_data.tokenKey is not None:
sms_auth_token = await current_app.savvy_bulk_sms_kenya_controller.get_token_from_key(
mongo_data_conn = current_app.data_mongo,
token_key = inbound_data.tokenKey,
must_be_active = True,
additional_filter = token_check.get_authorization_filter(user_info = user_info)
)
# Otherwise, we fetch the first SMS client account:
else:
sms_auth_token = await current_app.savvy_bulk_sms_kenya_controller.get_first_token(
mongo_data_conn = current_app.data_mongo,
must_be_active = True,
additional_filter = token_check.get_authorization_filter(user_info = user_info)
)
# If we found no account:
if not sms_auth_token: return ResponseModel(
status_code = StatusCodes.FAILED,
http_code = HttpCodes.NOT_FOUND,
message = "No SMS integration account found."
)
# ┏┓ ┓ ┓ ┏┓┏┳┓┏┓
# ┗┓┏┓┏┓┏┫ ╋┣┓┏┓ ┃┃ ┃ ┃┃
# ┗┛┗ ┛┗┗┻ ┗┛┗┗ ┗┛ ┻ ┣┛
# Add the user's info to the 'id' map:
otp_id = copy.deepcopy(inbound_data.id)
otp_id["user"] = kwargs["session_info"]
# Generate an OTP:
otp_response = await current_app.timed_otp_controller.generate(
redis_cache = current_app.module_cache,
inbound_data = GenerateTimedOTP(
id = otp_id,
attempts = inbound_data.attempts,
seconds = inbound_data.seconds
)
)
# If the OTP generation failed:
if not otp_response.success: return ResponseModel(
status_code = StatusCodes.FAILED,
http_code = HttpCodes.INTERNAL_SERVER_ERROR,
message = otp_response.message
)
# Format the message:
sms_message = SavvyBulkSMSKenyaMessage(
recipientNo = inbound_data.recipientNo,
text = inbound_data.smsText.replace(inbound_data.smsReplace, str(otp_response.data))
)
# Send the message:
sms_results = await current_app.savvy_bulk_sms_kenya_controller.send_many_sms(
mongo_data_conn = current_app.data_mongo,
auth_token = sms_auth_token,
messages = [sms_message],
tags = inbound_data.tags or []
)
sms_success = True if sms_results.successCount == sms_results.totalCount else False
# ┳┓
# ┣┫┏┓┏┏┓┏┓┏┓┏┏┓
# ┛┗┗ ┛┣┛┗┛┛┗┛┗
# ┛
# Done here:
return ResponseModel(
status_code = StatusCodes.OK if sms_success else StatusCodes.FAILED,
http_code = HttpCodes.SUCCESS if sms_success else HttpCodes.INTERNAL_SERVER_ERROR,
message = "OTP sent successfully." if sms_success else "OTP NOT sent."
)
# ---------------------------------------------------------------------------------------------------------------------
@timed_otp_bp.route("/verify", methods = ["POST", "GET"])
@set_api_version(api_version = "1.0.0")
@read_input(sanitize_headers = True, sanitize_data = True)
@get_session_info(key = "X-Session-Token", session_coro = "get_session")
@log_request_to_mongo(
attr_name = "mongo",
log_type = "otp",
operation = "verifyOtp",
api_version = api_version,
attr_name = "logs_mongo",
project = constants.PROJECT_NAME,
log_type = constants.MODULE_NAME,
operation = "otpVerifyApi",
log_input = True,
log_output = True
log_output = True,
sensitive_keys = ["sessionToken", "X-Session-Token", "tokenKey"]
)
@log_chain_to_mongo(attr_name = "logs_mongo")
@should_not_be_under_maintenance(attr_name = "is_under_maintenance")
# @only_whitelisted_ips(attr_name = "whitelisted_ips")
@validate_input(data_validator = lambda x: VerifyTimedOTP(**x))
# @limit_rate(
# attr_name = "redis_cache",
# rate_limit = 1,
# seconds = 2,
# data_keys = ["id"],
# allow_if_exception = False,
# count_for_http_codes = [200]
# )
@validate_input(
header_validator = lambda x: TimedOTPRequestHeaders(**x).model_dump(),
data_validator = lambda x: VerifyTimedOTPRequestData(**x)
)
@handle_cancelled_request()
async def verify_otp(
inbound_headers: dict = None,
inbound_data: dict | VerifyTimedOTP = None,
inbound_files: dict = None,
log_id: str = None
**kwargs
):
"""
Verifies the claimed OTP against the stored OTP.
:param inbound_headers: auto-extracted by the decorators from 'async_quart.py'.
:param inbound_data: auto-extracted by the decorators from 'async_quart.py'.
:param inbound_files: auto-extracted by the decorators from 'async_quart.py'.
:param log_id: An identifier for the logs (if logging is enabled).
:return: A standard response structure from the function in 'async_quart.py'.
: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.
"""
try:
# ┏┓ ┓ ┏┓┓ ┓
# ┣┫┓┏╋┣┓ ┃ ┣┓┏┓┏┃┏
# ┛┗┗┻┗┛┗ ┗┛┛┗┗ ┗┛┗
# Start by assuming failure:
is_valid = False
attempts_left = None
# Fetch the OTP from Redis:
otp_key = current_app.redis_cache.make_key(str(inbound_data.id))
stored_otp = await current_app.redis_cache.get(key = otp_key)
# Test the validity of the OTP:
if stored_otp is not None:
# Delete the record from the cache.:
await current_app.redis_cache.delete(key = otp_key)
# Make note of the attempts left.
# We reduce the count by one straightaway:
attempts_left = stored_otp["att"] - 1
# If the stored OTP matches the claimed OTP,
# we note down the acceptance and delete the record from the cache:
if inbound_data.otp == stored_otp["otp"]:
is_valid = True
attempts_left = 0
# If the stored OTP and the claimed OTP don't match,
# we reduce the attempt count and :
elif attempts_left > 0:
# Update the OTP info in the cache:
otp_updated = await current_app.redis_cache.set(
key = otp_key,
value = {
"otp": stored_otp["otp"],
"att": attempts_left,
"iat": stored_otp["iat"],
"sec": stored_otp["sec"]
},
expiry = (stored_otp["iat"] + stored_otp["sec"]) - date_time.get_current_utc_date_time().timestamp()
)
# If the update failed:
if not otp_updated: attempts_left = None
# Done here:
# Either the session must be valid, or
# the IP address requesting the service must be whitelisted:
if (
kwargs.get("session_info") is None and
inbound_headers["Remote-IP"] not in current_app.whitelisted_ips
):
return ResponseModel(
api_version = api_version,
status_code = StatusCodes.OK if is_valid else StatusCodes.FAILED,
data = {
"isValid": is_valid,
"attemptsLeft": attempts_left
},
http_code = HttpCodes.UNAUTHORIZED
status_code = StatusCodes.FAILED,
http_code = HttpCodes.UNAUTHORIZED,
message = "Invalid session and/or bad IP addr."
)
# In case the client terminates the connection prematurely:
except asyncio.CancelledError as exception:
current_app.printer(exception)
return ResponseModel(api_version = api_version, status_code = StatusCodes.CLIENT_CLOSED_REQUEST)
# Get the user's info:
user_info = CoreUserInfoModel(**kwargs["session_info"])
# ┓┏ •┏ ┓ ┏┓┏┳┓┏┓
# ┃┃┏┓┏┓┓╋┓┏ ╋┣┓┏┓ ┃┃ ┃ ┃┃
# ┗┛┗ ┛ ┗┛┗┫ ┗┛┗┗ ┗┛ ┻ ┣┛
# ┛
# Add the user's info to the 'id' map:
otp_id = copy.deepcopy(inbound_data.id)
otp_id["user"] = kwargs["session_info"]
# Perform actual verification:
otp_response = await current_app.timed_otp_controller.verify(
redis_cache = current_app.module_cache,
inbound_data = VerifyTimedOTP(
id = otp_id,
otp = inbound_data.otp
)
)
# ┳┓
# ┣┫┏┓┏┏┓┏┓┏┓┏┏┓
# ┛┗┗ ┛┣┛┗┛┛┗┛┗
# ┛
# Done here:
return ResponseModel(
status_code = StatusCodes.OK if otp_response.success else StatusCodes.FAILED,
http_code = HttpCodes.SUCCESS if otp_response.success else HttpCodes.UNAUTHORIZED,
message = otp_response.message
)
# *****************************************************************************************************************
+10 -4
View File
@@ -101,6 +101,8 @@ from controllers_v2.finstitutions.payments.safaricom_mpesa_express import Safari
from controllers_v2.software.mikrotik.all_mikrotik import AllMikroTikController
from controllers_v2.software.mikrotik.mikrotik_pppoe_1000 import MikroTikPPPoE1000Controller
from controllers_v2.software.mikrotik.mikrotik_hostpot_1000 import MikroTikHotspot1000Controller
# ---
from controllers_v2.common.otp.timed_otp import TimedOTPController
# To make REST API calls:
import httpx
@@ -152,8 +154,7 @@ from api.blueprints.ai.llm.invoke import llm_invoke_bp
# Common Blueprints:
from api.blueprints.common.disable import auth_token_disable_bp
from api.blueprints.common.session_token import session_token_bp
from api.blueprints.common.isp.user_login import isp_user_login_bp
from api.blueprints.common.isp.user_signup import isp_user_signup_bp
from api.blueprints.common.otp.timed_otp import timed_otp_bp
# Tech and Testing Blueprints:
from api.blueprints.tech.chat_alerts import tech_chat_alert_bp
@@ -229,8 +230,7 @@ app.register_blueprint(trading_symbols_list_bp, url_prefix = f"/{MODULE_BASE}/fi
# Common Blueprints:
app.register_blueprint(auth_token_disable_bp, url_prefix = f"/{MODULE_BASE}")
app.register_blueprint(session_token_bp, url_prefix = f"/{MODULE_BASE}")
app.register_blueprint(isp_user_login_bp, url_prefix = f"/{MODULE_BASE}/isp/user")
app.register_blueprint(isp_user_signup_bp, url_prefix = f"/{MODULE_BASE}/isp/user")
app.register_blueprint(timed_otp_bp, url_prefix = f"/{MODULE_BASE}/otp/timed")
# AI Blueprints:
app.register_blueprint(llm_invoke_bp, url_prefix = f"/{MODULE_BASE}/ai")
@@ -592,6 +592,12 @@ async def app_startup(**kwargs):
)
current_app.printer("Software/MikroTik (C) ready.")
# Common / OTP:
current_app.timed_otp_controller = TimedOTPController(
debug = enable_debugging
)
current_app.printer("Common/OTP (C) ready.")
# ┏┓ ┓ ┏┓┓•
# ┃ ┏┓┏┓┏┓┏┓┏╋┏┓┏┓┏ ┏┓┏┓┏┫ ┃ ┃┓┏┓┏┓╋┏
# ┗┛┗┛┛┗┛┗┗ ┗┗┗┛┛ ┛ ┗┻┛┗┗┻ ┗┛┗┗┗ ┛┗┗┛