AuthorizationService.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. # Copyright (c) 2024 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. from datetime import datetime, timedelta
  5. from typing import Callable, Dict, Optional, TYPE_CHECKING, Union
  6. from urllib.parse import urlencode, quote_plus
  7. from PyQt6.QtCore import QUrl, QTimer
  8. from PyQt6.QtGui import QDesktopServices
  9. from UM.Logger import Logger
  10. from UM.Message import Message
  11. from UM.Signal import Signal
  12. from UM.i18n import i18nCatalog
  13. from UM.TaskManagement.HttpRequestManager import HttpRequestManager # To download log-in tokens.
  14. from cura.OAuth2.AuthorizationHelpers import AuthorizationHelpers, TOKEN_TIMESTAMP_FORMAT
  15. from cura.OAuth2.LocalAuthorizationServer import LocalAuthorizationServer
  16. from cura.OAuth2.Models import AuthenticationResponse, BaseModel
  17. i18n_catalog = i18nCatalog("cura")
  18. if TYPE_CHECKING:
  19. from cura.OAuth2.Models import UserProfile, OAuth2Settings
  20. from UM.Preferences import Preferences
  21. MYCLOUD_LOGOFF_URL = "https://account.ultimaker.com/logoff?utm_source=cura&utm_medium=software&utm_campaign=change-account-before-adding-printers"
  22. REFRESH_TOKEN_MAX_RETRIES = 15
  23. REFRESH_TOKEN_RETRY_INTERVAL = 1000
  24. class AuthorizationService:
  25. """The authorization service is responsible for handling the login flow, storing user credentials and providing
  26. account information.
  27. """
  28. def __init__(self,
  29. settings: "OAuth2Settings",
  30. preferences: Optional["Preferences"] = None,
  31. get_user_profile: bool = True) -> None:
  32. # Emit signal when authentication is completed.
  33. self.onAuthStateChanged = Signal()
  34. # Emit signal when authentication failed.
  35. self.onAuthenticationError = Signal()
  36. self.accessTokenChanged = Signal()
  37. self._settings = settings
  38. self._auth_helpers = AuthorizationHelpers(settings)
  39. self._auth_url = "{}/authorize".format(self._settings.OAUTH_SERVER_URL)
  40. self._auth_data: Optional[AuthenticationResponse] = None
  41. self._user_profile: Optional["UserProfile"] = None
  42. self._get_user_profile: bool = get_user_profile
  43. self._preferences = preferences
  44. self._server = LocalAuthorizationServer(self._auth_helpers, self._onAuthStateChanged, daemon=True)
  45. self._currently_refreshing_token = False # Whether we are currently in the process of refreshing auth. Don't make new requests while busy.
  46. self._unable_to_get_data_message: Optional[Message] = None
  47. self.onAuthStateChanged.connect(self._authChanged)
  48. self._refresh_token_retries = 0
  49. self._refresh_token_retry_timer = QTimer()
  50. self._refresh_token_retry_timer.setInterval(REFRESH_TOKEN_RETRY_INTERVAL)
  51. self._refresh_token_retry_timer.setSingleShot(True)
  52. self._refresh_token_retry_timer.timeout.connect(self.refreshAccessToken)
  53. def _authChanged(self, logged_in):
  54. if logged_in and self._unable_to_get_data_message is not None:
  55. self._unable_to_get_data_message.hide()
  56. def initialize(self, preferences: Optional["Preferences"] = None) -> None:
  57. if preferences is not None:
  58. self._preferences = preferences
  59. if self._preferences:
  60. self._preferences.addPreference(self._settings.AUTH_DATA_PREFERENCE_KEY, "{}")
  61. def getUserProfile(self, callback: Optional[Callable[[Optional["UserProfile"]], None]] = None) -> None:
  62. """
  63. Get the user profile as obtained from the JWT (JSON Web Token).
  64. If the JWT is not yet checked and parsed, calling this will take care of that.
  65. :param callback: Once the user profile is obtained, this function will be called with the given user profile. If
  66. the profile fails to be obtained, this function will be called with None.
  67. See also: :py:method:`cura.OAuth2.AuthorizationService.AuthorizationService._parseJWT`
  68. """
  69. if self._user_profile:
  70. # We already obtained the profile. No need to make another request for it.
  71. if callback is not None:
  72. callback(self._user_profile)
  73. return
  74. # If no user profile was stored locally, we try to get it from JWT.
  75. def store_profile(profile: Optional["UserProfile"]) -> None:
  76. if profile is not None:
  77. self._user_profile = profile
  78. if callback is not None:
  79. callback(profile)
  80. elif self._auth_data:
  81. # If there is no user profile from the JWT, we have to log in again.
  82. Logger.warning("The user profile could not be loaded. The user must log in again!")
  83. self.deleteAuthData()
  84. if callback is not None:
  85. callback(None)
  86. else:
  87. if callback is not None:
  88. callback(None)
  89. self._parseJWT(callback = store_profile)
  90. def _parseJWT(self, callback: Callable[[Optional["UserProfile"]], None]) -> None:
  91. """
  92. Tries to parse the JWT (JSON Web Token) data, which it does if all the needed data is there.
  93. :param callback: A function to call asynchronously once the user profile has been obtained. It will be called
  94. with `None` if it failed to obtain a user profile.
  95. """
  96. if not self._auth_data or self._auth_data.access_token is None:
  97. # If no auth data exists, we should always log in again.
  98. Logger.debug("There was no auth data or access token")
  99. callback(None)
  100. return
  101. # When we checked the token we may get a user profile. This callback checks if that is a valid one and tries to refresh the token if it's not.
  102. def check_user_profile(user_profile: Optional["UserProfile"]) -> None:
  103. if user_profile:
  104. # If the profile was found, we call it back immediately.
  105. callback(user_profile)
  106. return
  107. # The JWT was expired or invalid and we should request a new one.
  108. if self._auth_data is None or self._auth_data.refresh_token is None:
  109. Logger.warning("There was no refresh token in the auth data.")
  110. callback(None)
  111. return
  112. def process_auth_data(auth_data: AuthenticationResponse) -> None:
  113. if auth_data.access_token is None:
  114. Logger.warning("Unable to use the refresh token to get a new access token.")
  115. callback(None)
  116. return
  117. # Ensure it gets stored as otherwise we only have it in memory. The stored refresh token has been
  118. # deleted from the server already. Do not store the auth_data if we could not get new auth_data (e.g.
  119. # due to a network error), since this would cause an infinite loop trying to get new auth-data.
  120. if auth_data.success:
  121. self._storeAuthData(auth_data)
  122. self._auth_helpers.checkToken(auth_data.access_token, callback, lambda: callback(None))
  123. self._auth_helpers.getAccessTokenUsingRefreshToken(self._auth_data.refresh_token, process_auth_data)
  124. self._auth_helpers.checkToken(self._auth_data.access_token, check_user_profile, lambda: check_user_profile(None))
  125. def getAccessToken(self) -> Optional[str]:
  126. """Get the access token as provided by the response data."""
  127. if self._auth_data is None:
  128. Logger.log("d", "No auth data to retrieve the access_token from")
  129. return None
  130. # Check if the current access token is expired and refresh it if that is the case.
  131. # We have a fallback on a date far in the past for currently stored auth data in cura.cfg.
  132. received_at = datetime.strptime(self._auth_data.received_at, TOKEN_TIMESTAMP_FORMAT) \
  133. if self._auth_data.received_at else datetime(2000, 1, 1)
  134. expiry_date = received_at + timedelta(seconds = float(self._auth_data.expires_in or 0) - 60)
  135. if datetime.now() > expiry_date:
  136. self.refreshAccessToken()
  137. return self._auth_data.access_token if self._auth_data else None
  138. def refreshAccessToken(self) -> None:
  139. """Try to refresh the access token. This should be used when it has expired."""
  140. if self._auth_data is None or self._auth_data.refresh_token is None:
  141. Logger.log("w", "Unable to refresh access token, since there is no refresh token.")
  142. return
  143. def process_auth_data(response: AuthenticationResponse) -> None:
  144. self._currently_refreshing_token = False
  145. if response.success:
  146. self._refresh_token_retries = 0
  147. self._storeAuthData(response)
  148. HttpRequestManager.getInstance().setDelayRequests(False)
  149. self.onAuthStateChanged.emit(logged_in = True)
  150. else:
  151. if self._refresh_token_retries >= REFRESH_TOKEN_MAX_RETRIES:
  152. self._refresh_token_retries = 0
  153. Logger.warning("Failed to get a new access token from the server, giving up.")
  154. HttpRequestManager.getInstance().setDelayRequests(False)
  155. self.onAuthStateChanged.emit(logged_in = False)
  156. else:
  157. # Retry a bit later, network may be offline right now and will hopefully be back soon
  158. Logger.warning("Failed to get a new access token from the server, retrying later.")
  159. self._refresh_token_retries += 1
  160. self._refresh_token_retry_timer.start()
  161. if self._currently_refreshing_token:
  162. Logger.debug("Was already busy refreshing token. Do not start a new request.")
  163. return
  164. HttpRequestManager.getInstance().setDelayRequests(True)
  165. self._currently_refreshing_token = True
  166. self._auth_helpers.getAccessTokenUsingRefreshToken(self._auth_data.refresh_token, process_auth_data)
  167. def deleteAuthData(self) -> None:
  168. """Delete the authentication data that we have stored locally (eg; logout)"""
  169. if self._auth_data is not None:
  170. self._storeAuthData()
  171. self.onAuthStateChanged.emit(logged_in = False)
  172. def startAuthorizationFlow(self, force_browser_logout: bool = False) -> None:
  173. """Start the flow to become authenticated. This will start a new webbrowser tap, prompting the user to login."""
  174. Logger.log("d", "Starting new OAuth2 flow...")
  175. # Create the tokens needed for the code challenge (PKCE) extension for OAuth2.
  176. # This is needed because the CuraDrivePlugin is a untrusted (open source) client.
  177. # More details can be found at https://tools.ietf.org/html/rfc7636.
  178. verification_code = self._auth_helpers.generateVerificationCode()
  179. challenge_code = self._auth_helpers.generateVerificationCodeChallenge(verification_code)
  180. state = AuthorizationHelpers.generateVerificationCode()
  181. # Create the query dict needed for the OAuth2 flow.
  182. query_parameters_dict = {
  183. "client_id": self._settings.CLIENT_ID,
  184. "redirect_uri": self._settings.CALLBACK_URL,
  185. "scope": self._settings.CLIENT_SCOPES,
  186. "response_type": "code",
  187. "state": state, # Forever in our Hearts, RIP "(.Y.)" (2018-2020)
  188. "code_challenge": challenge_code,
  189. "code_challenge_method": "S512"
  190. }
  191. # Start a local web server to receive the callback URL on.
  192. try:
  193. self._server.start(verification_code, state)
  194. except OSError:
  195. Logger.logException("w", "Unable to create authorization request server")
  196. Message(i18n_catalog.i18nc("@info",
  197. "Unable to start a new sign in process. Check if another sign in attempt is still active."),
  198. title=i18n_catalog.i18nc("@info:title", "Warning"),
  199. message_type = Message.MessageType.WARNING).show()
  200. return
  201. auth_url = self._generate_auth_url(query_parameters_dict, force_browser_logout)
  202. # Open the authorization page in a new browser window.
  203. QDesktopServices.openUrl(QUrl(auth_url))
  204. def _generate_auth_url(self, query_parameters_dict: Dict[str, Optional[str]], force_browser_logout: bool) -> str:
  205. """
  206. Generates the authentications url based on the original auth_url and the query_parameters_dict to be included.
  207. If there is a request to force logging out of mycloud in the browser, the link to logoff from mycloud is
  208. prepended in order to force the browser to logoff from mycloud and then redirect to the authentication url to
  209. login again. This case is used to sync the accounts between Cura and the browser.
  210. :param query_parameters_dict: A dictionary with the query parameters to be url encoded and added to the
  211. authentication link
  212. :param force_browser_logout: If True, Cura will prepend the MYCLOUD_LOGOFF_URL link before the authentication
  213. link to force the a browser logout from mycloud.ultimaker.com
  214. :return: The authentication URL, properly formatted and encoded
  215. """
  216. auth_url = f"{self._auth_url}?{urlencode(query_parameters_dict)}"
  217. if force_browser_logout:
  218. connecting_char = "&" if "?" in MYCLOUD_LOGOFF_URL else "?"
  219. # The url after 'next=' should be urlencoded
  220. auth_url = f"{MYCLOUD_LOGOFF_URL}{connecting_char}next={quote_plus(auth_url)}"
  221. return auth_url
  222. def _onAuthStateChanged(self, auth_response: AuthenticationResponse) -> None:
  223. """Callback method for the authentication flow."""
  224. if auth_response.success:
  225. Logger.log("d", "Got callback from Authorization state. The user should now be logged in!")
  226. self._storeAuthData(auth_response)
  227. self.onAuthStateChanged.emit(logged_in = True)
  228. else:
  229. Logger.log("d", "Got callback from Authorization state. Something went wrong: [%s]", auth_response.err_message)
  230. self.onAuthenticationError.emit(logged_in = False, error_message = auth_response.err_message)
  231. self._server.stop() # Stop the web server at all times.
  232. def loadAuthDataFromPreferences(self) -> None:
  233. """Load authentication data from preferences."""
  234. Logger.log("d", "Attempting to load the auth data from preferences.")
  235. if self._preferences is None:
  236. Logger.log("e", "Unable to load authentication data, since no preference has been set!")
  237. return
  238. try:
  239. preferences_data = json.loads(self._preferences.getValue(self._settings.AUTH_DATA_PREFERENCE_KEY))
  240. if preferences_data:
  241. self._auth_data = AuthenticationResponse(**preferences_data)
  242. # Also check if we can actually get the user profile information.
  243. def callback(profile: Optional["UserProfile"]) -> None:
  244. if profile is not None:
  245. self.onAuthStateChanged.emit(logged_in = True)
  246. Logger.debug("Auth data was successfully loaded")
  247. else:
  248. if self._unable_to_get_data_message is not None:
  249. self._unable_to_get_data_message.show()
  250. else:
  251. self._unable_to_get_data_message = Message(i18n_catalog.i18nc("@info",
  252. "Unable to reach the UltiMaker account server."),
  253. title = i18n_catalog.i18nc("@info:title", "Log-in failed"),
  254. message_type = Message.MessageType.ERROR)
  255. Logger.warning("Unable to get user profile using auth data from preferences.")
  256. self._unable_to_get_data_message.show()
  257. if self._get_user_profile:
  258. self.getUserProfile(callback)
  259. except (ValueError, TypeError):
  260. Logger.logException("w", "Could not load auth data from preferences")
  261. def _storeAuthData(self, auth_data: Optional[AuthenticationResponse] = None) -> None:
  262. """Store authentication data in preferences."""
  263. Logger.log("d", "Attempting to store the auth data for [%s]", self._settings.OAUTH_SERVER_URL)
  264. if self._preferences is None:
  265. Logger.log("e", "Unable to save authentication data, since no preference has been set!")
  266. return
  267. self._auth_data = auth_data
  268. self._currently_refreshing_token = False
  269. if auth_data:
  270. if self._get_user_profile:
  271. self.getUserProfile()
  272. self._preferences.setValue(self._settings.AUTH_DATA_PREFERENCE_KEY, json.dumps(auth_data.dump()))
  273. else:
  274. Logger.log("d", "Clearing the user profile")
  275. self._user_profile = None
  276. self._preferences.resetPreference(self._settings.AUTH_DATA_PREFERENCE_KEY)
  277. self.accessTokenChanged.emit()