|
13 | 13 | from oauthlib.oauth2 import MobileApplicationClient |
14 | 14 | from requests_oauthlib import OAuth2Session |
15 | 15 |
|
| 16 | +# Required for Selenium script and for web_driver_manager |
| 17 | +import time |
| 18 | +from selenium import webdriver |
| 19 | +from selenium.webdriver.common.by import By |
| 20 | +from selenium.webdriver.support.ui import WebDriverWait |
| 21 | +from selenium.webdriver.support import expected_conditions as EC |
| 22 | + |
| 23 | +from webdriver_manager.chrome import ChromeDriverManager |
| 24 | +from webdriver_manager.firefox import GeckoDriverManager |
| 25 | +from webdriver_manager.microsoft import EdgeChromiumDriverManager |
| 26 | + |
16 | 27 | console = Console() |
17 | 28 |
|
18 | 29 |
|
@@ -111,11 +122,36 @@ def setCustomKey(self): |
111 | 122 | # Create an OAuth session and open the auth_url in a browser for the user to authenticate |
112 | 123 | stackApps = OAuth2Session(client=MobileApplicationClient(client_id=client_id), scope=scopes, redirect_uri=redirect_uri) |
113 | 124 | auth_url, state = stackApps.authorization_url(authorization_url) |
114 | | - print(f"Visit this page in your browser: {auth_url}") |
115 | | - webbrowser.open(auth_url) |
116 | 125 |
|
117 | | - # Extract the access token data and save to a variable |
118 | | - callback_url = input("Paste URL after authenticating here: ") |
| 126 | + # Try to install web drivers for one of these browsers |
| 127 | + # Chrome, Firefox, Edge (One of them must be installed) |
| 128 | + try: |
| 129 | + driver = webdriver.Chrome(ChromeDriverManager().install()) |
| 130 | + except ValueError: |
| 131 | + try: |
| 132 | + driver = webdriver.Firefox(executable_path=GeckoDriverManager().install()) |
| 133 | + except ValueError: |
| 134 | + try: |
| 135 | + driver = webdriver.Edge(EdgeChromiumDriverManager().install()) |
| 136 | + except ValueError: |
| 137 | + print("You do not have one of these supported browsers: Chrome, Firefox, Edge") |
| 138 | + |
| 139 | + # Open auth_url in one of the supported browsers |
| 140 | + driver.get(auth_url) |
| 141 | + |
| 142 | + # Close the window after 20s (Assuming that the user logs in within 30 seconds) |
| 143 | + time.sleep(30) |
| 144 | + |
| 145 | + # Close the windows as soon as authorization is done |
| 146 | + try: |
| 147 | + element = WebDriverWait(driver, 1).until( |
| 148 | + EC.presence_of_element_located((By.TAG_NAME, "h2")) |
| 149 | + ) |
| 150 | + callback_url = driver.current_url |
| 151 | + finally: |
| 152 | + driver.quit() |
| 153 | + |
| 154 | + # Extract access token data from callback_url |
119 | 155 | accessTokenData = stackApps.token_from_fragment(callback_url) |
120 | 156 |
|
121 | 157 | # Store the access token data in a dictionary |
|
0 commit comments