Skip to content

Commit 65ea334

Browse files
committed
update backend playwright auth logic
1 parent ac30634 commit 65ea334

File tree

3 files changed

+61
-140
lines changed

3 files changed

+61
-140
lines changed

visual-tree-search-backend/app/api/lwats/webagent_utils_async/utils/playwright_manager.py

Lines changed: 41 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from dotenv import load_dotenv
66
from browserbase import Browserbase
77
import aiohttp
8+
import boto3
89

910
# Load environment variables from .env file
1011
load_dotenv()
@@ -97,117 +98,46 @@ async def restore_cookies(browser_tab: Page, cookie_file_path: str):
9798

9899

99100
async def authenticate(browser_tab: Page, cookie_file_path: str):
100-
"""Authenticate to Magento using Playwright form submission, then show a detailed cookie table."""
101-
print("Attempting login with Playwright form submission")
102-
username = "emma.lopez@gmail.com"
103-
password = "Password.123"
104-
105-
# Start fresh without cookies
106-
await browser_tab.context.clear_cookies()
107-
print("Cleared cookies before login.\n")
108-
109-
# Optional: set a test cookie
110-
await browser_tab.context.add_cookies([{
111-
"name": "test_cookie",
112-
"value": "1",
113-
"domain": "128.105.145.205",
114-
"path": "/",
115-
}])
116-
117-
# Navigate to login page
118-
await browser_tab.goto(SITE_LOGIN_URL)
119-
await browser_tab.wait_for_load_state("networkidle")
120-
121-
print("Current URL:", browser_tab.url)
122-
print("Filling in login form...\n")
123-
124-
# Fill the username
125-
email_field = await browser_tab.query_selector("#email")
126-
if email_field:
127-
await email_field.fill(username)
128-
print("Filled email field")
129-
else:
130-
print("⚠️ Could not find email field")
131-
132-
# Fill the password
133-
password_field = await browser_tab.query_selector("#pass")
134-
if password_field:
135-
await password_field.fill(password)
136-
print("Filled password field")
137-
else:
138-
print("⚠️ Could not find password field")
139-
140-
print("Examining form elements...\n")
141-
form_elements = await browser_tab.query_selector_all("form.form-login input, form#login-form input")
142-
for element in form_elements:
143-
name = await element.get_attribute("name")
144-
value = await element.get_attribute("value")
145-
input_type = await element.get_attribute("type")
146-
if name:
147-
print(f" Form input: {name} = {value if value else '[empty]'} (type: {input_type})")
148-
149-
print("\nClicking login button...")
150-
login_button = (
151-
await browser_tab.query_selector(".action.login.primary")
152-
or await browser_tab.query_selector("#send2")
153-
or await browser_tab.query_selector("button[type='submit']")
154-
)
155-
156-
if login_button:
157-
print(f"Found login button: id={await login_button.get_attribute('id')} type={await login_button.get_attribute('type')}")
158-
try:
159-
async with browser_tab.expect_navigation(wait_until="networkidle", timeout=15000):
160-
await login_button.click()
161-
print("Clicked login button and waited for navigation.\n")
162-
except Exception as e:
163-
print(f"Navigation timeout or error after clicking login: {e}")
164-
else:
165-
print("⚠️ Could not find login button!")
166-
167-
# Save the cookies regardless of success
168-
await store_cookies(browser_tab, cookie_file_path)
169-
170-
# Check if login succeeded
171-
print("Checking if login succeeded...\n")
172-
173-
cookies = await browser_tab.context.cookies()
174-
print(f"Cookies after login attempt ({len(cookies)}) (Markdown Table):\n")
175-
print()
176-
177-
# Check for Magento 2's typical session cookie (PHPSESSID) or Magento 1's (frontend)
178-
magento_session_cookies = [c for c in cookies if c["name"] in ("frontend", "frontend_cid", "PHPSESSID")]
179-
if magento_session_cookies:
180-
print(f"✅ Found {len(magento_session_cookies)} potential Magento session cookie(s): {', '.join(c['name'] for c in magento_session_cookies)}")
181-
else:
182-
print("❌ No Magento 'frontend' or 'PHPSESSID' cookie found - likely not authenticated.\n")
183-
184-
# Navigate to account page to confirm
185-
await browser_tab.goto(f"{SITE_URL}/customer/account/")
186-
await browser_tab.wait_for_load_state("networkidle")
187-
188-
# Check if we're truly logged in by searching for My Account or a welcome message
189-
is_logged_in = False
190-
welcome_msg = await browser_tab.query_selector(".box-information .box-content p") or await browser_tab.query_selector(".welcome-msg")
191-
if welcome_msg:
192-
welcome_text = await welcome_msg.text_content()
193-
if "Emma" in welcome_text:
194-
is_logged_in = True
195-
print(f"✅ Found welcome message containing 'Emma': {welcome_text.strip()}")
196-
197-
page_title = await browser_tab.title()
198-
if "My Account" in page_title and "Login" not in page_title:
199-
is_logged_in = True
200-
print(f"✅ Page title indicates logged in: {page_title}")
201-
202-
if is_logged_in:
203-
print("✅ Successfully logged in!\n")
204-
return True
205-
else:
206-
current_title = await browser_tab.title()
207-
print(f"❌ Login verification failed. Current page: {browser_tab.url} | Title: {current_title}\n")
208-
content = await browser_tab.content()
209-
snippet = content[:500].replace("\n", " ")
210-
print(f"Page content snippet:\n{snippet}...\n")
101+
"""Authenticate using remote API call and store cookies if successful"""
102+
print("Attempting authentication via remote API")
103+
104+
auth_url = os.environ["AUTHENTICATE_URL"]
105+
auth_data = {
106+
"username": "emma.lopez@gmail.com",
107+
"password": "Password.123",
108+
"site_url": SITE_URL
109+
}
110+
111+
try:
112+
async with aiohttp.ClientSession() as session:
113+
headers = {
114+
'Content-Type': 'application/json',
115+
'Connection': 'close'
116+
}
117+
async with session.post(auth_url, json=auth_data, headers=headers) as response:
118+
result = await response.json()
119+
120+
if response.status == 200 and result.get('status') == 'success':
121+
print("✅ Remote authentication successful")
122+
123+
# Navigate to account page to verify
124+
s3_client = boto3.client('s3')
125+
s3_client.download_file('test-litewebagent', 'shopping.json', cookie_file_path)
126+
print("✅ downloaded cookies from s3")
127+
cookies_restored = await restore_cookies(browser_tab, cookie_file_path)
128+
print("✅ restored cookies")
129+
await browser_tab.goto(f"{SITE_URL}/customer/account/")
130+
await browser_tab.wait_for_load_state("networkidle")
131+
132+
# Store cookies if login succeeded
133+
# await store_cookies(browser_tab, cookie_file_path)
134+
return True
135+
else:
136+
print(f"❌ Remote authentication failed: {result.get('message', 'Unknown error')}")
137+
return False
138+
139+
except Exception as e:
140+
print(f"❌ Remote authentication error: {str(e)}")
211141
return False
212142

