AuthorizationService.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import webbrowser
  5. from datetime import datetime, timedelta
  6. from typing import Optional, TYPE_CHECKING
  7. from urllib.parse import urlencode
  8. import requests.exceptions
  9. from UM.Logger import Logger
  10. from UM.Message import Message
  11. from UM.Signal import Signal
  12. from cura.OAuth2.LocalAuthorizationServer import LocalAuthorizationServer
  13. from cura.OAuth2.AuthorizationHelpers import AuthorizationHelpers, TOKEN_TIMESTAMP_FORMAT
  14. from cura.OAuth2.Models import AuthenticationResponse
  15. from UM.i18n import i18nCatalog
  16. i18n_catalog = i18nCatalog("cura")
  17. if TYPE_CHECKING:
  18. from cura.OAuth2.Models import UserProfile, OAuth2Settings
  19. from UM.Preferences import Preferences
  20. ## The authorization service is responsible for handling the login flow,
  21. # storing user credentials and providing account information.
  22. class AuthorizationService:
  23. # Emit signal when authentication is completed.
  24. onAuthStateChanged = Signal()
  25. # Emit signal when authentication failed.
  26. onAuthenticationError = Signal()
  27. accessTokenChanged = Signal()
  28. def __init__(self, settings: "OAuth2Settings", preferences: Optional["Preferences"] = None) -> None:
  29. self._settings = settings
  30. self._auth_helpers = AuthorizationHelpers(settings)
  31. self._auth_url = "{}/authorize".format(self._settings.OAUTH_SERVER_URL)
  32. self._auth_data = None # type: Optional[AuthenticationResponse]
  33. self._user_profile = None # type: Optional["UserProfile"]
  34. self._preferences = preferences
  35. self._server = LocalAuthorizationServer(self._auth_helpers, self._onAuthStateChanged, daemon=True)
  36. self._unable_to_get_data_message = None # type: Optional[Message]
  37. self.onAuthStateChanged.connect(self._authChanged)
  38. def _authChanged(self, logged_in):
  39. if logged_in and self._unable_to_get_data_message is not None:
  40. self._unable_to_get_data_message.hide()
  41. def initialize(self, preferences: Optional["Preferences"] = None) -> None:
  42. if preferences is not None:
  43. self._preferences = preferences
  44. if self._preferences:
  45. self._preferences.addPreference(self._settings.AUTH_DATA_PREFERENCE_KEY, "{}")
  46. ## Get the user profile as obtained from the JWT (JSON Web Token).
  47. # If the JWT is not yet parsed, calling this will take care of that.
  48. # \return UserProfile if a user is logged in, None otherwise.
  49. # \sa _parseJWT
  50. def getUserProfile(self) -> Optional["UserProfile"]:
  51. if not self._user_profile:
  52. # If no user profile was stored locally, we try to get it from JWT.
  53. try:
  54. self._user_profile = self._parseJWT()
  55. except requests.exceptions.ConnectionError:
  56. # Unable to get connection, can't login.
  57. Logger.logException("w", "Unable to validate user data with the remote server.")
  58. return None
  59. if not self._user_profile and self._auth_data:
  60. # If there is still no user profile from the JWT, we have to log in again.
  61. Logger.log("w", "The user profile could not be loaded. The user must log in again!")
  62. self.deleteAuthData()
  63. return None
  64. return self._user_profile
  65. ## Tries to parse the JWT (JSON Web Token) data, which it does if all the needed data is there.
  66. # \return UserProfile if it was able to parse, None otherwise.
  67. def _parseJWT(self) -> Optional["UserProfile"]:
  68. if not self._auth_data or self._auth_data.access_token is None:
  69. # If no auth data exists, we should always log in again.
  70. Logger.log("d", "There was no auth data or access token")
  71. return None
  72. user_data = self._auth_helpers.parseJWT(self._auth_data.access_token)
  73. if user_data:
  74. # If the profile was found, we return it immediately.
  75. return user_data
  76. # The JWT was expired or invalid and we should request a new one.
  77. if self._auth_data.refresh_token is None:
  78. Logger.log("w", "There was no refresh token in the auth data.")
  79. return None
  80. self._auth_data = self._auth_helpers.getAccessTokenUsingRefreshToken(self._auth_data.refresh_token)
  81. if not self._auth_data or self._auth_data.access_token is None:
  82. Logger.log("w", "Unable to use the refresh token to get a new access token.")
  83. # The token could not be refreshed using the refresh token. We should login again.
  84. return None
  85. # Ensure it gets stored as otherwise we only have it in memory. The stored refresh token has been deleted
  86. # from the server already.
  87. self._storeAuthData(self._auth_data)
  88. return self._auth_helpers.parseJWT(self._auth_data.access_token)
  89. ## Get the access token as provided by the repsonse data.
  90. def getAccessToken(self) -> Optional[str]:
  91. if self._auth_data is None:
  92. Logger.log("d", "No auth data to retrieve the access_token from")
  93. return None
  94. # Check if the current access token is expired and refresh it if that is the case.
  95. # We have a fallback on a date far in the past for currently stored auth data in cura.cfg.
  96. received_at = datetime.strptime(self._auth_data.received_at, TOKEN_TIMESTAMP_FORMAT) \
  97. if self._auth_data.received_at else datetime(2000, 1, 1)
  98. expiry_date = received_at + timedelta(seconds = float(self._auth_data.expires_in or 0) - 60)
  99. if datetime.now() > expiry_date:
  100. self.refreshAccessToken()
  101. return self._auth_data.access_token if self._auth_data else None
  102. ## Try to refresh the access token. This should be used when it has expired.
  103. def refreshAccessToken(self) -> None:
  104. if self._auth_data is None or self._auth_data.refresh_token is None:
  105. Logger.log("w", "Unable to refresh access token, since there is no refresh token.")
  106. return
  107. response = self._auth_helpers.getAccessTokenUsingRefreshToken(self._auth_data.refresh_token)
  108. if response.success:
  109. self._storeAuthData(response)
  110. self.onAuthStateChanged.emit(logged_in = True)
  111. else:
  112. Logger.log("w", "Failed to get a new access token from the server.")
  113. self.onAuthStateChanged.emit(logged_in = False)
  114. ## Delete the authentication data that we have stored locally (eg; logout)
  115. def deleteAuthData(self) -> None:
  116. if self._auth_data is not None:
  117. self._storeAuthData()
  118. self.onAuthStateChanged.emit(logged_in = False)
  119. ## Start the flow to become authenticated. This will start a new webbrowser tap, prompting the user to login.
  120. def startAuthorizationFlow(self) -> None:
  121. Logger.log("d", "Starting new OAuth2 flow...")
  122. # Create the tokens needed for the code challenge (PKCE) extension for OAuth2.
  123. # This is needed because the CuraDrivePlugin is a untrusted (open source) client.
  124. # More details can be found at https://tools.ietf.org/html/rfc7636.
  125. verification_code = self._auth_helpers.generateVerificationCode()
  126. challenge_code = self._auth_helpers.generateVerificationCodeChallenge(verification_code)
  127. # Create the query string needed for the OAuth2 flow.
  128. query_string = urlencode({
  129. "client_id": self._settings.CLIENT_ID,
  130. "redirect_uri": self._settings.CALLBACK_URL,
  131. "scope": self._settings.CLIENT_SCOPES,
  132. "response_type": "code",
  133. "state": "(.Y.)",
  134. "code_challenge": challenge_code,
  135. "code_challenge_method": "S512"
  136. })
  137. # Open the authorization page in a new browser window.
  138. webbrowser.open_new("{}?{}".format(self._auth_url, query_string))
  139. # Start a local web server to receive the callback URL on.
  140. self._server.start(verification_code)
  141. ## Callback method for the authentication flow.
  142. def _onAuthStateChanged(self, auth_response: AuthenticationResponse) -> None:
  143. if auth_response.success:
  144. self._storeAuthData(auth_response)
  145. self.onAuthStateChanged.emit(logged_in = True)
  146. else:
  147. self.onAuthenticationError.emit(logged_in = False, error_message = auth_response.err_message)
  148. self._server.stop() # Stop the web server at all times.
  149. ## Load authentication data from preferences.
  150. def loadAuthDataFromPreferences(self) -> None:
  151. if self._preferences is None:
  152. Logger.log("e", "Unable to load authentication data, since no preference has been set!")
  153. return
  154. try:
  155. preferences_data = json.loads(self._preferences.getValue(self._settings.AUTH_DATA_PREFERENCE_KEY))
  156. if preferences_data:
  157. self._auth_data = AuthenticationResponse(**preferences_data)
  158. # Also check if we can actually get the user profile information.
  159. user_profile = self.getUserProfile()
  160. if user_profile is not None:
  161. self.onAuthStateChanged.emit(logged_in = True)
  162. else:
  163. if self._unable_to_get_data_message is not None:
  164. self._unable_to_get_data_message.hide()
  165. self._unable_to_get_data_message = Message(i18n_catalog.i18nc("@info", "Unable to reach the Ultimaker account server."), title = i18n_catalog.i18nc("@info:title", "Warning"))
  166. self._unable_to_get_data_message.addAction("retry", i18n_catalog.i18nc("@action:button", "Retry"), "[no_icon]", "[no_description]")
  167. self._unable_to_get_data_message.actionTriggered.connect(self._onMessageActionTriggered)
  168. self._unable_to_get_data_message.show()
  169. except ValueError:
  170. Logger.logException("w", "Could not load auth data from preferences")
  171. ## Store authentication data in preferences.
  172. def _storeAuthData(self, auth_data: Optional[AuthenticationResponse] = None) -> None:
  173. Logger.log("d", "Attempting to store the auth data")
  174. if self._preferences is None:
  175. Logger.log("e", "Unable to save authentication data, since no preference has been set!")
  176. return
  177. self._auth_data = auth_data
  178. if auth_data:
  179. self._user_profile = self.getUserProfile()
  180. self._preferences.setValue(self._settings.AUTH_DATA_PREFERENCE_KEY, json.dumps(vars(auth_data)))
  181. else:
  182. self._user_profile = None
  183. self._preferences.resetPreference(self._settings.AUTH_DATA_PREFERENCE_KEY)
  184. self.accessTokenChanged.emit()
  185. def _onMessageActionTriggered(self, _, action):
  186. if action == "retry":
  187. self.loadAuthDataFromPreferences()