KeyringAttribute.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Type, TYPE_CHECKING, Optional, List
  4. import keyring
  5. from keyring.backend import KeyringBackend
  6. from keyring.errors import NoKeyringError, PasswordSetError, KeyringLocked
  7. from UM.Logger import Logger
  8. if TYPE_CHECKING:
  9. from cura.OAuth2.Models import BaseModel
  10. # Need to do some extra workarounds on windows:
  11. import sys
  12. from UM.Platform import Platform
  13. if Platform.isWindows() and hasattr(sys, "frozen"):
  14. import win32timezone
  15. from keyring.backends.Windows import WinVaultKeyring
  16. keyring.set_keyring(WinVaultKeyring())
  17. if Platform.isOSX() and hasattr(sys, "frozen"):
  18. from keyring.backends.macOS import Keyring
  19. keyring.set_keyring(Keyring())
  20. # Even if errors happen, we don't want this stored locally:
  21. DONT_EVER_STORE_LOCALLY: List[str] = ["refresh_token"]
  22. class KeyringAttribute:
  23. """
  24. Descriptor for attributes that need to be stored in the keyring. With Fallback behaviour to the preference cfg file
  25. """
  26. def __get__(self, instance: "BaseModel", owner: type) -> Optional[str]:
  27. if self._store_secure: # type: ignore
  28. try:
  29. value = keyring.get_password("cura", self._keyring_name)
  30. return value if value != "" else None
  31. except NoKeyringError:
  32. self._store_secure = False
  33. Logger.logException("w", "No keyring backend present")
  34. return getattr(instance, self._name)
  35. except KeyringLocked:
  36. self._store_secure = False
  37. Logger.log("i", "Access to the keyring was denied.")
  38. return getattr(instance, self._name)
  39. else:
  40. return getattr(instance, self._name)
  41. def __set__(self, instance: "BaseModel", value: Optional[str]):
  42. if self._store_secure:
  43. setattr(instance, self._name, None)
  44. if value is not None:
  45. try:
  46. keyring.set_password("cura", self._keyring_name, value)
  47. except (PasswordSetError, KeyringLocked):
  48. self._store_secure = False
  49. if self._name not in DONT_EVER_STORE_LOCALLY:
  50. setattr(instance, self._name, value)
  51. Logger.logException("w", "Keyring access denied")
  52. except NoKeyringError:
  53. self._store_secure = False
  54. if self._name not in DONT_EVER_STORE_LOCALLY:
  55. setattr(instance, self._name, value)
  56. Logger.logException("w", "No keyring backend present")
  57. except BaseException as e:
  58. # A BaseException can occur in Windows when the keyring attempts to write a token longer than 1024
  59. # characters in the Windows Credentials Manager.
  60. self._store_secure = False
  61. if self._name not in DONT_EVER_STORE_LOCALLY:
  62. setattr(instance, self._name, value)
  63. Logger.log("w", "Keyring failed: {}".format(e))
  64. else:
  65. setattr(instance, self._name, value)
  66. def __set_name__(self, owner: type, name: str):
  67. self._name = "_{}".format(name)
  68. self._keyring_name = name
  69. self._store_secure = False
  70. try:
  71. self._store_secure = KeyringBackend.viable
  72. except NoKeyringError:
  73. Logger.logException("w", "Could not use keyring")
  74. setattr(owner, self._name, None)