AuthorizationService.py 9.7 KB

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