213143
async def check_login_status(browser_tab: Page) -> bool:

visual-tree-search-backend/app/api/shopping.json

Lines changed: 18 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,10 @@
11
[
2-
{
3-
"name": "test_cookie",
4-
"value": "1",
5-
"domain": "128.105.145.205",
6-
"path": "/",
7-
"expires": -1,
8-
"httpOnly": false,
9-
"secure": false,
10-
"sameSite": "Lax"
11-
},
122
{
133
"name": "mage-cache-storage",
144
"value": "{}",
155
"domain": "128.105.145.205",
166
"path": "/",
17-
"expires": 1775087319,
7+
"expires": 1775110732,
188
"httpOnly": false,
199
"secure": false,
2010
"sameSite": "Lax"
@@ -24,7 +14,7 @@
2414
"value": "{}",
2515
"domain": "128.105.145.205",
2616
"path": "/",
27-
"expires": 1775087319,
17+
"expires": 1775110732,
2818
"httpOnly": false,
2919
"secure": false,
3020
"sameSite": "Lax"
@@ -34,7 +24,7 @@
3424
"value": "",
3525
"domain": "128.105.145.205",
3626
"path": "/",
37-
"expires": 1775087321,
27+
"expires": 1775110735,
3828
"httpOnly": false,
3929
"secure": false,
4030
"sameSite": "Strict"
@@ -44,7 +34,7 @@
4434
"value": "{}",
4535
"domain": "128.105.145.205",
4636
"path": "/",
47-
"expires": 1775087319,
37+
"expires": 1775110732,
4838
"httpOnly": false,
4939
"secure": false,
5040
"sameSite": "Lax"
@@ -54,7 +44,7 @@
5444
"value": "{}",
5545
"domain": "128.105.145.205",
5646
"path": "/",
57-
"expires": 1775087319,
47+
"expires": 1775110732,
5848
"httpOnly": false,
5949
"secure": false,
6050
"sameSite": "Lax"
@@ -64,7 +54,7 @@
6454
"value": "{}",
6555
"domain": "128.105.145.205",
6656
"path": "/",
67-
"expires": 1775087319,
57+
"expires": 1775110732,
6858
"httpOnly": false,
6959
"secure": false,
7060
"sameSite": "Lax"
@@ -74,7 +64,7 @@
7464
"value": "{}",
7565
"domain": "128.105.145.205",
7666
"path": "/",
77-
"expires": 1775087319,
67+
"expires": 1775110732,
7868
"httpOnly": false,
7969
"secure": false,
8070
"sameSite": "Lax"
@@ -84,27 +74,27 @@
8474
"value": "{}",
8575
"domain": "128.105.145.205",
8676
"path": "/",
87-
"expires": 1775087319,
77+
"expires": 1775110732,
8878
"httpOnly": false,
8979
"secure": false,
9080
"sameSite": "Lax"
9181
},
9282
{
9383
"name": "private_content_version",
94-
"value": "f91357b9819a2a9e549670302a9b54c1",
84+
"value": "843052e37c1703f047c79850de356543",
9585
"domain": "128.105.145.205",
9686
"path": "/",
97-
"expires": 1778111320.876585,
87+
"expires": 1778134733.861287,
9888
"httpOnly": false,
9989
"secure": false,
10090
"sameSite": "Lax"
10191
},
10292
{
10393
"name": "PHPSESSID",
104-
"value": "f0197f9fa8f8c65632bd837264f9ee76",
94+
"value": "e60e354f4484dbe490e863a6e3c5b4b9",
10595
"domain": "128.105.145.205",
10696
"path": "/",
107-
"expires": 1775087322.228014,
97+
"expires": 1775110737.116277,
10898
"httpOnly": true,
10999
"secure": false,
110100
"sameSite": "Lax"
@@ -114,17 +104,17 @@
114104
"value": "9bf9a599123e6402b85cde67144717a08b817412",
115105
"domain": "128.105.145.205",
116106
"path": "/",
117-
"expires": 1775087322.228253,
107+
"expires": 1775110737.116485,
118108
"httpOnly": true,
119109
"secure": false,
120110
"sameSite": "Lax"
121111
},
122112
{
123113
"name": "form_key",
124-
"value": "g9TUo6ztR9TQFmj1",
114+
"value": "M0iOyk8VTBOyKC1q",
125115
"domain": "128.105.145.205",
126116
"path": "/",
127-
"expires": 1775087322.228177,
117+
"expires": 1775110737.116428,
128118
"httpOnly": false,
129119
"secure": false,
130120
"sameSite": "Lax"
@@ -134,17 +124,17 @@
134124
"value": "true",
135125
"domain": "128.105.145.205",
136126
"path": "/",
137-
"expires": 1775087321,
127+
"expires": 1775110735,
138128
"httpOnly": false,
139129
"secure": false,
140130
"sameSite": "Lax"
141131
},
142132
{
143133
"name": "section_data_ids",
144-
"value": "{%22messages%22:1743551322%2C%22customer%22:1743551322%2C%22compare-products%22:1743551322%2C%22last-ordered-items%22:1743551322%2C%22cart%22:1743551322%2C%22directory-data%22:1743551322%2C%22captcha%22:1743551322%2C%22instant-purchase%22:1743551322%2C%22loggedAsCustomer%22:1743551322%2C%22persistent%22:1743551322%2C%22review%22:1743551322%2C%22wishlist%22:1743551322%2C%22recently_viewed_product%22:1743551322%2C%22recently_compared_product%22:1743551322%2C%22product_data_storage%22:1743551322%2C%22paypal-billing-agreement%22:1743551322}",
134+
"value": "{%22messages%22:1743574735%2C%22customer%22:1743574735%2C%22compare-products%22:1743574735%2C%22last-ordered-items%22:1743574735%2C%22cart%22:1743574735%2C%22directory-data%22:1743574735%2C%22captcha%22:1743574735%2C%22instant-purchase%22:1743574735%2C%22loggedAsCustomer%22:1743574735%2C%22persistent%22:1743574735%2C%22review%22:1743574735%2C%22wishlist%22:1743574735%2C%22recently_viewed_product%22:1743574735%2C%22recently_compared_product%22:1743574735%2C%22product_data_storage%22:1743574735%2C%22paypal-billing-agreement%22:1743574735}",
145135
"domain": "128.105.145.205",
146136
"path": "/",
147-
"expires": 1775087321,
137+
"expires": 1775110735,
148138
"httpOnly": false,
149139
"secure": false,
150140
"sameSite": "Lax"

visual-tree-search-backend/requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,5 @@ aiolimiter==1.1.0
2323
transformers==4.34.0
2424
nltk==3.8.1
2525
browserbase
26-
aiohttp
26+
aiohttp
27+
boto3==1.34.34

0 commit comments

Comments
 (0)