GlobalAuth.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2015 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_External\Lib\Auth\Password;
  8. use OCA\Files_External\Lib\Auth\AuthMechanism;
  9. use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException;
  10. use OCA\Files_External\Lib\StorageConfig;
  11. use OCA\Files_External\Service\BackendService;
  12. use OCP\IL10N;
  13. use OCP\IUser;
  14. use OCP\Security\ICredentialsManager;
  15. /**
  16. * Global Username and Password
  17. */
  18. class GlobalAuth extends AuthMechanism {
  19. public const CREDENTIALS_IDENTIFIER = 'password::global';
  20. private const PWD_PLACEHOLDER = '************************';
  21. public function __construct(
  22. IL10N $l,
  23. protected ICredentialsManager $credentialsManager,
  24. ) {
  25. $this
  26. ->setIdentifier('password::global')
  27. ->setVisibility(BackendService::VISIBILITY_DEFAULT)
  28. ->setScheme(self::SCHEME_PASSWORD)
  29. ->setText($l->t('Global credentials'));
  30. }
  31. public function getAuth($uid) {
  32. $auth = $this->credentialsManager->retrieve($uid, self::CREDENTIALS_IDENTIFIER);
  33. if (!is_array($auth)) {
  34. return [
  35. 'user' => '',
  36. 'password' => ''
  37. ];
  38. } else {
  39. $auth['password'] = self::PWD_PLACEHOLDER;
  40. return $auth;
  41. }
  42. }
  43. public function saveAuth($uid, $user, $password) {
  44. // Use old password if it has not changed.
  45. if ($password === self::PWD_PLACEHOLDER) {
  46. $auth = $this->credentialsManager->retrieve($uid, self::CREDENTIALS_IDENTIFIER);
  47. $password = $auth['password'];
  48. }
  49. $this->credentialsManager->store($uid, self::CREDENTIALS_IDENTIFIER, [
  50. 'user' => $user,
  51. 'password' => $password
  52. ]);
  53. }
  54. /**
  55. * @return void
  56. */
  57. public function manipulateStorageConfig(StorageConfig &$storage, ?IUser $user = null) {
  58. if ($storage->getType() === StorageConfig::MOUNT_TYPE_ADMIN) {
  59. $uid = '';
  60. } elseif (is_null($user)) {
  61. throw new InsufficientDataForMeaningfulAnswerException('No credentials saved');
  62. } else {
  63. $uid = $user->getUID();
  64. }
  65. $credentials = $this->credentialsManager->retrieve($uid, self::CREDENTIALS_IDENTIFIER);
  66. if (is_array($credentials)) {
  67. $storage->setBackendOption('user', $credentials['user']);
  68. $storage->setBackendOption('password', $credentials['password']);
  69. }
  70. }
  71. }