-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbluelinktoken.py
More file actions
146 lines (127 loc) · 6.1 KB
/
bluelinktoken.py
File metadata and controls
146 lines (127 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/env uv run
# bluelinktoken.py
#
# Unified script to retrieve the refresh token for a Hyundai/Kia
# car.
#
# Original authors:
# Kia: fuatakgun (https://gist.githubusercontent.com/fuatakgun/fa4ef1e1d48b8dca2d22133d4d028dc9#gistfile1.txt)
# Hyundai: Maaxion (https://gist.github.com/Maaxion/22a38ba8fb06937da18482ddf35171ac#file-gistfile1-txt)
#
import argparse
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import requests
import time
def main():
"""
Determine brand to get the refresh token for
"""
parser = argparse.ArgumentParser()
parser.add_argument("--brand", help="Brand of vehicle (Hyundai/Kia)", type=str.lower, required=True, choices=['hyundai','kia'])
args = parser.parse_args()
"""
Populate global variables
"""
BASE_URL = f"https://idpconnect-eu.{args.brand}.com/auth/api/v2/user/oauth2/"
TOKEN_URL = f"{BASE_URL}token"
if args.brand == 'kia':
# Kia specific variables here
CLIENT_ID = "fdc85c00-0a2f-4c64-bcb4-2cfb1500730a"
CLIENT_SECRET = "secret"
REDIRECT_URL_FINAL = "https://prd.eu-ccapi.kia.com:8080/api/v1/user/oauth2/redirect"
SUCCESS_ELEMENT_SELECTOR = "a[class='logout user']"
LOGIN_URL = f"{BASE_URL}authorize?ui_locales=de&scope=openid%20profile%20email%20phone&response_type=code&client_id=peukiaidm-online-sales&redirect_uri=https://www.kia.com/api/bin/oneid/login&state=aHR0cHM6Ly93d3cua2lhLmNvbTo0NDMvZGUvP21zb2NraWQ9MjM1NDU0ODBmNmUyNjg5NDIwMmU0MDBjZjc2OTY5NWQmX3RtPTE3NTYzMTg3MjY1OTImX3RtPTE3NTYzMjQyMTcxMjY=_default"
elif args.brand == 'hyundai':
# Hyundai specific variables
CLIENT_ID = "6d477c38-3ca4-4cf3-9557-2a1929a94654"
CLIENT_SECRET = "KUy49XxPzLpLuoK0xhBC77W6VXhmtQR9iQhmIFjjoY4IpxsV"
REDIRECT_URL_FINAL = "https://prd.eu-ccapi.hyundai.com:8080/api/v1/user/oauth2/token"
SUCCESS_ELEMENT_SELECTOR = "button.mail_check"
LOGIN_URL = f"{BASE_URL}authorize?client_id=peuhyundaiidm-ctb&redirect_uri=https%3A%2F%2Fctbapi.hyundai-europe.com%2Fapi%2Fauth&nonce=&state=NL_&scope=openid+profile+email+phone&response_type=code&connector_client_id=peuhyundaiidm-ctb&connector_scope=&connector_session_key=&country=&captcha=1&ui_locales=en-US"
REDIRECT_URL = f"{BASE_URL}authorize?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URL_FINAL}&lang=de&state=ccsp"
"""
Main function to run the Selenium automation.
"""
# Initialize the Chrome WebDriver
# Make sure you have chromedriver installed and in your PATH,
# or specify the path to it.
options = webdriver.ChromeOptions()
options.add_argument("user-agent=Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19_CCS_APP_AOS")
options.add_argument("--auto-open-devtools-for-tabs")
driver = webdriver.Chrome(options=options)
driver.maximize_window()
# 1. Open the login page
print(f"Opening login page: {LOGIN_URL}")
driver.get(LOGIN_URL)
print("\n" + "="*50)
print("Please log in manually in the browser window.")
print("The script will wait for you to complete the login...")
print("="*50 + "\n")
try:
wait = WebDriverWait(driver, 300) # 300-second timeout
if args.brand == "kia":
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, SUCCESS_ELEMENT_SELECTOR)))
else:
wait.until(EC.any_of(
EC.presence_of_element_located((By.CSS_SELECTOR, SUCCESS_ELEMENT_SELECTOR)),
EC.presence_of_element_located((By.CSS_SELECTOR, "button.ctb_button"))
)
)
print("✅ Login successful! Element found.")
print(f"Redirecting to: {REDIRECT_URL}")
driver.get(REDIRECT_URL)
wait = WebDriverWait(driver, 15) # 15-second timeout
current_url = ""
tries_left = 10
redir_found = False
while (tries_left > 0):
current_url = driver.current_url
print(f" - [{11 - tries_left}] Waiting for redirect URLwith code")
if args.brand == "kia":
if re.match(r'^https://.*:8080/api/v1/user/oauth2/redirect', current_url):
redir_found = True
break
elif args.brand == "hyundai":
if re.match(r'^https://.*:8080/api/v1/user/oauth2/token', current_url):
redir_found = True
break
tries_left -= 1
time.sleep(1)
if not redir_found:
print(f"\n❌ Failed to get redirected to correct URL, got {current_url} instead")
code = re.search(
r'code=([0-9a-fA-F-]{36}\.[0-9a-fA-F-]{36}\.[0-9a-fA-F-]{36})',
current_url
).group(1)
data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URL_FINAL,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
}
session = requests.Session()
response = session.post(TOKEN_URL, data=data)
if response.status_code == 200:
tokens = response.json()
if tokens is not None:
refresh_token = tokens["refresh_token"]
access_token = tokens["access_token"]
print(f"\n✅ Your tokens are:\n\n- Refresh Token: {refresh_token}\n- Access Token: {access_token}")
else:
print(f"\n❌ Error getting tokens from der API!\n{response.text}")
except TimeoutException:
print("❌ Timed out after 5 minutes. Login was not completed or the success element was not found.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
time.sleep(3600)
finally:
print("Cleaning up and closing the browser.")
driver.quit()
if __name__ == "__main__":
main()