AuthorizationHelpers.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from datetime import datetime
  4. import json
  5. import random
  6. from hashlib import sha512
  7. from base64 import b64encode
  8. from typing import Optional
  9. import requests
  10. from UM.i18n import i18nCatalog
  11. from UM.Logger import Logger
  12. from cura.OAuth2.Models import AuthenticationResponse, UserProfile, OAuth2Settings
  13. catalog = i18nCatalog("cura")
  14. TOKEN_TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"
  15. ## Class containing several helpers to deal with the authorization flow.
  16. class AuthorizationHelpers:
  17. def __init__(self, settings: "OAuth2Settings") -> None:
  18. self._settings = settings
  19. self._token_url = "{}/token".format(self._settings.OAUTH_SERVER_URL)
  20. @property
  21. ## The OAuth2 settings object.
  22. def settings(self) -> "OAuth2Settings":
  23. return self._settings
  24. ## Request the access token from the authorization server.
  25. # \param authorization_code: The authorization code from the 1st step.
  26. # \param verification_code: The verification code needed for the PKCE
  27. # extension.
  28. # \return An AuthenticationResponse object.
  29. def getAccessTokenUsingAuthorizationCode(self, authorization_code: str, verification_code: str) -> "AuthenticationResponse":
  30. data = {
  31. "client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
  32. "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
  33. "grant_type": "authorization_code",
  34. "code": authorization_code,
  35. "code_verifier": verification_code,
  36. "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "",
  37. }
  38. try:
  39. return self.parseTokenResponse(requests.post(self._token_url, data = data)) # type: ignore
  40. except requests.exceptions.ConnectionError:
  41. return AuthenticationResponse(success=False, err_message="Unable to connect to remote server")
  42. ## Request the access token from the authorization server using a refresh token.
  43. # \param refresh_token:
  44. # \return An AuthenticationResponse object.
  45. def getAccessTokenUsingRefreshToken(self, refresh_token: str) -> "AuthenticationResponse":
  46. Logger.log("d", "Refreshing the access token.")
  47. data = {
  48. "client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
  49. "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
  50. "grant_type": "refresh_token",
  51. "refresh_token": refresh_token,
  52. "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "",
  53. }
  54. try:
  55. return self.parseTokenResponse(requests.post(self._token_url, data = data)) # type: ignore
  56. except requests.exceptions.ConnectionError:
  57. return AuthenticationResponse(success=False, err_message="Unable to connect to remote server")
  58. @staticmethod
  59. ## Parse the token response from the authorization server into an AuthenticationResponse object.
  60. # \param token_response: The JSON string data response from the authorization server.
  61. # \return An AuthenticationResponse object.
  62. def parseTokenResponse(token_response: requests.models.Response) -> "AuthenticationResponse":
  63. token_data = None
  64. try:
  65. token_data = json.loads(token_response.text)
  66. except ValueError:
  67. Logger.log("w", "Could not parse token response data: %s", token_response.text)
  68. if not token_data:
  69. return AuthenticationResponse(success = False, err_message = catalog.i18nc("@message", "Could not read response."))
  70. if token_response.status_code not in (200, 201):
  71. return AuthenticationResponse(success = False, err_message = token_data["error_description"])
  72. return AuthenticationResponse(success=True,
  73. token_type=token_data["token_type"],
  74. access_token=token_data["access_token"],
  75. refresh_token=token_data["refresh_token"],
  76. expires_in=token_data["expires_in"],
  77. scope=token_data["scope"],
  78. received_at=datetime.now().strftime(TOKEN_TIMESTAMP_FORMAT))
  79. ## Calls the authentication API endpoint to get the token data.
  80. # \param access_token: The encoded JWT token.
  81. # \return Dict containing some profile data.
  82. def parseJWT(self, access_token: str) -> Optional["UserProfile"]:
  83. try:
  84. token_request = requests.get("{}/check-token".format(self._settings.OAUTH_SERVER_URL), headers = {
  85. "Authorization": "Bearer {}".format(access_token)
  86. })
  87. except requests.exceptions.ConnectionError:
  88. # Connection was suddenly dropped. Nothing we can do about that.
  89. Logger.logException("w", "Something failed while attempting to parse the JWT token")
  90. return None
  91. if token_request.status_code not in (200, 201):
  92. Logger.log("w", "Could not retrieve token data from auth server: %s", token_request.text)
  93. return None
  94. user_data = token_request.json().get("data")
  95. if not user_data or not isinstance(user_data, dict):
  96. Logger.log("w", "Could not parse user data from token: %s", user_data)
  97. return None
  98. return UserProfile(
  99. user_id = user_data["user_id"],
  100. username = user_data["username"],
  101. profile_image_url = user_data.get("profile_image_url", "")
  102. )
  103. @staticmethod
  104. ## Generate a 16-character verification code.
  105. # \param code_length: How long should the code be?
  106. def generateVerificationCode(code_length: int = 16) -> str:
  107. return "".join(random.choice("0123456789ABCDEF") for i in range(code_length))
  108. @staticmethod
  109. ## Generates a base64 encoded sha512 encrypted version of a given string.
  110. # \param verification_code:
  111. # \return The encrypted code in base64 format.
  112. def generateVerificationCodeChallenge(verification_code: str) -> str:
  113. encoded = sha512(verification_code.encode()).digest()
  114. return b64encode(encoded, altchars = b"_-").decode()