From 744ceff9b4ca5397c9b8b488a4cc9677ed6b646a Mon Sep 17 00:00:00 2001 From: tijsziere <39266480+tijsziere@users.noreply.github.com> Date: Mon, 23 Sep 2024 18:11:26 +0200 Subject: [PATCH] store cookie in ram --- main.py | 87 ++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 58 insertions(+), 29 deletions(-) diff --git a/main.py b/main.py index 8324263..be427ec 100644 --- a/main.py +++ b/main.py @@ -17,7 +17,7 @@ import requests import csv import pandas as pd -from datetime import datetime +from datetime import datetime, timedelta import os from azure.cosmos.exceptions import CosmosResourceExistsError import azure.cosmos.cosmos_client as cosmos_client @@ -412,6 +412,58 @@ def required_headers_121( ): return url121, username121, password121 +# Dictionary to store cookies, credentials, and expiration times +cookie121 = {} + +def login121(url121, username, password): + # Check if URL exists in the dictionary + if url121 in cookie121: + cookie_data = cookie121[url121] + # Check if the stored username and password match + if cookie_data['username'] == username and cookie_data['password'] == password: + cookie_expiry = cookie_data['expiry'] + current_time = datetime.utcnow() + + # Check if the cookie is valid for at least 24 more hours + if (cookie_expiry - current_time) >= timedelta(hours=24): + logger.info(f"Using cached cookie for {url121}") + return cookie_data['cookie'] + else: + logger.info(f"Cookie for {url121} is valid for less than 24 hours, refreshing cookie...") + + # Otherwise, request a new cookie + body = {'username': username, 'password': password} + url = f'{url121}/api/users/login' + + try: + login_response = requests.post(url, data=body) + login_response.raise_for_status() + except requests.RequestException as e: + error_message = str(e) + logger.error( + f"Failed: 121 login returned {login_response.status_code} {error_message}", + extra=None, + ) + raise HTTPException( + status_code=login_response.status_code, detail=error_message + ) + + # Parse the response + response_data = login_response.json() + cookie = response_data['access_token_general'] + + # Store the new cookie, username, password, and expiration time in the dictionary + expiry_datetime = datetime.fromisoformat(response_data['expires'].replace("Z", "")) + + cookie121[url121] = { + 'username': username, + 'password': password, + 'cookie': cookie, + 'expiry': expiry_datetime + } + + logger.info(f"New cookie stored for {url121} with credentials.") + return cookie @app.post("/kobo-to-121") async def kobo_to_121(request: Request, dependencies=Depends(required_headers_121)): @@ -482,23 +534,8 @@ async def kobo_to_121(request: Request, dependencies=Depends(required_headers_12 payload["referenceId"] = referenceId - # get access token from cookie - body = { - "username": request.headers["username121"], - "password": request.headers["password121"], - } - url = f"{request.headers['url121']}/api/users/login" - login_response = requests.post(url, data=body) - if login_response.status_code >= 400: - error_message = login_response.content.decode("utf-8") - logger.info( - f"Failed: 121 login returned {login_response.status_code} {error_message}", - extra=extra_logs, - ) - raise HTTPException( - status_code=login_response.status_code, detail=error_message - ) - access_token = login_response.json()["access_token_general"] + access_token = login121(request.headers["url121"], request.headers["username121"], request.headers["password121"]) + # POST to 121 import endpoint import_response = requests.post( @@ -506,6 +543,7 @@ async def kobo_to_121(request: Request, dependencies=Depends(required_headers_12 headers={"Cookie": f"access_token_general={access_token}"}, json=[payload], ) + import_response_message = import_response.content.decode("utf-8") if 200 <= import_response.status_code <= 299: logger.info( @@ -557,17 +595,8 @@ async def kobo_update_121(request: Request, dependencies=Depends(required_header ) referenceId = kobo_data['referenceid'] - print(referenceId) - # get access token from cookie - body = {'username': request.headers['username121'], 'password': request.headers['password121']} - url = f"{request.headers['url121']}/api/users/login" - login = requests.post(url, data=body) - if login.status_code >= 400: - raise HTTPException( - status_code=login.status_code, - detail=login.content.decode("utf-8") - ) - access_token = login.json()['access_token_general'] + + access_token = login121(url, request.headers["username121"], request.headers["password121"]) # Create API payload body intvalues = ['maxPayments', 'paymentAmountMultiplier', 'inclusionScore']