AuthorizationHelpers.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 PyQt5.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. "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
  35. "grant_type": "authorization_code",
  36. "code": authorization_code,
  37. "code_verifier": verification_code,
  38. "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "",
  39. }
  40. headers = {"Content-type": "application/x-www-form-urlencoded"}
  41. HttpRequestManager.getInstance().post(
  42. self._token_url,
  43. data = urllib.parse.urlencode(data).encode("UTF-8"),
  44. headers_dict = headers,
  45. callback = lambda response: self.parseTokenResponse(response, callback),
  46. error_callback = lambda response, _: self.parseTokenResponse(response, callback)
  47. )
  48. def getAccessTokenUsingRefreshToken(self, refresh_token: str, callback: Callable[[AuthenticationResponse], None]) -> None:
  49. """
  50. Request the access token from the authorization server using a refresh token.
  51. :param refresh_token: A long-lived token used to refresh the authentication token.
  52. :param callback: Once the token has been obtained, this function will be called with the response.
  53. """
  54. Logger.log("d", "Refreshing the access token for [%s]", self._settings.OAUTH_SERVER_URL)
  55. data = {
  56. "client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
  57. "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
  58. "grant_type": "refresh_token",
  59. "refresh_token": refresh_token,
  60. "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "",
  61. }
  62. headers = {"Content-type": "application/x-www-form-urlencoded"}
  63. HttpRequestManager.getInstance().post(
  64. self._token_url,
  65. data = urllib.parse.urlencode(data).encode("UTF-8"),
  66. headers_dict = headers,
  67. callback = lambda response: self.parseTokenResponse(response, callback),
  68. error_callback = lambda response, _: self.parseTokenResponse(response, callback)
  69. )
  70. def parseTokenResponse(self, token_response: QNetworkReply, callback: Callable[[AuthenticationResponse], None]) -> None:
  71. """Parse the token response from the authorization server into an AuthenticationResponse object.
  72. :param token_response: The JSON string data response from the authorization server.
  73. :return: An AuthenticationResponse object.
  74. """
  75. token_data = HttpRequestManager.readJSON(token_response)
  76. if not token_data:
  77. callback(AuthenticationResponse(success = False, err_message = catalog.i18nc("@message", "Could not read response.")))
  78. return
  79. if token_response.error() != QNetworkReply.NetworkError.NoError:
  80. callback(AuthenticationResponse(success = False, err_message = token_data["error_description"]))
  81. return
  82. callback(AuthenticationResponse(success = True,
  83. token_type = token_data["token_type"],
  84. access_token = token_data["access_token"],
  85. refresh_token = token_data["refresh_token"],
  86. expires_in = token_data["expires_in"],
  87. scope = token_data["scope"],
  88. received_at = datetime.now().strftime(TOKEN_TIMESTAMP_FORMAT)))
  89. return
  90. def checkToken(self, access_token: str, success_callback: Optional[Callable[[UserProfile], None]] = None, failed_callback: Optional[Callable[[], None]] = None) -> None:
  91. """Calls the authentication API endpoint to get the token data.
  92. The API is called asynchronously. When a response is given, the callback is called with the user's profile.
  93. :param access_token: The encoded JWT token.
  94. :param success_callback: When a response is given, this function will be called with a user profile. If None,
  95. there will not be a callback.
  96. :param failed_callback: When the request failed or the response didn't parse, this function will be called.
  97. """
  98. check_token_url = "{}/check-token".format(self._settings.OAUTH_SERVER_URL)
  99. Logger.log("d", "Checking the access token for [%s]", check_token_url)
  100. headers = {
  101. "Authorization": f"Bearer {access_token}"
  102. }
  103. HttpRequestManager.getInstance().get(
  104. check_token_url,
  105. headers_dict = headers,
  106. callback = lambda reply: self._parseUserProfile(reply, success_callback, failed_callback),
  107. error_callback = lambda _, _2: failed_callback() if failed_callback is not None else None
  108. )
  109. def _parseUserProfile(self, reply: QNetworkReply, success_callback: Optional[Callable[[UserProfile], None]], failed_callback: Optional[Callable[[], None]] = None) -> None:
  110. """
  111. Parses the user profile from a reply to /check-token.
  112. If the response is valid, the callback will be called to return the user profile to the caller.
  113. :param reply: A network reply to a request to the /check-token URL.
  114. :param success_callback: A function to call once a user profile was successfully obtained.
  115. :param failed_callback: A function to call if parsing the profile failed.
  116. """
  117. if reply.error() != QNetworkReply.NetworkError.NoError:
  118. Logger.warning(f"Could not access account information. QNetworkError {reply.errorString()}")
  119. if failed_callback is not None:
  120. failed_callback()
  121. return
  122. profile_data = HttpRequestManager.getInstance().readJSON(reply)
  123. if profile_data is None or "data" not in profile_data:
  124. Logger.warning("Could not parse user data from token.")
  125. if failed_callback is not None:
  126. failed_callback()
  127. return
  128. profile_data = profile_data["data"]
  129. required_fields = {"user_id", "username"}
  130. if "user_id" not in profile_data or "username" not in profile_data:
  131. Logger.warning(f"User data missing required field(s): {required_fields - set(profile_data.keys())}")
  132. if failed_callback is not None:
  133. failed_callback()
  134. return
  135. if success_callback is not None:
  136. success_callback(UserProfile(
  137. user_id = profile_data["user_id"],
  138. username = profile_data["username"],
  139. profile_image_url = profile_data.get("profile_image_url", ""),
  140. organization_id = profile_data.get("organization", {}).get("organization_id"),
  141. subscriptions = profile_data.get("subscriptions", [])
  142. ))
  143. @staticmethod
  144. def generateVerificationCode(code_length: int = 32) -> str:
  145. """Generate a verification code of arbitrary length.
  146. :param code_length:: How long should the code be in bytes? This should never be lower than 16, but it's probably
  147. better to leave it at 32
  148. """
  149. return secrets.token_hex(code_length)
  150. @staticmethod
  151. def generateVerificationCodeChallenge(verification_code: str) -> str:
  152. """Generates a base64 encoded sha512 encrypted version of a given string.
  153. :param verification_code:
  154. :return: The encrypted code in base64 format.
  155. """
  156. encoded = sha512(verification_code.encode()).digest()
  157. return b64encode(encoded, altchars = b"_-").decode()