AuthorizationHelpers.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 AuthorizationHelpers:
  16. """Class containing several helpers to deal with the authorization flow."""
  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. def settings(self) -> "OAuth2Settings":
  22. """The OAuth2 settings object."""
  23. return self._settings
  24. def getAccessTokenUsingAuthorizationCode(self, authorization_code: str, verification_code: str) -> "AuthenticationResponse":
  25. """Request the access token from the authorization server.
  26. :param authorization_code: The authorization code from the 1st step.
  27. :param verification_code: The verification code needed for the PKCE extension.
  28. :return: An AuthenticationResponse object.
  29. """
  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. def getAccessTokenUsingRefreshToken(self, refresh_token: str) -> "AuthenticationResponse":
  43. """Request the access token from the authorization server using a refresh token.
  44. :param refresh_token:
  45. :return: An AuthenticationResponse object.
  46. """
  47. Logger.log("d", "Refreshing the access token.")
  48. data = {
  49. "client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
  50. "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
  51. "grant_type": "refresh_token",
  52. "refresh_token": refresh_token,
  53. "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "",
  54. }
  55. try:
  56. return self.parseTokenResponse(requests.post(self._token_url, data = data)) # type: ignore
  57. except requests.exceptions.ConnectionError:
  58. return AuthenticationResponse(success=False, err_message="Unable to connect to remote server")
  59. @staticmethod
  60. def parseTokenResponse(token_response: requests.models.Response) -> "AuthenticationResponse":
  61. """Parse the token response from the authorization server into an AuthenticationResponse object.
  62. :param token_response: The JSON string data response from the authorization server.
  63. :return: An AuthenticationResponse object.
  64. """
  65. token_data = None
  66. try:
  67. token_data = json.loads(token_response.text)
  68. except ValueError:
  69. Logger.log("w", "Could not parse token response data: %s", token_response.text)
  70. if not token_data:
  71. return AuthenticationResponse(success = False, err_message = catalog.i18nc("@message", "Could not read response."))
  72. if token_response.status_code not in (200, 201):
  73. return AuthenticationResponse(success = False, err_message = token_data["error_description"])
  74. return AuthenticationResponse(success=True,
  75. token_type=token_data["token_type"],
  76. access_token=token_data["access_token"],
  77. refresh_token=token_data["refresh_token"],
  78. expires_in=token_data["expires_in"],
  79. scope=token_data["scope"],
  80. received_at=datetime.now().strftime(TOKEN_TIMESTAMP_FORMAT))
  81. def parseJWT(self, access_token: str) -> Optional["UserProfile"]:
  82. """Calls the authentication API endpoint to get the token data.
  83. :param access_token: The encoded JWT token.
  84. :return: Dict containing some profile data.
  85. """
  86. try:
  87. token_request = requests.get("{}/check-token".format(self._settings.OAUTH_SERVER_URL), headers = {
  88. "Authorization": "Bearer {}".format(access_token)
  89. })
  90. except requests.exceptions.ConnectionError:
  91. # Connection was suddenly dropped. Nothing we can do about that.
  92. Logger.logException("w", "Something failed while attempting to parse the JWT token")
  93. return None
  94. if token_request.status_code not in (200, 201):
  95. Logger.log("w", "Could not retrieve token data from auth server: %s", token_request.text)
  96. return None
  97. user_data = token_request.json().get("data")
  98. if not user_data or not isinstance(user_data, dict):
  99. Logger.log("w", "Could not parse user data from token: %s", user_data)
  100. return None
  101. return UserProfile(
  102. user_id = user_data["user_id"],
  103. username = user_data["username"],
  104. profile_image_url = user_data.get("profile_image_url", "")
  105. )
  106. @staticmethod
  107. def generateVerificationCode(code_length: int = 32) -> str:
  108. """Generate a verification code of arbitrary length.
  109. :param code_length:: How long should the code be? This should never be lower than 16, but it's probably
  110. better to leave it at 32
  111. """
  112. return "".join(random.choice("0123456789ABCDEF") for i in range(code_length))
  113. @staticmethod
  114. def generateVerificationCodeChallenge(verification_code: str) -> str:
  115. """Generates a base64 encoded sha512 encrypted version of a given string.
  116. :param verification_code:
  117. :return: The encrypted code in base64 format.
  118. """
  119. encoded = sha512(verification_code.encode()).digest()
  120. return b64encode(encoded, altchars = b"_-").decode()