StoragesController.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_External\Controller;
  8. use OCA\Files_External\Lib\Auth\AuthMechanism;
  9. use OCA\Files_External\Lib\Backend\Backend;
  10. use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException;
  11. use OCA\Files_External\Lib\StorageConfig;
  12. use OCA\Files_External\MountConfig;
  13. use OCA\Files_External\NotFoundException;
  14. use OCA\Files_External\Service\StoragesService;
  15. use OCP\AppFramework\Controller;
  16. use OCP\AppFramework\Http;
  17. use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired;
  18. use OCP\AppFramework\Http\DataResponse;
  19. use OCP\Files\StorageNotAvailableException;
  20. use OCP\IConfig;
  21. use OCP\IGroupManager;
  22. use OCP\IL10N;
  23. use OCP\IRequest;
  24. use OCP\IUserSession;
  25. use Psr\Log\LoggerInterface;
  26. /**
  27. * Base class for storages controllers
  28. */
  29. abstract class StoragesController extends Controller {
  30. /**
  31. * Creates a new storages controller.
  32. *
  33. * @param string $AppName application name
  34. * @param IRequest $request request object
  35. * @param IL10N $l10n l10n service
  36. * @param StoragesService $storagesService storage service
  37. * @param LoggerInterface $logger
  38. */
  39. public function __construct(
  40. $AppName,
  41. IRequest $request,
  42. protected IL10N $l10n,
  43. protected StoragesService $service,
  44. protected LoggerInterface $logger,
  45. protected IUserSession $userSession,
  46. protected IGroupManager $groupManager,
  47. protected IConfig $config,
  48. ) {
  49. parent::__construct($AppName, $request);
  50. }
  51. /**
  52. * Create a storage from its parameters
  53. *
  54. * @param string $mountPoint storage mount point
  55. * @param string $backend backend identifier
  56. * @param string $authMechanism authentication mechanism identifier
  57. * @param array $backendOptions backend-specific options
  58. * @param array|null $mountOptions mount-specific options
  59. * @param array|null $applicableUsers users for which to mount the storage
  60. * @param array|null $applicableGroups groups for which to mount the storage
  61. * @param int|null $priority priority
  62. *
  63. * @return StorageConfig|DataResponse
  64. */
  65. protected function createStorage(
  66. $mountPoint,
  67. $backend,
  68. $authMechanism,
  69. $backendOptions,
  70. $mountOptions = null,
  71. $applicableUsers = null,
  72. $applicableGroups = null,
  73. $priority = null,
  74. ) {
  75. $canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
  76. if (!$canCreateNewLocalStorage && $backend === 'local') {
  77. return new DataResponse(
  78. [
  79. 'message' => $this->l10n->t('Forbidden to manage local mounts')
  80. ],
  81. Http::STATUS_FORBIDDEN
  82. );
  83. }
  84. try {
  85. return $this->service->createStorage(
  86. $mountPoint,
  87. $backend,
  88. $authMechanism,
  89. $backendOptions,
  90. $mountOptions,
  91. $applicableUsers,
  92. $applicableGroups,
  93. $priority
  94. );
  95. } catch (\InvalidArgumentException $e) {
  96. $this->logger->error($e->getMessage(), ['exception' => $e]);
  97. return new DataResponse(
  98. [
  99. 'message' => $this->l10n->t('Invalid backend or authentication mechanism class')
  100. ],
  101. Http::STATUS_UNPROCESSABLE_ENTITY
  102. );
  103. }
  104. }
  105. /**
  106. * Validate storage config
  107. *
  108. * @param StorageConfig $storage storage config
  109. *1
  110. * @return DataResponse|null returns response in case of validation error
  111. */
  112. protected function validate(StorageConfig $storage) {
  113. $mountPoint = $storage->getMountPoint();
  114. if ($mountPoint === '') {
  115. return new DataResponse(
  116. [
  117. 'message' => $this->l10n->t('Invalid mount point'),
  118. ],
  119. Http::STATUS_UNPROCESSABLE_ENTITY
  120. );
  121. }
  122. if ($storage->getBackendOption('objectstore')) {
  123. // objectstore must not be sent from client side
  124. return new DataResponse(
  125. [
  126. 'message' => $this->l10n->t('Objectstore forbidden'),
  127. ],
  128. Http::STATUS_UNPROCESSABLE_ENTITY
  129. );
  130. }
  131. /** @var Backend */
  132. $backend = $storage->getBackend();
  133. /** @var AuthMechanism */
  134. $authMechanism = $storage->getAuthMechanism();
  135. if ($backend->checkDependencies()) {
  136. // invalid backend
  137. return new DataResponse(
  138. [
  139. 'message' => $this->l10n->t('Invalid storage backend "%s"', [
  140. $backend->getIdentifier(),
  141. ]),
  142. ],
  143. Http::STATUS_UNPROCESSABLE_ENTITY
  144. );
  145. }
  146. if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
  147. // not permitted to use backend
  148. return new DataResponse(
  149. [
  150. 'message' => $this->l10n->t('Not permitted to use backend "%s"', [
  151. $backend->getIdentifier(),
  152. ]),
  153. ],
  154. Http::STATUS_UNPROCESSABLE_ENTITY
  155. );
  156. }
  157. if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
  158. // not permitted to use auth mechanism
  159. return new DataResponse(
  160. [
  161. 'message' => $this->l10n->t('Not permitted to use authentication mechanism "%s"', [
  162. $authMechanism->getIdentifier(),
  163. ]),
  164. ],
  165. Http::STATUS_UNPROCESSABLE_ENTITY
  166. );
  167. }
  168. if (!$backend->validateStorage($storage)) {
  169. // unsatisfied parameters
  170. return new DataResponse(
  171. [
  172. 'message' => $this->l10n->t('Unsatisfied backend parameters'),
  173. ],
  174. Http::STATUS_UNPROCESSABLE_ENTITY
  175. );
  176. }
  177. if (!$authMechanism->validateStorage($storage)) {
  178. // unsatisfied parameters
  179. return new DataResponse(
  180. [
  181. 'message' => $this->l10n->t('Unsatisfied authentication mechanism parameters'),
  182. ],
  183. Http::STATUS_UNPROCESSABLE_ENTITY
  184. );
  185. }
  186. return null;
  187. }
  188. protected function manipulateStorageConfig(StorageConfig $storage) {
  189. /** @var AuthMechanism */
  190. $authMechanism = $storage->getAuthMechanism();
  191. $authMechanism->manipulateStorageConfig($storage);
  192. /** @var Backend */
  193. $backend = $storage->getBackend();
  194. $backend->manipulateStorageConfig($storage);
  195. }
  196. /**
  197. * Check whether the given storage is available / valid.
  198. *
  199. * Note that this operation can be time consuming depending
  200. * on whether the remote storage is available or not.
  201. *
  202. * @param StorageConfig $storage storage configuration
  203. * @param bool $testOnly whether to storage should only test the connection or do more things
  204. */
  205. protected function updateStorageStatus(StorageConfig &$storage, $testOnly = true) {
  206. try {
  207. $this->manipulateStorageConfig($storage);
  208. /** @var Backend */
  209. $backend = $storage->getBackend();
  210. // update status (can be time-consuming)
  211. $storage->setStatus(
  212. MountConfig::getBackendStatus(
  213. $backend->getStorageClass(),
  214. $storage->getBackendOptions(),
  215. false,
  216. $testOnly
  217. )
  218. );
  219. } catch (InsufficientDataForMeaningfulAnswerException $e) {
  220. $status = $e->getCode() ?: StorageNotAvailableException::STATUS_INDETERMINATE;
  221. $storage->setStatus(
  222. (int)$status,
  223. $this->l10n->t('Insufficient data: %s', [$e->getMessage()])
  224. );
  225. } catch (StorageNotAvailableException $e) {
  226. $storage->setStatus(
  227. (int)$e->getCode(),
  228. $this->l10n->t('%s', [$e->getMessage()])
  229. );
  230. } catch (\Exception $e) {
  231. // FIXME: convert storage exceptions to StorageNotAvailableException
  232. $storage->setStatus(
  233. StorageNotAvailableException::STATUS_ERROR,
  234. get_class($e) . ': ' . $e->getMessage()
  235. );
  236. }
  237. }
  238. /**
  239. * Get all storage entries
  240. *
  241. * @return DataResponse
  242. */
  243. public function index() {
  244. $storages = array_map(static fn ($storage) => $storage->jsonSerialize(true), $this->service->getStorages());
  245. return new DataResponse(
  246. $storages,
  247. Http::STATUS_OK
  248. );
  249. }
  250. /**
  251. * Get an external storage entry.
  252. *
  253. * @param int $id storage id
  254. * @param bool $testOnly whether to storage should only test the connection or do more things
  255. *
  256. * @return DataResponse
  257. */
  258. public function show(int $id, $testOnly = true) {
  259. try {
  260. $storage = $this->service->getStorage($id);
  261. $this->updateStorageStatus($storage, $testOnly);
  262. } catch (NotFoundException $e) {
  263. return new DataResponse(
  264. [
  265. 'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
  266. ],
  267. Http::STATUS_NOT_FOUND
  268. );
  269. }
  270. $data = $storage->jsonSerialize(true);
  271. $isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
  272. $data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAL || $isAdmin;
  273. return new DataResponse(
  274. $data,
  275. Http::STATUS_OK
  276. );
  277. }
  278. /**
  279. * Deletes the storage with the given id.
  280. *
  281. * @param int $id storage id
  282. *
  283. * @return DataResponse
  284. */
  285. #[PasswordConfirmationRequired(strict: true)]
  286. public function destroy(int $id) {
  287. try {
  288. $this->service->removeStorage($id);
  289. } catch (NotFoundException $e) {
  290. return new DataResponse(
  291. [
  292. 'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
  293. ],
  294. Http::STATUS_NOT_FOUND
  295. );
  296. }
  297. return new DataResponse([], Http::STATUS_NO_CONTENT);
  298. }
  299. }