UltimakerCloudScope.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt6.QtNetwork import QNetworkRequest
  4. from UM.Logger import Logger
  5. from UM.TaskManagement.HttpRequestScope import DefaultUserAgentScope
  6. from typing import TYPE_CHECKING
  7. if TYPE_CHECKING:
  8. from cura.CuraApplication import CuraApplication
  9. from cura.API.Account import Account
  10. class UltimakerCloudScope(DefaultUserAgentScope):
  11. """
  12. Add an Authorization header to the request for Ultimaker Cloud Api requests, if available.
  13. Also add the user agent headers (see DefaultUserAgentScope).
  14. """
  15. def __init__(self, application: "CuraApplication", token_prefix: str = ''):
  16. super().__init__(application)
  17. api = application.getCuraAPI()
  18. self._account = api.account # type: Account
  19. self._token_prefix = token_prefix
  20. def requestHook(self, request: QNetworkRequest):
  21. super().requestHook(request)
  22. token = self._account.accessToken
  23. if not self._account.isLoggedIn or token is None:
  24. Logger.debug("User is not logged in for Cloud API request to {url}".format(url = request.url().toDisplayString()))
  25. return
  26. header_dict = {
  27. "Authorization": "Bearer {}{}".format(self._token_prefix, token)
  28. }
  29. self.addHeaders(request, header_dict)