diff --git a/app/api/integrations/simbrella.py b/app/api/integrations/simbrella.py index 101664e..58171f4 100644 --- a/app/api/integrations/simbrella.py +++ b/app/api/integrations/simbrella.py @@ -1,14 +1,64 @@ +from os import access import httpx -import json +import time from app.utils.logger import logger from app.config import settings -import logging class SimbrellaIntegration: BASE_URL = settings.SIMBRELLA_BASE_URL ENDPOINT_RAC_CHECKS = settings.SIMBRELLA_ENDPOINT_RAC_CHECKS HEALTH_ENDPOINT = settings.SIMBRELLA_HEALTH + AUTH_ENDPOINT = settings.BANK_CALL_AUTH_ENDPOINT + + _access_token = None # cache token in memory + _token_expiry = 0 + + @staticmethod + def generate_token(): + """ + Generate a new access token using the username and password from settings. + """ + url = f"{SimbrellaIntegration.BASE_URL}{SimbrellaIntegration.AUTH_ENDPOINT}" + + payload = { + "username": settings.BANK_CALL_USERNAME, + "password": settings.BANK_CALL_PASSWORD, + "grant_type": "password" + } + + headers = {"Content-Type": "application/json"} + + try: + logger.info(f"Requesting Bank token from {url}") + + response = httpx.post(url, json=payload, headers=headers, timeout=10.0) + response.raise_for_status() + + data = response.json() + expires_in = data.get("expires_in", 1800) + + SimbrellaIntegration._access_token = data.get("access_token") + SimbrellaIntegration._token_expiry = time.time() + expires_in - 60 + + if not SimbrellaIntegration._access_token: + raise Exception("Access token not found in Bank Authorization response") + + logger.info("Successfully retrieved Bank access token") + return SimbrellaIntegration._access_token + + except Exception as e: + logger.error(f"Token generation failed: {str(e)}", exc_info=True) + raise Exception(f"Token generation failed: {str(e)}") + + @staticmethod + def _get_token(): + """ + Return a valid token, refreshing if expired or missing + """ + if not SimbrellaIntegration._access_token or time.time() >= SimbrellaIntegration._token_expiry: + return SimbrellaIntegration.generate_token() + return SimbrellaIntegration._access_token @staticmethod def rac_check(customer_id, account_id, transaction_id): @@ -27,13 +77,14 @@ class SimbrellaIntegration: "channel": "USSD" } - headers = { - "Content-Type": "application/json", - "x-api-key": f"{settings.VALID_API_KEY}", - "App-Id": f"{settings.VALID_APP_ID}", - } - try: + access_token = SimbrellaIntegration._get_token() + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {access_token}" + } + + response = httpx.post(url, json=payload, headers=headers, timeout=10.0) logger.info(f"This is Response: {str(response)}", exc_info=True) @@ -47,17 +98,23 @@ class SimbrellaIntegration: @staticmethod def health_check(): """ - Health check for Simbrella Service + Health check for Bank Service """ url = f"{SimbrellaIntegration.BASE_URL}/{SimbrellaIntegration.HEALTH_ENDPOINT}" - logger.info(f"Simbrella Health Check URL: {url}") + logger.info(f"Bank Health Check URL: {url}") try: - response = httpx.get(url, timeout=10.0) - logger.info(f"Simbrella Health Check Response: {response.text}") + access_token = SimbrellaIntegration._get_token() + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {access_token}" + } + + response = httpx.get(url, headers=headers, timeout=10.0) + logger.info(f"Bank Health Check Response: {response.text}") return response except Exception as e: - logger.error(f"Simbrella Health Check API call failed: {str(e)}", exc_info=True) - raise + logger.error(f"Bank Health Check API call failed: {str(e)}", exc_info=True) + raise Exception(f"Bank Health Check API call failed: {str(e)}") diff --git a/app/api/routes/routes.py b/app/api/routes/routes.py index 999d9b2..6e63009 100644 --- a/app/api/routes/routes.py +++ b/app/api/routes/routes.py @@ -1,5 +1,3 @@ -from re import S -from sqlite3 import DatabaseError from app.api.integrations.events_service import EventServiceIntegration from app.api.integrations.simbrella import SimbrellaIntegration from flask import Blueprint, request, jsonify, send_from_directory @@ -127,7 +125,7 @@ def health_check(): response = {} db_status = "Connection Successful" events_service_status = "Connection Successful" - emulator_status = "Connection Successful" + bank_status = "Connection Successful" errors = [] status = "ok" @@ -165,26 +163,26 @@ def health_check(): status = "failed" errors.append(f"Events Service connection failed: {str(e)}") - # Check Emulator health + # Check Bank health try: emulator_response = SimbrellaIntegration.health_check() if emulator_response.status_code != 200: - emulator_status = "Connection Failed" + bank_status = "Connection Failed" status = "failed" - errors.append(f"Emulator response: {emulator_response.text}") + errors.append(f"Bank Connection response: {emulator_response.text}") except Exception as e: - emulator_status = "Connection Failed" + bank_status = "Connection Failed" status = "failed" - errors.append(f"Emulator connection failed: {str(e)}") + errors.append(f"Connection to Bank failed: {str(e)}") response = { "status": status, "db_status": db_status, "events_service_status": events_service_status, - "emulator_status": emulator_status, + "bank_status": bank_status, "db_uri": db_uri, "errors": errors or None } diff --git a/app/config.py b/app/config.py index 17af0a7..8cf31c2 100644 --- a/app/config.py +++ b/app/config.py @@ -44,11 +44,12 @@ class Config: # SIMBRELLA_ENDPOINT_RAC_CHECKS = os.getenv("SIMBRELLA_ENDPOINT_RAC_CHECKS", "RACCheck") VALID_APP_ID = os.getenv("SIMBRELLA_APP_ID", "app1") VALID_API_KEY = os.getenv("SIMBRELLA_API_KEY", "test-api-key-12345") - - SIMBRELLA_BASE_URL = os.getenv("SIMBRELLA_BASE_URL", "http://127.0.0.1:6337") SIMBRELLA_ENDPOINT_RAC_CHECKS = os.getenv("SIMBRELLA_ENDPOINT_RAC_CHECKS","api/rac-check") SIMBRELLA_HEALTH = os.getenv("SIMBRELLA_ENDPOINT_RAC_CHECKS","api/system-health-check") + BANK_CALL_AUTH_ENDPOINT = os.getenv("BANK_CALL_AUTH_ENDPOINT", "/api/Auth/generate-token") + BANK_CALL_USERNAME = os.getenv("BANK_CALL_USERNAME", "simbrella") + BANK_CALL_PASSWORD = os.getenv("BANK_CALL_PASSWORD", "G7$k9@pL2!qR") diff --git a/app/swagger/digifi_swagger.json b/app/swagger/digifi_swagger.json index ab4fa0b..423ba5b 100644 --- a/app/swagger/digifi_swagger.json +++ b/app/swagger/digifi_swagger.json @@ -104,7 +104,7 @@ "status": "ok", "db_status": "Connection Successful", "events_service_status":"Connection Successful", - "emulator_status":"Connection Successful", + "bank_status":"Connection Successful", "db_uri": "postgresql://user:****@localhost:5432/digifi_db", "error": [] } @@ -119,7 +119,7 @@ "status": "failed", "db_status": "Connection Failed", "events_service_status":"Connection Failed", - "emulator_status":"Connection Failed", + "bank_status":"Connection Failed", "db_uri": "Unavailable", "error":["could not connect to server: Connection refused"] }