AuthorizationHelpers.py 6.1 KB

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