AuthorizationHelpers.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import random
  5. from hashlib import sha512
  6. from base64 import b64encode
  7. from typing import Dict, Optional
  8. import requests
  9. from UM.Logger import Logger
  10. from cura.OAuth2.Models import AuthenticationResponse, UserProfile, OAuth2Settings
  11. # Class containing several helpers to deal with the authorization flow.
  12. class AuthorizationHelpers:
  13. def __init__(self, settings: "OAuth2Settings") -> None:
  14. self._settings = settings
  15. self._token_url = "{}/token".format(self._settings.OAUTH_SERVER_URL)
  16. @property
  17. # The OAuth2 settings object.
  18. def settings(self) -> "OAuth2Settings":
  19. return self._settings
  20. # Gets a dictionary with data that need to be used for any HTTP authorization request.
  21. def getCommonRequestDataDict(self) -> Dict[str, str]:
  22. data_dict = {"client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
  23. "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
  24. "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "",
  25. }
  26. return data_dict
  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. # \return: An AuthenticationResponse object.
  31. def getAccessTokenUsingAuthorizationCode(self, authorization_code: str, verification_code: str) -> "AuthenticationResponse":
  32. data = self.getCommonRequestDataDict()
  33. data["grant_type"] = "authorization_code"
  34. data["code"] = authorization_code
  35. data["code_verifier"] = verification_code
  36. return self.parseTokenResponse(requests.post(self._token_url, data = data)) # type: ignore
  37. # Request the access token from the authorization server using a refresh token.
  38. # \param refresh_token:
  39. # \return: An AuthenticationResponse object.
  40. def getAccessTokenUsingRefreshToken(self, refresh_token: str) -> "AuthenticationResponse":
  41. data = self.getCommonRequestDataDict()
  42. data["grant_type"] = "refresh_token"
  43. data["refresh_token"] = refresh_token
  44. return self.parseTokenResponse(requests.post(self._token_url, data = data)) # type: ignore
  45. @staticmethod
  46. # Parse the token response from the authorization server into an AuthenticationResponse object.
  47. # \param token_response: The JSON string data response from the authorization server.
  48. # \return: An AuthenticationResponse object.
  49. def parseTokenResponse(token_response: requests.models.Response) -> "AuthenticationResponse":
  50. token_data = None
  51. try:
  52. token_data = json.loads(token_response.text)
  53. except ValueError:
  54. Logger.log("w", "Could not parse token response data: %s", token_response.text)
  55. if not token_data:
  56. return AuthenticationResponse(success=False, err_message="Could not read response.")
  57. if token_response.status_code not in (200, 201):
  58. return AuthenticationResponse(success=False, err_message=token_data["error_description"])
  59. return AuthenticationResponse(success=True,
  60. token_type=token_data["token_type"],
  61. access_token=token_data["access_token"],
  62. refresh_token=token_data["refresh_token"],
  63. expires_in=token_data["expires_in"],
  64. scope=token_data["scope"])
  65. # Calls the authentication API endpoint to get the token data.
  66. # \param access_token: The encoded JWT token.
  67. # \return: Dict containing some profile data.
  68. def parseJWT(self, access_token: str) -> Optional["UserProfile"]:
  69. token_request = requests.get("{}/check-token".format(self._settings.OAUTH_SERVER_URL), headers = {
  70. "Authorization": "Bearer {}".format(access_token)
  71. })
  72. if token_request.status_code not in (200, 201):
  73. Logger.log("w", "Could not retrieve token data from auth server: %s", token_request.text)
  74. return None
  75. user_data = token_request.json().get("data")
  76. if not user_data or not isinstance(user_data, dict):
  77. Logger.log("w", "Could not parse user data from token: %s", user_data)
  78. return None
  79. return UserProfile(
  80. user_id = user_data["user_id"],
  81. username = user_data["username"],
  82. profile_image_url = user_data.get("profile_image_url", "")
  83. )
  84. @staticmethod
  85. # Generate a 16-character verification code.
  86. # \param code_length: How long should the code be?
  87. def generateVerificationCode(code_length: int = 16) -> str:
  88. return "".join(random.choice("0123456789ABCDEF") for i in range(code_length))
  89. @staticmethod
  90. # Generates a base64 encoded sha512 encrypted version of a given string.
  91. # \param verification_code:
  92. # \return: The encrypted code in base64 format.
  93. def generateVerificationCodeChallenge(verification_code: str) -> str:
  94. encoded = sha512(verification_code.encode()).digest()
  95. return b64encode(encoded, altchars = b"_-").decode()