1111import uvicorn
1212from dotenv import load_dotenv
1313import json
14+ import boto3
1415
1516# Configure logging
1617logging .basicConfig (
@@ -57,8 +58,6 @@ class AuthenticationRequest(BaseModel):
5758class AuthenticationResponse (BaseModel ):
5859 status : str
5960 message : str
60- cookies : list = None
61- screenshot_path : str = None
6261
6362@app .get ("/" )
6463async def root ():
@@ -68,17 +67,6 @@ async def root():
6867async def hello ():
6968 return {"message" : "Hello World!" }
7069
71- @app .get ("/health" )
72- async def health_check ():
73- return JSONResponse (
74- status_code = status .HTTP_200_OK ,
75- content = {
76- "status" : "healthy" ,
77- "uptime" : time .time (),
78- "service" : "web-automation-api"
79- }
80- )
81-
8270@app .post ("/automate" , response_model = WebAutomationResponse )
8371async def automate_web (request : WebAutomationRequest , background_tasks : BackgroundTasks ):
8472 try :
@@ -90,6 +78,55 @@ async def automate_web(request: WebAutomationRequest, background_tasks: Backgrou
9078 message = f"Automation failed: { str (e )} "
9179 )
9280
81+ async def download_cookies_from_s3 ():
82+ """Download cookies from S3 and return them as a list"""
83+ s3_client = boto3 .client ('s3' )
84+ temp_cookie_path = "/tmp/shopping.json"
85+ try :
86+ # Check if file exists in S3
87+ try :
88+ s3_client .head_object (Bucket = 'test-litewebagent' , Key = 'shopping.json' )
89+ except s3_client .exceptions .ClientError as e :
90+ if e .response ['Error' ]['Code' ] == '404' :
91+ print ("No existing cookies file in S3" )
92+ return None
93+ else :
94+ # Something else went wrong
95+ raise e
96+
97+ # If we get here, file exists, so download it
98+ s3_client .download_file ('test-litewebagent' , 'shopping.json' , temp_cookie_path )
99+ with open (temp_cookie_path , 'r' ) as f :
100+ return json .load (f )
101+ except Exception as e :
102+ print (f"Failed to download cookies from S3: { str (e )} " )
103+ return None
104+
105+ async def check_login_status (page , site_url ) -> bool :
106+ """Check if we're on the customer account page rather than the login page."""
107+ await page .goto (f"{ site_url } /customer/account/" )
108+ await page .wait_for_load_state ("networkidle" )
109+
110+ title = await page .title ()
111+ if "Login" in title :
112+ print ("User is not logged in (title contains 'Login')" )
113+ return False
114+ else :
115+ print ("User is already logged in (account page). Title:" , title )
116+ return True
117+
118+ async def restore_cookies (page , cookies ):
119+ """Restore cookies to the browser"""
120+ if not cookies :
121+ return False
122+ try :
123+ await page .context .add_cookies (cookies )
124+ print (f"Restored { len (cookies )} cookie(s) to the browser context" )
125+ return True
126+ except Exception as e :
127+ print (f"Failed to restore cookies: { str (e )} " )
128+ return False
129+
93130@app .post ("/authenticate" , response_model = AuthenticationResponse )
94131async def authenticate_user (request : AuthenticationRequest ):
95132 try :
@@ -98,6 +135,21 @@ async def authenticate_user(request: AuthenticationRequest):
98135 context = await browser .new_context ()
99136 page = await context .new_page ()
100137
138+ # First try to restore cookies from S3
139+ cookies = await download_cookies_from_s3 ()
140+ if cookies :
141+ cookies_restored = await restore_cookies (page , cookies )
142+ if cookies_restored and await check_login_status (page , request .site_url ):
143+ print ("Successfully logged in with existing cookies" )
144+ return AuthenticationResponse (
145+ status = "success" ,
146+ message = "Successfully authenticated using existing cookies"
147+ )
148+
149+ # If we get here, either there were no cookies or they didn't work
150+ # Proceed with fresh authentication
151+ print ("Existing cookies failed or not found, proceeding with fresh authentication" )
152+
101153 # Navigate to login page
102154 login_url = f"{ request .site_url } /customer/account/login/"
103155 await page .goto (login_url , wait_until = "networkidle" )
@@ -128,36 +180,39 @@ async def authenticate_user(request: AuthenticationRequest):
128180 after_login_screenshot = "/tmp/screenshot_after_login.png"
129181 await page .screenshot (path = after_login_screenshot )
130182
131- cookies = await page .context .cookies ()
132-
133- # Check for Magento 2's typical session cookie (PHPSESSID) or Magento 1's (frontend)
134- magento_session_cookies = [c for c in cookies if c ["name" ] in ("frontend" , "frontend_cid" , "PHPSESSID" )]
135- if magento_session_cookies :
136- print (f"✅ Found { len (magento_session_cookies )} potential Magento session cookie(s): { ', ' .join (c ['name' ] for c in magento_session_cookies )} " )
137- else :
138- print ("❌ No Magento 'frontend' or 'PHPSESSID' cookie found - likely not authenticated.\n " )
139-
140183 # Check login status
141184 await page .goto (f"{ request .site_url } /customer/account/" )
142185 page_title = await page .title ()
143- print (page_title )
144186
145- # Get cookies
146- cookies = await context .cookies ()
147-
187+ # Get new cookies
188+ new_cookies = await context .cookies ()
189+
148190 # Check if login was successful
149191 if "Login" not in page_title :
192+ # Save and upload new cookies
193+ temp_cookie_path = "/tmp/shopping.json"
194+ with open (temp_cookie_path , 'w' ) as f :
195+ json .dump (new_cookies , f , indent = 4 )
196+
197+ try :
198+ s3_client = boto3 .client ('s3' )
199+ s3_client .upload_file (
200+ temp_cookie_path ,
201+ 'test-litewebagent' ,
202+ 'shopping.json'
203+ )
204+ print ("Successfully uploaded new cookies to S3" )
205+ except Exception as e :
206+ print (f"Failed to upload new cookies to S3: { str (e )} " )
207+
150208 return AuthenticationResponse (
151209 status = "success" ,
152- message = "Successfully authenticated" ,
153- cookies = cookies ,
154- screenshot_path = after_login_screenshot
210+ message = "Successfully authenticated with fresh login"
155211 )
156212 else :
157213 return AuthenticationResponse (
158214 status = "error" ,
159- message = "Authentication failed - still on login page" ,
160- screenshot_path = after_login_screenshot
215+ message = "Authentication failed - still on login page"
161216 )
162217
163218 await browser .close ()
0 commit comments