18 from requests.exceptions
import RequestException
23 from ...networking
import networkManager, NetworkRequestError, baseUrl
24 from ...configuration
import UserConfiguration, InvalidConfiguration, ConfigurationNotFound
27 def validateServerUrl(serverUrl: str) -> bool:
29 endpoint = baseUrl(serverUrl) +
"/info.json"
30 response = requests.get(endpoint, timeout = 5)
32 except RequestException:
36 def configureServerUrl() -> str:
37 availableChoices = [
"Official Coretex Server URL",
"Custom Server URL"]
38 selectedChoice = ui.arrowPrompt(availableChoices,
"Please select server url that you want to use (use arrow keys to select an option):")
40 if not "Official" in selectedChoice:
41 serverUrl: str = ui.clickPrompt(
"Enter server url that you wish to use", type = str)
43 while not validateServerUrl(serverUrl):
44 serverUrl = ui.clickPrompt(
"You've entered invalid server url. Please try again.", type = str)
48 return "https://api.coretex.ai/"
51 def configUser(retryCount: int = 0) -> UserConfiguration:
53 raise RuntimeError(
"Failed to authenticate. Terminating...")
55 userConfig = UserConfiguration({})
56 userConfig.serverUrl = configureServerUrl()
57 username = ui.clickPrompt(
"Email", type = str)
58 password = ui.clickPrompt(
"Password", type = str, hide_input =
True)
60 ui.progressEcho(
"Authenticating...")
61 response = networkManager.authenticate(username, password,
False)
63 if response.hasFailed():
64 ui.errorEcho(
"Failed to authenticate. Please try again...")
65 return configUser(retryCount + 1)
67 jsonResponse = response.getJson(dict)
68 userConfig.username = username
69 userConfig.password = password
70 userConfig.token = jsonResponse[
"token"]
71 userConfig.tokenExpirationDate = jsonResponse[
"expires_on"]
72 userConfig.refreshToken = jsonResponse.get(
"refresh_token")
73 userConfig.refreshTokenExpirationDate = jsonResponse.get(
"refresh_expires_on")
78 def authenticateUser(userConfig: UserConfiguration) ->
None:
79 response = networkManager.authenticate(userConfig.username, userConfig.password)
81 if response.statusCode >= 500:
82 raise NetworkRequestError(response,
"Something went wrong, please try again later.")
83 elif response.statusCode >= 400:
84 ui.errorEcho(f
"Failed to authenticate with stored credentials (Server URL: {userConfig.serverUrl}).")
85 if not ui.clickPrompt(
"Would you like to reconfigure the user? (Y/n)", type = bool, default =
True, show_default =
False):
88 userConfig.update(configUser())
90 jsonResponse = response.getJson(dict)
91 userConfig.token = jsonResponse[
"token"]
92 userConfig.tokenExpirationDate = jsonResponse[
"expires_on"]
93 userConfig.refreshToken = jsonResponse.get(
"refresh_token")
94 userConfig.refreshTokenExpirationDate = jsonResponse.get(
"refresh_expires_on")
97 def authenticateWithRefreshToken(userConfig: UserConfiguration) ->
None:
98 if not isinstance(userConfig.refreshToken, str):
99 raise TypeError(f
"Expected \"str\" received \"{type(userConfig.refreshToken)}\"")
101 response = networkManager.authenticateWithRefreshToken(userConfig.refreshToken)
103 if response.statusCode >= 500:
104 raise NetworkRequestError(response,
"Something went wrong, please try again later.")
105 elif response.statusCode >= 400:
106 authenticateUser(userConfig)
108 jsonResponse = response.getJson(dict)
109 userConfig.token = jsonResponse[
"token"]
110 userConfig.token = jsonResponse[
"expires_on"]
113 def initializeUserSession() -> None:
115 userConfig = UserConfiguration.load()
116 if userConfig.isTokenValid(
"token"):
119 if not userConfig.isTokenValid(
"token")
and userConfig.isTokenValid(
"refreshToken"):
120 authenticateWithRefreshToken(userConfig)
122 authenticateUser(userConfig)
123 except ConfigurationNotFound:
124 ui.errorEcho(
"User configuration not found.")
125 if not ui.clickPrompt(
"Would you like to configure the user? (Y/n)", type = bool, default =
True, show_default =
False):
128 userConfig = configUser()
129 except InvalidConfiguration
as ex:
130 ui.errorEcho(
"Invalid user configuration found.")
131 for error
in ex.errors:
132 ui.errorEcho(f
"{error}")
134 if not ui.clickPrompt(
"Would you like to reconfigure the user? (Y/n)", type = bool, default =
True, show_default =
False):
137 userConfig = configUser()