AuthorizationHelpers.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from base64 import b64encode
  4. from datetime import datetime
  5. from hashlib import sha512
  6. from PyQt6.QtNetwork import QNetworkReply
  7. import secrets
  8. from typing import Callable, Optional
  9. import urllib.parse
  10. from cura.OAuth2.Models import AuthenticationResponse, UserProfile, OAuth2Settings
  11. from UM.i18n import i18nCatalog
  12. from UM.Logger import Logger
  13. from UM.TaskManagement.HttpRequestManager import HttpRequestManager # To download log-in tokens.
  14. catalog = i18nCatalog("cura")
  15. TOKEN_TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"
  16. class AuthorizationHelpers:
  17. """Class containing several helpers to deal with the authorization flow."""
  18. def __init__(self, settings: "OAuth2Settings") -> None:
  19. self._settings = settings
  20. self._token_url = "{}/token".format(self._settings.OAUTH_SERVER_URL)
  21. @property
  22. def settings(self) -> "OAuth2Settings":
  23. """The OAuth2 settings object."""
  24. return self._settings
  25. def getAccessTokenUsingAuthorizationCode(self, authorization_code: str, verification_code: str, callback: Callable[[AuthenticationResponse], None]) -> None:
  26. """
  27. Request the access token from the authorization server.
  28. :param authorization_code: The authorization code from the 1st step.
  29. :param verification_code: The verification code needed for the PKCE extension.
  30. :param callback: Once the token has been obtained, this function will be called with the response.
  31. """
  32. data = {
  33. "client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
  34. "client_secret": self._settings.CLIENT_SECRET if self._settings.CLIENT_SECRET is not None else "",
  35. "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
  36. "grant_type": "authorization_code",
  37. "code": authorization_code,
  38. "code_verifier": verification_code,
  39. "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "",
  40. }
  41. headers = {"Content-type": "application/x-www-form-urlencoded"}
  42. HttpRequestManager.getInstance().post(
  43. self._token_url,
  44. data = urllib.parse.urlencode(data).encode("UTF-8"),
  45. headers_dict = headers,
  46. callback = lambda response: self.parseTokenResponse(response, callback),
  47. error_callback = lambda response, _: self.parseTokenResponse(response, callback)
  48. )
  49. def getAccessTokenUsingRefreshToken(self, refresh_token: str, callback: Callable[[AuthenticationResponse], None]) -> None:
  50. """
  51. Request the access token from the authorization server using a refresh token.
  52. :param refresh_token: A long-lived token used to refresh the authentication token.
  53. :param callback: Once the token has been obtained, this function will be called with the response.
  54. """
  55. Logger.log("d", "Refreshing the access token for [%s]", self._settings.OAUTH_SERVER_URL)
  56. data = {
  57. "client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
  58. "client_secret": self._settings.CLIENT_SECRET if self._settings.CLIENT_SECRET is not None else "",
  59. "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
  60. "grant_type": "refresh_token",
  61. "refresh_token": refresh_token,
  62. "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "",
  63. }
  64. headers = {"Content-type": "application/x-www-form-urlencoded"}
  65. HttpRequestManager.getInstance().post(
  66. self._token_url,
  67. data = urllib.parse.urlencode(data).encode("UTF-8"),
  68. headers_dict = headers,
  69. callback = lambda response: self.parseTokenResponse(response, callback),
  70. error_callback = lambda response, _: self.parseTokenResponse(response, callback)
  71. )
  72. def parseTokenResponse(self, token_response: QNetworkReply, callback: Callable[[AuthenticationResponse], None]) -> None:
  73. """Parse the token response from the authorization server into an AuthenticationResponse object.
  74. :param token_response: The JSON string data response from the authorization server.
  75. :return: An AuthenticationResponse object.
  76. """
  77. token_data = HttpRequestManager.readJSON(token_response)
  78. if not token_data:
  79. callback(AuthenticationResponse(success = False, err_message = catalog.i18nc("@message", "Could not read response.")))
  80. return
  81. if token_response.error() != QNetworkReply.NetworkError.NoError:
  82. callback(AuthenticationResponse(success = False, err_message = token_data["error_description"]))
  83. return
  84. callback(AuthenticationResponse(success = True,
  85. token_type = token_data["token_type"],
  86. access_token = token_data["access_token"],
  87. refresh_token = token_data["refresh_token"],
  88. expires_in = token_data["expires_in"],
  89. scope = token_data["scope"],
  90. received_at = datetime.now().strftime(TOKEN_TIMESTAMP_FORMAT)))
  91. return
  92. def checkToken(self, access_token: str, success_callback: Optional[Callable[[UserProfile], None]] = None, failed_callback: Optional[Callable[[], None]] = None) -> None:
  93. """Calls the authentication API endpoint to get the token data.
  94. The API is called asynchronously. When a response is given, the callback is called with the user's profile.
  95. :param access_token: The encoded JWT token.
  96. :param success_callback: When a response is given, this function will be called with a user profile. If None,
  97. there will not be a callback.
  98. :param failed_callback: When the request failed or the response didn't parse, this function will be called.
  99. """
  100. check_token_url = "{}/check-token".format(self._settings.OAUTH_SERVER_URL)
  101. Logger.log("d", "Checking the access token for [%s]", check_token_url)
  102. headers = {
  103. "Authorization": f"Bearer {access_token}"
  104. }
  105. HttpRequestManager.getInstance().get(
  106. check_token_url,
  107. headers_dict = headers,
  108. callback = lambda reply: self._parseUserProfile(reply, success_callback, failed_callback),
  109. error_callback = lambda _, _2: failed_callback() if failed_callback is not None else None
  110. )
  111. def _parseUserProfile(self, reply: QNetworkReply, success_callback: Optional[Callable[[UserProfile], None]], failed_callback: Optional[Callable[[], None]] = None) -> None:
  112. """
  113. Parses the user profile from a reply to /check-token.
  114. If the response is valid, the callback will be called to return the user profile to the caller.
  115. :param reply: A network reply to a request to the /check-token URL.
  116. :param success_callback: A function to call once a user profile was successfully obtained.
  117. :param failed_callback: A function to call if parsing the profile failed.
  118. """
  119. if reply.error() != QNetworkReply.NetworkError.NoError:
  120. Logger.warning(f"Could not access account information. QNetworkError {reply.errorString()}")
  121. if failed_callback is not None:
  122. failed_callback()
  123. return
  124. profile_data = HttpRequestManager.getInstance().readJSON(reply)
  125. if profile_data is None or "data" not in profile_data:
  126. Logger.warning("Could not parse user data from token.")
  127. if failed_callback is not None:
  128. failed_callback()
  129. return
  130. profile_data = profile_data["data"]
  131. required_fields = {"user_id", "username"}
  132. if "user_id" not in profile_data or "username" not in profile_data:
  133. Logger.warning(f"User data missing required field(s): {required_fields - set(profile_data.keys())}")
  134. if failed_callback is not None:
  135. failed_callback()
  136. return
  137. if success_callback is not None:
  138. success_callback(UserProfile(
  139. user_id = profile_data["user_id"],
  140. username = profile_data["username"],
  141. profile_image_url = profile_data.get("profile_image_url", ""),
  142. organization_id = profile_data.get("organization", {}).get("organization_id"),
  143. subscriptions = profile_data.get("subscriptions", [])
  144. ))
  145. @staticmethod
  146. def generateVerificationCode(code_length: int = 32) -> str:
  147. """Generate a verification code of arbitrary length.
  148. :param code_length:: How long should the code be in bytes? This should never be lower than 16, but it's probably
  149. better to leave it at 32
  150. """
  151. return secrets.token_hex(code_length)
  152. @staticmethod
  153. def generateVerificationCodeChallenge(verification_code: str) -> str:
  154. """Generates a base64 encoded sha512 encrypted version of a given string.
  155. :param verification_code:
  156. :return: The encrypted code in base64 format.
  157. """
  158. encoded = sha512(verification_code.encode()).digest()
  159. return b64encode(encoded, altchars = b"_-").decode()