AuthorizationHelpers.py 8.6 KB

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