From f5d0b464a718a32d78226836417c7ab35203f275 Mon Sep 17 00:00:00 2001 From: Björn Schießle Date: Mon, 23 May 2016 11:48:14 +0200 Subject: create a real federated share if a user add a public link to his ownCloud this way the owner sees all mounted public links and control them individually --- apps/federatedfilesharing/appinfo/app.php | 2 +- apps/federatedfilesharing/appinfo/routes.php | 26 +++++++ .../lib/AppInfo/Application.php | 4 + .../lib/Controller/SaveToOwnCloudController.php | 88 ++++++++++++++++++++++ .../lib/FederatedShareProvider.php | 8 +- apps/files_sharing/js/public.js | 73 ++++++++---------- apps/files_sharing/templates/public.php | 2 +- 7 files changed, 156 insertions(+), 47 deletions(-) create mode 100644 apps/federatedfilesharing/appinfo/routes.php create mode 100644 apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php (limited to 'apps') diff --git a/apps/federatedfilesharing/appinfo/app.php b/apps/federatedfilesharing/appinfo/app.php index 5891b9cbbc1..8abdf8cac19 100644 --- a/apps/federatedfilesharing/appinfo/app.php +++ b/apps/federatedfilesharing/appinfo/app.php @@ -20,7 +20,7 @@ * */ -$app = new \OCA\FederatedFileSharing\AppInfo\Application('federatedfilesharing'); +$app = new \OCA\FederatedFileSharing\AppInfo\Application(); use OCA\FederatedFileSharing\Notifier; diff --git a/apps/federatedfilesharing/appinfo/routes.php b/apps/federatedfilesharing/appinfo/routes.php new file mode 100644 index 00000000000..534733e001f --- /dev/null +++ b/apps/federatedfilesharing/appinfo/routes.php @@ -0,0 +1,26 @@ + + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +return [ + 'routes' => [ + ['name' => 'SaveToOwnCloud#saveToOwnCloud', 'url' => '/saveToOwnCloud', 'verb' => 'POST'], + ] +]; diff --git a/apps/federatedfilesharing/lib/AppInfo/Application.php b/apps/federatedfilesharing/lib/AppInfo/Application.php index 4faebea7b0a..ea5018e6a90 100644 --- a/apps/federatedfilesharing/lib/AppInfo/Application.php +++ b/apps/federatedfilesharing/lib/AppInfo/Application.php @@ -31,6 +31,10 @@ class Application extends App { /** @var FederatedShareProvider */ protected $federatedShareProvider; + public function __construct() { + parent::__construct('federatedfilesharing'); + } + /** * register personal and admin settings page */ diff --git a/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php b/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php new file mode 100644 index 00000000000..a20806e6abb --- /dev/null +++ b/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php @@ -0,0 +1,88 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + + +namespace OCA\FederatedFileSharing\Controller; + +use OC\HintException; +use OCA\FederatedFileSharing\AddressHandler; +use OCA\FederatedFileSharing\FederatedShareProvider; +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\JSONResponse; +use OCP\IRequest; +use OCP\Share\IManager; + +class SaveToOwnCloudController extends Controller { + + /** @var FederatedShareProvider */ + private $federatedShareProvider; + + /** @var AddressHandler */ + private $addressHandler; + + /** @var IManager */ + private $shareManager; + + public function __construct($appName, + IRequest $request, + FederatedShareProvider $federatedShareProvider, + IManager $shareManager, + AddressHandler $addressHandler) { + parent::__construct($appName, $request); + + $this->federatedShareProvider = $federatedShareProvider; + $this->shareManager = $shareManager; + $this->addressHandler = $addressHandler; + } + + /** + * save public link to my ownCloud by asking the owner to create a federated + * share with me + * + * @NoCSRFRequired + * @PublicPage + * + * @param string $shareWith + * @param string $token + * @return JSONResponse + */ + public function saveToOwnCloud($shareWith, $token) { + + try { + list(, $server) = $this->addressHandler->splitUserRemote($shareWith); + $share = $this->shareManager->getShareByToken($token); + } catch (HintException $e) { + return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST); + } + + $share->setSharedWith($shareWith); + + try { + $this->federatedShareProvider->create($share); + } catch (\Exception $e) { + return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); + } + + return new JSONResponse(['remoteUrl' => $server]); + } + +} diff --git a/apps/federatedfilesharing/lib/FederatedShareProvider.php b/apps/federatedfilesharing/lib/FederatedShareProvider.php index 1ea31f2dbc0..7b64b56a16d 100644 --- a/apps/federatedfilesharing/lib/FederatedShareProvider.php +++ b/apps/federatedfilesharing/lib/FederatedShareProvider.php @@ -135,7 +135,7 @@ class FederatedShareProvider implements IShareProvider { $itemType = $share->getNodeType(); $permissions = $share->getPermissions(); $sharedBy = $share->getSharedBy(); - + /* * Check if file is not already shared with the remote user */ @@ -626,7 +626,7 @@ class FederatedShareProvider implements IShareProvider { ->from('share') ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))) ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))); - + $cursor = $qb->execute(); $data = $cursor->fetch(); $cursor->closeCursor(); @@ -727,13 +727,13 @@ class FederatedShareProvider implements IShareProvider { $data = $cursor->fetch(); if ($data === false) { - throw new ShareNotFound(); + throw new ShareNotFound('Share not found', $this->l->t('Could not find share')); } try { $share = $this->createShareObject($data); } catch (InvalidShare $e) { - throw new ShareNotFound(); + throw new ShareNotFound('Share not found', $this->l->t('Could not find share')); } return $share; diff --git a/apps/files_sharing/js/public.js b/apps/files_sharing/js/public.js index 3befeaeda1f..38dc40eeb1e 100644 --- a/apps/files_sharing/js/public.js +++ b/apps/files_sharing/js/public.js @@ -244,10 +244,8 @@ OCA.Sharing.PublicApp = { var remote = $(this).find('input[type="text"]').val(); var token = $('#sharingToken').val(); var owner = $('#save').data('owner'); - var ownerDisplayName = $('#save').data('owner-display-name'); var name = $('#save').data('name'); - var isProtected = $('#save').data('protected') ? 1 : 0; - OCA.Sharing.PublicApp._saveToOwnCloud(remote, token, owner, ownerDisplayName, name, isProtected); + OCA.Sharing.PublicApp._saveToOwnCloud(remote, token); }); $('#remote_address').on("keyup paste", function() { @@ -294,50 +292,43 @@ OCA.Sharing.PublicApp = { this.fileList.changeDirectory(params.path || params.dir, false, true); }, - _saveToOwnCloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { - var toggleLoading = function() { - var iconClass = $('#save-button-confirm').attr('class'); - var loading = iconClass.indexOf('icon-loading-small') !== -1; - if(loading) { - $('#save-button-confirm') - .removeClass("icon-loading-small") - .addClass("icon-confirm"); - } - else { - $('#save-button-confirm') - .removeClass("icon-confirm") - .addClass("icon-loading-small"); + _saveToOwnCloud: function (remote, token) { + $.post( + OC.generateUrl('/apps/federatedfilesharing/saveToOwnCloud'), + { + 'shareWith': remote, + 'token': token } - }; - - toggleLoading(); - var location = window.location.protocol + '//' + window.location.host + OC.webroot; - - if(remote.substr(-1) !== '/') { - remote += '/' - }; - - var url = remote + 'index.php/apps/files#' + 'remote=' + encodeURIComponent(location) // our location is the remote for the other server - + "&token=" + encodeURIComponent(token) + "&owner=" + encodeURIComponent(owner) +"&ownerDisplayName=" + encodeURIComponent(ownerDisplayName) + "&name=" + encodeURIComponent(name) + "&protected=" + isProtected; + ).done( + function (data) { + var url = data.remoteUrl; - - if (remote.indexOf('://') > 0) { - OC.redirect(url); - } else { - // if no protocol is specified, we automatically detect it by testing https and http - // this check needs to happen on the server due to the Content Security Policy directive - $.get(OC.generateUrl('apps/files_sharing/testremote'), {remote: remote}).then(function (protocol) { - if (protocol !== 'http' && protocol !== 'https') { - toggleLoading(); - OC.dialogs.alert(t('files_sharing', 'No compatible server found at {remote}', {remote: remote}), - t('files_sharing', 'Invalid server URL')); + if (url.indexOf('://') > 0) { + OC.redirect(url); } else { - OC.redirect(protocol + '://' + url); + // if no protocol is specified, we automatically detect it by testing https and http + // this check needs to happen on the server due to the Content Security Policy directive + $.get(OC.generateUrl('apps/files_sharing/testremote'), {remote: remote}).then(function (protocol) { + if (protocol !== 'http' && protocol !== 'https') { + toggleLoading(); + OC.dialogs.alert(t('files_sharing', 'No ownCloud installation (7 or higher) found at {remote}', {remote: remote}), + t('files_sharing', 'Invalid ownCloud url')); + } else { + OC.redirect(protocol + '://' + url); + } + }); } - }); - } + } + ).fail( + function (jqXHR) { + console.log("ERROR!"); + console.log(jqXHR); + OC.dialogs.alert(JSON.parse(jqXHR.responseText).message, + t('files_sharing', 'Failed to add the public link to your ownCloud')); + } + ); } }; diff --git a/apps/files_sharing/templates/public.php b/apps/files_sharing/templates/public.php index c15001ad24b..8b8267a4e3f 100644 --- a/apps/files_sharing/templates/public.php +++ b/apps/files_sharing/templates/public.php @@ -84,7 +84,7 @@ $maxUploadFilesize = min($upload_max_filesize, $post_max_size); data-owner-display-name="" data-owner="" data-name=""> -- cgit v1.2.3 From a0ae16aa1ab717613a11083868a4856795413991 Mon Sep 17 00:00:00 2001 From: Björn Schießle Date: Mon, 23 May 2016 14:57:22 +0200 Subject: add unit tests --- .../Controller/SaveToOwnCloudControllerTest.php | 161 +++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php (limited to 'apps') diff --git a/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php b/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php new file mode 100644 index 00000000000..24bc18d5644 --- /dev/null +++ b/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php @@ -0,0 +1,161 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + + +namespace OCA\FederatedFileSharing\Tests\Controller; + +use OC\HintException; +use OCA\FederatedFileSharing\AddressHandler; +use OCA\FederatedFileSharing\Controller\SaveToOwnCloudController; +use OCA\FederatedFileSharing\FederatedShareProvider; +use OCP\AppFramework\Http; +use OCP\Files\IRootFolder; +use OCP\IUserManager; +use OCP\Share; +use OCP\Share\IManager; +use OCP\Share\IShare; + +class SaveToOwnCloudControllerTest extends \Test\TestCase { + + /** @var SaveToOwnCloudController */ + private $controller; + + /** @var \OCP\IRequest | \PHPUnit_Framework_MockObject_MockObject */ + private $request; + + /** @var FederatedShareProvider | \PHPUnit_Framework_MockObject_MockObject */ + private $federatedShareProvider; + + /** @var IManager | \PHPUnit_Framework_MockObject_MockObject */ + private $shareManager; + + /** @var AddressHandler | \PHPUnit_Framework_MockObject_MockObject */ + private $addressHandler; + + /** @var IRootFolder | \PHPUnit_Framework_MockObject_MockObject */ + private $rootFolder; + + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */ + private $userManager; + + /** @var IShare */ + private $share; + + public function setUp() { + parent::setUp(); + + $this->request = $this->getMock('OCP\IRequest'); + $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') + ->disableOriginalConstructor()->getMock(); + $this->shareManager = $this->getMock('OCP\Share\IManager'); + $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') + ->disableOriginalConstructor()->getMock(); + $this->rootFolder = $this->getMock('OCP\Files\IRootFolder'); + $this->userManager = $this->getMock('OCP\IUserManager'); + $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); + + $this->controller = new SaveToOwnCloudController( + 'federatedfilesharing', $this->request, + $this->federatedShareProvider, + $this->shareManager, + $this->addressHandler + ); + } + + /** + * @dataProvider dataTestSaveToOwnCloud + * + * @param string $shareWith + * @param bool $validShareWith + * @param string $token + * @param bool $validToken + * @param bool $createSuccessful + * @param string $expectedReturnData + */ + public function testSaveToOwnCloud($shareWith, $validShareWith, $token, $validToken, $createSuccessful, $expectedReturnData) { + $this->addressHandler->expects($this->any())->method('splitUserRemote') + ->with($shareWith) + ->willReturnCallback( + function($shareWith) use ($validShareWith, $expectedReturnData) { + if ($validShareWith) { + return ['user', 'server']; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $share = $this->share; + + $this->shareManager->expects($this->any())->method('getShareByToken') + ->with($token) + ->willReturnCallback( + function ($token) use ($validToken, $share, $expectedReturnData) { + if ($validToken) { + return $share; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $this->federatedShareProvider->expects($this->any())->method('create') + ->with($share) + ->willReturnCallback( + function (IShare $share) use ($createSuccessful, $shareWith, $expectedReturnData) { + $this->assertEquals($shareWith, $share->getSharedWith()); + if ($createSuccessful) { + return $share; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $result = $this->controller->saveToOwnCloud($shareWith, $token); + + $errorCase = !$validShareWith || !$validToken || !$createSuccessful; + + if ($errorCase) { + $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus()); + $this->assertTrue(isset($result->getData()['message'])); + $this->assertSame($expectedReturnData, $result->getData()['message']); + } else { + $this->assertSame(Http::STATUS_OK, $result->getStatus()); + $this->assertTrue(isset($result->getData()['remoteUrl'])); + $this->assertSame($expectedReturnData, $result->getData()['remoteUrl']); + + } + + } + + public function dataTestSaveToOwnCloud() { + return [ + //shareWith, validShareWith, token, validToken, createSuccessful, expectedReturnData + ['user@server', true, 'token', true, true, 'server'], + ['user@server', false, 'token', true, true, 'invalid federated cloud id'], + ['user@server', false, 'token', false, true, 'invalid federated cloud id'], + ['user@server', false, 'token', false, false, 'invalid federated cloud id'], + ['user@server', false, 'token', true, false, 'invalid federated cloud id'], + ['user@server', true, 'token', false, true, 'invalid token'], + ['user@server', true, 'token', false, false, 'invalid token'], + ['user@server', true, 'token', true, false, 'can not create share'] + ]; + } + +} -- cgit v1.2.3 From 1394b0afb9b1d3d7c8952faea85873e731ccb801 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Tue, 12 Jul 2016 12:04:41 +0200 Subject: replace 'ownCloud' with 'Nextcloud' --- apps/files_sharing/js/public.js | 2 +- apps/files_sharing/templates/public.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'apps') diff --git a/apps/files_sharing/js/public.js b/apps/files_sharing/js/public.js index 38dc40eeb1e..d4f3bd36a63 100644 --- a/apps/files_sharing/js/public.js +++ b/apps/files_sharing/js/public.js @@ -313,7 +313,7 @@ OCA.Sharing.PublicApp = { $.get(OC.generateUrl('apps/files_sharing/testremote'), {remote: remote}).then(function (protocol) { if (protocol !== 'http' && protocol !== 'https') { toggleLoading(); - OC.dialogs.alert(t('files_sharing', 'No ownCloud installation (7 or higher) found at {remote}', {remote: remote}), + OC.dialogs.alert(t('files_sharing', 'No Nextcloud installation (7 or higher) found at {remote}', {remote: remote}), t('files_sharing', 'Invalid ownCloud url')); } else { OC.redirect(protocol + '://' + url); diff --git a/apps/files_sharing/templates/public.php b/apps/files_sharing/templates/public.php index 8b8267a4e3f..8a906f02a7e 100644 --- a/apps/files_sharing/templates/public.php +++ b/apps/files_sharing/templates/public.php @@ -82,9 +82,9 @@ $maxUploadFilesize = min($upload_max_filesize, $post_max_size); ?> - + -- cgit v1.2.3 From 33a685bc41628e1236015bd79cc8f82b9cb6cabf Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Tue, 12 Jul 2016 14:03:29 +0200 Subject: continue to accept the URL of the remote server instead of the federated cloud id --- .../lib/Controller/SaveToOwnCloudController.php | 40 +++++-- .../Controller/SaveToOwnCloudControllerTest.php | 16 ++- apps/files_sharing/ajax/external.php | 119 ++++----------------- apps/files_sharing/js/external.js | 6 +- apps/files_sharing/js/public.js | 86 ++++++++++++--- 5 files changed, 138 insertions(+), 129 deletions(-) (limited to 'apps') diff --git a/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php b/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php index a20806e6abb..2318d21afb5 100644 --- a/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php +++ b/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php @@ -29,6 +29,7 @@ use OCP\AppFramework\Controller; use OCP\AppFramework\Http; use OCP\AppFramework\Http\JSONResponse; use OCP\IRequest; +use OCP\ISession; use OCP\Share\IManager; class SaveToOwnCloudController extends Controller { @@ -42,16 +43,32 @@ class SaveToOwnCloudController extends Controller { /** @var IManager */ private $shareManager; + /** @var ISession */ + private $session; + + /** + * SaveToOwnCloudController constructor. + * + * @param string $appName + * @param IRequest $request + * @param FederatedShareProvider $federatedShareProvider + * @param IManager $shareManager + * @param AddressHandler $addressHandler + * @param ISession $session + */ public function __construct($appName, - IRequest $request, - FederatedShareProvider $federatedShareProvider, - IManager $shareManager, - AddressHandler $addressHandler) { + IRequest $request, + FederatedShareProvider $federatedShareProvider, + IManager $shareManager, + AddressHandler $addressHandler, + ISession $session + ) { parent::__construct($appName, $request); $this->federatedShareProvider = $federatedShareProvider; $this->shareManager = $shareManager; $this->addressHandler = $addressHandler; + $this->session = $session; } /** @@ -63,9 +80,10 @@ class SaveToOwnCloudController extends Controller { * * @param string $shareWith * @param string $token + * @param string $password * @return JSONResponse */ - public function saveToOwnCloud($shareWith, $token) { + public function saveToOwnCloud($shareWith, $token, $password = '') { try { list(, $server) = $this->addressHandler->splitUserRemote($shareWith); @@ -74,6 +92,14 @@ class SaveToOwnCloudController extends Controller { return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST); } + // make sure that user is authenticated in case of a password protected link + $storedPassword = $share->getPassword(); + $authenticated = $this->session->get('public_link_authenticated') === $share->getId() || + $this->shareManager->checkPassword($share, $password); + if (!empty($storedPassword) && !$authenticated ) { + return new JSONResponse(['message' => 'No permission to access the share'], Http::STATUS_BAD_REQUEST); + } + $share->setSharedWith($shareWith); try { @@ -81,8 +107,8 @@ class SaveToOwnCloudController extends Controller { } catch (\Exception $e) { return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); } - + return new JSONResponse(['remoteUrl' => $server]); } - + } diff --git a/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php b/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php index 24bc18d5644..9189ac76601 100644 --- a/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php @@ -28,6 +28,7 @@ use OCA\FederatedFileSharing\Controller\SaveToOwnCloudController; use OCA\FederatedFileSharing\FederatedShareProvider; use OCP\AppFramework\Http; use OCP\Files\IRootFolder; +use OCP\ISession; use OCP\IUserManager; use OCP\Share; use OCP\Share\IManager; @@ -56,6 +57,9 @@ class SaveToOwnCloudControllerTest extends \Test\TestCase { /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */ private $userManager; + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject */ + private $session; + /** @var IShare */ private $share; @@ -71,12 +75,14 @@ class SaveToOwnCloudControllerTest extends \Test\TestCase { $this->rootFolder = $this->getMock('OCP\Files\IRootFolder'); $this->userManager = $this->getMock('OCP\IUserManager'); $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); + $this->session = $this->getMock('OCP\ISession'); $this->controller = new SaveToOwnCloudController( 'federatedfilesharing', $this->request, $this->federatedShareProvider, $this->shareManager, - $this->addressHandler + $this->addressHandler, + $this->session ); } @@ -101,9 +107,9 @@ class SaveToOwnCloudControllerTest extends \Test\TestCase { throw new HintException($expectedReturnData, $expectedReturnData); } ); - + $share = $this->share; - + $this->shareManager->expects($this->any())->method('getShareByToken') ->with($token) ->willReturnCallback( @@ -114,7 +120,7 @@ class SaveToOwnCloudControllerTest extends \Test\TestCase { throw new HintException($expectedReturnData, $expectedReturnData); } ); - + $this->federatedShareProvider->expects($this->any())->method('create') ->with($share) ->willReturnCallback( @@ -141,7 +147,7 @@ class SaveToOwnCloudControllerTest extends \Test\TestCase { $this->assertSame($expectedReturnData, $result->getData()['remoteUrl']); } - + } public function dataTestSaveToOwnCloud() { diff --git a/apps/files_sharing/ajax/external.php b/apps/files_sharing/ajax/external.php index 4a7a6096c91..d57d333c7ee 100644 --- a/apps/files_sharing/ajax/external.php +++ b/apps/files_sharing/ajax/external.php @@ -42,112 +42,35 @@ if ($federatedShareProvider->isIncomingServer2serverShareEnabled() === false) { $token = $_POST['token']; $remote = $_POST['remote']; -$owner = $_POST['owner']; -$ownerDisplayName = $_POST['ownerDisplayName']; -$name = $_POST['name']; -$password = $_POST['password']; +$password = isset($_POST['password']) ? $_POST['password'] : ''; -// Check for invalid name -if(!\OCP\Util::isValidFileName($name)) { - \OCP\JSON::error(array('data' => array('message' => $l->t('The mountpoint name contains invalid characters.')))); - exit(); -} - -$currentUser = \OC::$server->getUserSession()->getUser()->getUID(); -$currentServer = \OC::$server->getURLGenerator()->getAbsoluteURL('/'); -if (\OC\Share\Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer )) { - \OCP\JSON::error(array('data' => array('message' => $l->t('Not allowed to create a federated share with the same user server')))); - exit(); -} +$urlGenerator = \OC::$server->getURLGenerator(); -$discoveryManager = new \OCA\FederatedFileSharing\DiscoveryManager( - \OC::$server->getMemCacheFactory(), - \OC::$server->getHTTPClientService() -); -$externalManager = new \OCA\Files_Sharing\External\Manager( - \OC::$server->getDatabaseConnection(), - \OC\Files\Filesystem::getMountManager(), - \OC\Files\Filesystem::getLoader(), - \OC::$server->getHTTPHelper(), - \OC::$server->getNotificationManager(), - $discoveryManager, - \OC::$server->getUserSession()->getUser()->getUID() -); +$shareWith = \OCP\User::getUser() . '@' . $urlGenerator->getAbsoluteURL('/'); -// check for ssl cert -if (substr($remote, 0, 5) === 'https') { - try { - \OC::$server->getHTTPClientService()->newClient()->get($remote, [ - 'timeout' => 10, - 'connect_timeout' => 10, - ])->getBody(); - } catch (\Exception $e) { - \OCP\JSON::error(array('data' => array('message' => $l->t('Invalid or untrusted SSL certificate')))); - exit; - } -} +$httpClient = \OC::$server->getHTTPClientService()->newClient(); -$mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true); +error_log("do th post"); -/** - * @var \OCA\Files_Sharing\External\Storage $storage - */ -$storage = $mount->getStorage(); try { - // check if storage exists - $storage->checkStorageAvailability(); -} catch (\OCP\Files\StorageInvalidException $e) { - // note: checkStorageAvailability will already remove the invalid share - \OCP\Util::writeLog( - 'files_sharing', - 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), - \OCP\Util::DEBUG - ); - \OCP\JSON::error( - array( - 'data' => array( - 'message' => $l->t('Could not authenticate to remote share, password might be wrong') - ) - ) + $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/saveToOwnCloud', + [ + 'body' => + [ + 'token' => $token, + 'shareWith' => rtrim($shareWith, '/'), + 'password' => $password + ] + ] ); - exit(); } catch (\Exception $e) { - \OCP\Util::writeLog( - 'files_sharing', - 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), - \OCP\Util::DEBUG - ); - $externalManager->removeShare($mount->getMountPoint()); - \OCP\JSON::error(array('data' => array('message' => $l->t('Storage not valid')))); - exit(); -} -$result = $storage->file_exists(''); -if ($result) { - try { - $storage->getScanner()->scanAll(); - \OCP\JSON::success(); - } catch (\OCP\Files\StorageInvalidException $e) { - \OCP\Util::writeLog( - 'files_sharing', - 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), - \OCP\Util::DEBUG - ); - \OCP\JSON::error(array('data' => array('message' => $l->t('Storage not valid')))); - } catch (\Exception $e) { - \OCP\Util::writeLog( - 'files_sharing', - 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), - \OCP\Util::DEBUG - ); - \OCP\JSON::error(array('data' => array('message' => $l->t('Couldn\'t add remote share')))); + if (empty($password)) { + $message = $l->t("Couldn't establish a federated share."); + } else { + $message = $l->t("Couldn't establish a federated share, maybe the password was wrong."); } -} else { - $externalManager->removeShare($mount->getMountPoint()); - \OCP\Util::writeLog( - 'files_sharing', - 'Couldn\'t add remote share', - \OCP\Util::DEBUG - ); - \OCP\JSON::error(array('data' => array('message' => $l->t('Couldn\'t add remote share')))); + \OCP\JSON::error(array('data' => array('message' => $message))); + exit(); } +\OCP\JSON::success(array('data' => array('message' => $l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')))); diff --git a/apps/files_sharing/js/external.js b/apps/files_sharing/js/external.js index 0ca8213168e..be384818c3c 100644 --- a/apps/files_sharing/js/external.js +++ b/apps/files_sharing/js/external.js @@ -107,11 +107,7 @@ ownerDisplayName: share.ownerDisplayName || share.owner, name: share.name, password: password}, function(result) { - if (result.status === 'error') { - OC.Notification.showTemporary(result.data.message); - } else { - fileList.reload(); - } + OC.Notification.showTemporary(result.data.message); }); } }; diff --git a/apps/files_sharing/js/public.js b/apps/files_sharing/js/public.js index d4f3bd36a63..4293c7b310b 100644 --- a/apps/files_sharing/js/public.js +++ b/apps/files_sharing/js/public.js @@ -244,8 +244,10 @@ OCA.Sharing.PublicApp = { var remote = $(this).find('input[type="text"]').val(); var token = $('#sharingToken').val(); var owner = $('#save').data('owner'); + var ownerDisplayName = $('#save').data('owner-display-name'); var name = $('#save').data('name'); - OCA.Sharing.PublicApp._saveToOwnCloud(remote, token); + var isProtected = $('#save').data('protected') ? 1 : 0; + OCA.Sharing.PublicApp._saveToOwnCloud(remote, token, owner, ownerDisplayName, name, isProtected); }); $('#remote_address').on("keyup paste", function() { @@ -293,7 +295,72 @@ OCA.Sharing.PublicApp = { }, - _saveToOwnCloud: function (remote, token) { + /** + * fall back to old behaviour where we redirect the user to his server to mount + * the public link instead of creating a dedicated federated share + * + * @param remote + * @param token + * @param owner + * @param ownerDisplayName + * @param name + * @param isProtected + * @private + */ + _legacySaveToOwnCloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { + + var location = window.location.protocol + '//' + window.location.host + OC.webroot; + + if(remote.substr(-1) !== '/') { + remote += '/' + } + + var url = remote + 'index.php/apps/files#' + 'remote=' + encodeURIComponent(location) // our location is the remote for the other server + + "&token=" + encodeURIComponent(token) + "&owner=" + encodeURIComponent(owner) +"&ownerDisplayName=" + encodeURIComponent(ownerDisplayName) + "&name=" + encodeURIComponent(name) + "&protected=" + isProtected; + + + if (remote.indexOf('://') > 0) { + OC.redirect(url); + } else { + // if no protocol is specified, we automatically detect it by testing https and http + // this check needs to happen on the server due to the Content Security Policy directive + $.get(OC.generateUrl('apps/files_sharing/testremote'), {remote: remote}).then(function (protocol) { + if (protocol !== 'http' && protocol !== 'https') { + OC.dialogs.alert(t('files_sharing', 'No compatible server found at {remote}', {remote: remote}), + t('files_sharing', 'Invalid server URL')); + } else { + OC.redirect(protocol + '://' + url); + } + }); + } + }, + + _saveToOwnCloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { + + var toggleLoading = function() { + var iconClass = $('#save-button-confirm').attr('class'); + var loading = iconClass.indexOf('icon-loading-small') !== -1; + if(loading) { + $('#save-button-confirm') + .removeClass("icon-loading-small") + .addClass("icon-confirm"); + + } + else { + $('#save-button-confirm') + .removeClass("icon-confirm") + .addClass("icon-loading-small"); + + } + }; + + toggleLoading(); + + if (remote.indexOf('@') == -1) { + this._legacySaveToOwnCloud(remote, token, owner, ownerDisplayName, name, isProtected); + toggleLoading(); + return; + } $.post( OC.generateUrl('/apps/federatedfilesharing/saveToOwnCloud'), @@ -308,17 +375,7 @@ OCA.Sharing.PublicApp = { if (url.indexOf('://') > 0) { OC.redirect(url); } else { - // if no protocol is specified, we automatically detect it by testing https and http - // this check needs to happen on the server due to the Content Security Policy directive - $.get(OC.generateUrl('apps/files_sharing/testremote'), {remote: remote}).then(function (protocol) { - if (protocol !== 'http' && protocol !== 'https') { - toggleLoading(); - OC.dialogs.alert(t('files_sharing', 'No Nextcloud installation (7 or higher) found at {remote}', {remote: remote}), - t('files_sharing', 'Invalid ownCloud url')); - } else { - OC.redirect(protocol + '://' + url); - } - }); + OC.redirect('http://' + url); } } ).fail( @@ -326,7 +383,8 @@ OCA.Sharing.PublicApp = { console.log("ERROR!"); console.log(jqXHR); OC.dialogs.alert(JSON.parse(jqXHR.responseText).message, - t('files_sharing', 'Failed to add the public link to your ownCloud')); + t('files_sharing', 'Failed to add the public link to your Nextcloud')); + toggleLoading(); } ); } -- cgit v1.2.3 From 2f23054b0126ec3497a7b632ff2399f6f3843a0f Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Tue, 12 Jul 2016 16:30:09 +0200 Subject: s/ownCloud/Nextcloud --- apps/federatedfilesharing/appinfo/routes.php | 2 +- .../lib/Controller/SaveToNextcloudController.php | 114 ++++++++++++++ .../lib/Controller/SaveToOwnCloudController.php | 114 -------------- .../Controller/SaveToNextcloudControllerTest.php | 167 +++++++++++++++++++++ .../Controller/SaveToOwnCloudControllerTest.php | 167 --------------------- apps/files_sharing/ajax/external.php | 4 +- apps/files_sharing/js/external.js | 1 - apps/files_sharing/js/public.js | 10 +- 8 files changed, 288 insertions(+), 291 deletions(-) create mode 100644 apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php delete mode 100644 apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php create mode 100644 apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php delete mode 100644 apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php (limited to 'apps') diff --git a/apps/federatedfilesharing/appinfo/routes.php b/apps/federatedfilesharing/appinfo/routes.php index 534733e001f..2a90ef5b59b 100644 --- a/apps/federatedfilesharing/appinfo/routes.php +++ b/apps/federatedfilesharing/appinfo/routes.php @@ -21,6 +21,6 @@ return [ 'routes' => [ - ['name' => 'SaveToOwnCloud#saveToOwnCloud', 'url' => '/saveToOwnCloud', 'verb' => 'POST'], + ['name' => 'SaveToNextcloud#saveToNextcloud', 'url' => '/saveToNextcloud', 'verb' => 'POST'], ] ]; diff --git a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php new file mode 100644 index 00000000000..f2788cf1ccd --- /dev/null +++ b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php @@ -0,0 +1,114 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + + +namespace OCA\FederatedFileSharing\Controller; + +use OC\HintException; +use OCA\FederatedFileSharing\AddressHandler; +use OCA\FederatedFileSharing\FederatedShareProvider; +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\JSONResponse; +use OCP\IRequest; +use OCP\ISession; +use OCP\Share\IManager; + +class SaveToNextcloudController extends Controller { + + /** @var FederatedShareProvider */ + private $federatedShareProvider; + + /** @var AddressHandler */ + private $addressHandler; + + /** @var IManager */ + private $shareManager; + + /** @var ISession */ + private $session; + + /** + * SaveToNextcloudController constructor. + * + * @param string $appName + * @param IRequest $request + * @param FederatedShareProvider $federatedShareProvider + * @param IManager $shareManager + * @param AddressHandler $addressHandler + * @param ISession $session + */ + public function __construct($appName, + IRequest $request, + FederatedShareProvider $federatedShareProvider, + IManager $shareManager, + AddressHandler $addressHandler, + ISession $session + ) { + parent::__construct($appName, $request); + + $this->federatedShareProvider = $federatedShareProvider; + $this->shareManager = $shareManager; + $this->addressHandler = $addressHandler; + $this->session = $session; + } + + /** + * save public link to my Nextcloud by asking the owner to create a federated + * share with me + * + * @NoCSRFRequired + * @PublicPage + * + * @param string $shareWith + * @param string $token + * @param string $password + * @return JSONResponse + */ + public function saveToNextcloud($shareWith, $token, $password = '') { + + try { + list(, $server) = $this->addressHandler->splitUserRemote($shareWith); + $share = $this->shareManager->getShareByToken($token); + } catch (HintException $e) { + return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST); + } + + // make sure that user is authenticated in case of a password protected link + $storedPassword = $share->getPassword(); + $authenticated = $this->session->get('public_link_authenticated') === $share->getId() || + $this->shareManager->checkPassword($share, $password); + if (!empty($storedPassword) && !$authenticated ) { + return new JSONResponse(['message' => 'No permission to access the share'], Http::STATUS_BAD_REQUEST); + } + + $share->setSharedWith($shareWith); + + try { + $this->federatedShareProvider->create($share); + } catch (\Exception $e) { + return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); + } + + return new JSONResponse(['remoteUrl' => $server]); + } + +} diff --git a/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php b/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php deleted file mode 100644 index 2318d21afb5..00000000000 --- a/apps/federatedfilesharing/lib/Controller/SaveToOwnCloudController.php +++ /dev/null @@ -1,114 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - - -namespace OCA\FederatedFileSharing\Controller; - -use OC\HintException; -use OCA\FederatedFileSharing\AddressHandler; -use OCA\FederatedFileSharing\FederatedShareProvider; -use OCP\AppFramework\Controller; -use OCP\AppFramework\Http; -use OCP\AppFramework\Http\JSONResponse; -use OCP\IRequest; -use OCP\ISession; -use OCP\Share\IManager; - -class SaveToOwnCloudController extends Controller { - - /** @var FederatedShareProvider */ - private $federatedShareProvider; - - /** @var AddressHandler */ - private $addressHandler; - - /** @var IManager */ - private $shareManager; - - /** @var ISession */ - private $session; - - /** - * SaveToOwnCloudController constructor. - * - * @param string $appName - * @param IRequest $request - * @param FederatedShareProvider $federatedShareProvider - * @param IManager $shareManager - * @param AddressHandler $addressHandler - * @param ISession $session - */ - public function __construct($appName, - IRequest $request, - FederatedShareProvider $federatedShareProvider, - IManager $shareManager, - AddressHandler $addressHandler, - ISession $session - ) { - parent::__construct($appName, $request); - - $this->federatedShareProvider = $federatedShareProvider; - $this->shareManager = $shareManager; - $this->addressHandler = $addressHandler; - $this->session = $session; - } - - /** - * save public link to my ownCloud by asking the owner to create a federated - * share with me - * - * @NoCSRFRequired - * @PublicPage - * - * @param string $shareWith - * @param string $token - * @param string $password - * @return JSONResponse - */ - public function saveToOwnCloud($shareWith, $token, $password = '') { - - try { - list(, $server) = $this->addressHandler->splitUserRemote($shareWith); - $share = $this->shareManager->getShareByToken($token); - } catch (HintException $e) { - return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST); - } - - // make sure that user is authenticated in case of a password protected link - $storedPassword = $share->getPassword(); - $authenticated = $this->session->get('public_link_authenticated') === $share->getId() || - $this->shareManager->checkPassword($share, $password); - if (!empty($storedPassword) && !$authenticated ) { - return new JSONResponse(['message' => 'No permission to access the share'], Http::STATUS_BAD_REQUEST); - } - - $share->setSharedWith($shareWith); - - try { - $this->federatedShareProvider->create($share); - } catch (\Exception $e) { - return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); - } - - return new JSONResponse(['remoteUrl' => $server]); - } - -} diff --git a/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php b/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php new file mode 100644 index 00000000000..60136212c31 --- /dev/null +++ b/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php @@ -0,0 +1,167 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + + +namespace OCA\FederatedFileSharing\Tests\Controller; + +use OC\HintException; +use OCA\FederatedFileSharing\AddressHandler; +use OCA\FederatedFileSharing\Controller\SaveToNextcloudController; +use OCA\FederatedFileSharing\FederatedShareProvider; +use OCP\AppFramework\Http; +use OCP\Files\IRootFolder; +use OCP\ISession; +use OCP\IUserManager; +use OCP\Share; +use OCP\Share\IManager; +use OCP\Share\IShare; + +class SaveToNextcloudControllerTest extends \Test\TestCase { + + /** @var SaveToNextcloudController */ + private $controller; + + /** @var \OCP\IRequest | \PHPUnit_Framework_MockObject_MockObject */ + private $request; + + /** @var FederatedShareProvider | \PHPUnit_Framework_MockObject_MockObject */ + private $federatedShareProvider; + + /** @var IManager | \PHPUnit_Framework_MockObject_MockObject */ + private $shareManager; + + /** @var AddressHandler | \PHPUnit_Framework_MockObject_MockObject */ + private $addressHandler; + + /** @var IRootFolder | \PHPUnit_Framework_MockObject_MockObject */ + private $rootFolder; + + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */ + private $userManager; + + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject */ + private $session; + + /** @var IShare */ + private $share; + + public function setUp() { + parent::setUp(); + + $this->request = $this->getMock('OCP\IRequest'); + $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') + ->disableOriginalConstructor()->getMock(); + $this->shareManager = $this->getMock('OCP\Share\IManager'); + $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') + ->disableOriginalConstructor()->getMock(); + $this->rootFolder = $this->getMock('OCP\Files\IRootFolder'); + $this->userManager = $this->getMock('OCP\IUserManager'); + $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); + $this->session = $this->getMock('OCP\ISession'); + + $this->controller = new SaveToNextcloudController( + 'federatedfilesharing', $this->request, + $this->federatedShareProvider, + $this->shareManager, + $this->addressHandler, + $this->session + ); + } + + /** + * @dataProvider dataTestSaveToNextcloud + * + * @param string $shareWith + * @param bool $validShareWith + * @param string $token + * @param bool $validToken + * @param bool $createSuccessful + * @param string $expectedReturnData + */ + public function testSaveToNextcloud($shareWith, $validShareWith, $token, $validToken, $createSuccessful, $expectedReturnData) { + $this->addressHandler->expects($this->any())->method('splitUserRemote') + ->with($shareWith) + ->willReturnCallback( + function($shareWith) use ($validShareWith, $expectedReturnData) { + if ($validShareWith) { + return ['user', 'server']; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $share = $this->share; + + $this->shareManager->expects($this->any())->method('getShareByToken') + ->with($token) + ->willReturnCallback( + function ($token) use ($validToken, $share, $expectedReturnData) { + if ($validToken) { + return $share; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $this->federatedShareProvider->expects($this->any())->method('create') + ->with($share) + ->willReturnCallback( + function (IShare $share) use ($createSuccessful, $shareWith, $expectedReturnData) { + $this->assertEquals($shareWith, $share->getSharedWith()); + if ($createSuccessful) { + return $share; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $result = $this->controller->saveToNextcloud($shareWith, $token); + + $errorCase = !$validShareWith || !$validToken || !$createSuccessful; + + if ($errorCase) { + $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus()); + $this->assertTrue(isset($result->getData()['message'])); + $this->assertSame($expectedReturnData, $result->getData()['message']); + } else { + $this->assertSame(Http::STATUS_OK, $result->getStatus()); + $this->assertTrue(isset($result->getData()['remoteUrl'])); + $this->assertSame($expectedReturnData, $result->getData()['remoteUrl']); + + } + + } + + public function dataTestSaveToNextcloud() { + return [ + //shareWith, validShareWith, token, validToken, createSuccessful, expectedReturnData + ['user@server', true, 'token', true, true, 'server'], + ['user@server', false, 'token', true, true, 'invalid federated cloud id'], + ['user@server', false, 'token', false, true, 'invalid federated cloud id'], + ['user@server', false, 'token', false, false, 'invalid federated cloud id'], + ['user@server', false, 'token', true, false, 'invalid federated cloud id'], + ['user@server', true, 'token', false, true, 'invalid token'], + ['user@server', true, 'token', false, false, 'invalid token'], + ['user@server', true, 'token', true, false, 'can not create share'] + ]; + } + +} diff --git a/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php b/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php deleted file mode 100644 index 9189ac76601..00000000000 --- a/apps/federatedfilesharing/tests/Controller/SaveToOwnCloudControllerTest.php +++ /dev/null @@ -1,167 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - - -namespace OCA\FederatedFileSharing\Tests\Controller; - -use OC\HintException; -use OCA\FederatedFileSharing\AddressHandler; -use OCA\FederatedFileSharing\Controller\SaveToOwnCloudController; -use OCA\FederatedFileSharing\FederatedShareProvider; -use OCP\AppFramework\Http; -use OCP\Files\IRootFolder; -use OCP\ISession; -use OCP\IUserManager; -use OCP\Share; -use OCP\Share\IManager; -use OCP\Share\IShare; - -class SaveToOwnCloudControllerTest extends \Test\TestCase { - - /** @var SaveToOwnCloudController */ - private $controller; - - /** @var \OCP\IRequest | \PHPUnit_Framework_MockObject_MockObject */ - private $request; - - /** @var FederatedShareProvider | \PHPUnit_Framework_MockObject_MockObject */ - private $federatedShareProvider; - - /** @var IManager | \PHPUnit_Framework_MockObject_MockObject */ - private $shareManager; - - /** @var AddressHandler | \PHPUnit_Framework_MockObject_MockObject */ - private $addressHandler; - - /** @var IRootFolder | \PHPUnit_Framework_MockObject_MockObject */ - private $rootFolder; - - /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */ - private $userManager; - - /** @var ISession | \PHPUnit_Framework_MockObject_MockObject */ - private $session; - - /** @var IShare */ - private $share; - - public function setUp() { - parent::setUp(); - - $this->request = $this->getMock('OCP\IRequest'); - $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') - ->disableOriginalConstructor()->getMock(); - $this->shareManager = $this->getMock('OCP\Share\IManager'); - $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') - ->disableOriginalConstructor()->getMock(); - $this->rootFolder = $this->getMock('OCP\Files\IRootFolder'); - $this->userManager = $this->getMock('OCP\IUserManager'); - $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); - $this->session = $this->getMock('OCP\ISession'); - - $this->controller = new SaveToOwnCloudController( - 'federatedfilesharing', $this->request, - $this->federatedShareProvider, - $this->shareManager, - $this->addressHandler, - $this->session - ); - } - - /** - * @dataProvider dataTestSaveToOwnCloud - * - * @param string $shareWith - * @param bool $validShareWith - * @param string $token - * @param bool $validToken - * @param bool $createSuccessful - * @param string $expectedReturnData - */ - public function testSaveToOwnCloud($shareWith, $validShareWith, $token, $validToken, $createSuccessful, $expectedReturnData) { - $this->addressHandler->expects($this->any())->method('splitUserRemote') - ->with($shareWith) - ->willReturnCallback( - function($shareWith) use ($validShareWith, $expectedReturnData) { - if ($validShareWith) { - return ['user', 'server']; - } - throw new HintException($expectedReturnData, $expectedReturnData); - } - ); - - $share = $this->share; - - $this->shareManager->expects($this->any())->method('getShareByToken') - ->with($token) - ->willReturnCallback( - function ($token) use ($validToken, $share, $expectedReturnData) { - if ($validToken) { - return $share; - } - throw new HintException($expectedReturnData, $expectedReturnData); - } - ); - - $this->federatedShareProvider->expects($this->any())->method('create') - ->with($share) - ->willReturnCallback( - function (IShare $share) use ($createSuccessful, $shareWith, $expectedReturnData) { - $this->assertEquals($shareWith, $share->getSharedWith()); - if ($createSuccessful) { - return $share; - } - throw new HintException($expectedReturnData, $expectedReturnData); - } - ); - - $result = $this->controller->saveToOwnCloud($shareWith, $token); - - $errorCase = !$validShareWith || !$validToken || !$createSuccessful; - - if ($errorCase) { - $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus()); - $this->assertTrue(isset($result->getData()['message'])); - $this->assertSame($expectedReturnData, $result->getData()['message']); - } else { - $this->assertSame(Http::STATUS_OK, $result->getStatus()); - $this->assertTrue(isset($result->getData()['remoteUrl'])); - $this->assertSame($expectedReturnData, $result->getData()['remoteUrl']); - - } - - } - - public function dataTestSaveToOwnCloud() { - return [ - //shareWith, validShareWith, token, validToken, createSuccessful, expectedReturnData - ['user@server', true, 'token', true, true, 'server'], - ['user@server', false, 'token', true, true, 'invalid federated cloud id'], - ['user@server', false, 'token', false, true, 'invalid federated cloud id'], - ['user@server', false, 'token', false, false, 'invalid federated cloud id'], - ['user@server', false, 'token', true, false, 'invalid federated cloud id'], - ['user@server', true, 'token', false, true, 'invalid token'], - ['user@server', true, 'token', false, false, 'invalid token'], - ['user@server', true, 'token', true, false, 'can not create share'] - ]; - } - -} diff --git a/apps/files_sharing/ajax/external.php b/apps/files_sharing/ajax/external.php index d57d333c7ee..20c3706c12d 100644 --- a/apps/files_sharing/ajax/external.php +++ b/apps/files_sharing/ajax/external.php @@ -50,10 +50,8 @@ $shareWith = \OCP\User::getUser() . '@' . $urlGenerator->getAbsoluteURL('/'); $httpClient = \OC::$server->getHTTPClientService()->newClient(); -error_log("do th post"); - try { - $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/saveToOwnCloud', + $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/saveToNextcloud', [ 'body' => [ diff --git a/apps/files_sharing/js/external.js b/apps/files_sharing/js/external.js index be384818c3c..a04a5721f37 100644 --- a/apps/files_sharing/js/external.js +++ b/apps/files_sharing/js/external.js @@ -99,7 +99,6 @@ var callbackAddShare = function(result, share) { var password = share.password || ''; if (result) { - //$.post(OC.generateUrl('/apps/files_sharing/api/externalShares'), {id: share.id}); $.post(OC.generateUrl('apps/files_sharing/external'), { remote: share.remote, token: share.token, diff --git a/apps/files_sharing/js/public.js b/apps/files_sharing/js/public.js index 4293c7b310b..6bc31879d0f 100644 --- a/apps/files_sharing/js/public.js +++ b/apps/files_sharing/js/public.js @@ -247,7 +247,7 @@ OCA.Sharing.PublicApp = { var ownerDisplayName = $('#save').data('owner-display-name'); var name = $('#save').data('name'); var isProtected = $('#save').data('protected') ? 1 : 0; - OCA.Sharing.PublicApp._saveToOwnCloud(remote, token, owner, ownerDisplayName, name, isProtected); + OCA.Sharing.PublicApp._saveToNextcloud(remote, token, owner, ownerDisplayName, name, isProtected); }); $('#remote_address').on("keyup paste", function() { @@ -307,7 +307,7 @@ OCA.Sharing.PublicApp = { * @param isProtected * @private */ - _legacySaveToOwnCloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { + _legacySaveToNextcloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { var location = window.location.protocol + '//' + window.location.host + OC.webroot; @@ -335,7 +335,7 @@ OCA.Sharing.PublicApp = { } }, - _saveToOwnCloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { + _saveToNextcloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { var toggleLoading = function() { var iconClass = $('#save-button-confirm').attr('class'); @@ -357,13 +357,13 @@ OCA.Sharing.PublicApp = { toggleLoading(); if (remote.indexOf('@') == -1) { - this._legacySaveToOwnCloud(remote, token, owner, ownerDisplayName, name, isProtected); + this._legacySaveToNextcloud(remote, token, owner, ownerDisplayName, name, isProtected); toggleLoading(); return; } $.post( - OC.generateUrl('/apps/federatedfilesharing/saveToOwnCloud'), + OC.generateUrl('/apps/federatedfilesharing/saveToNextcloud'), { 'shareWith': remote, 'token': token -- cgit v1.2.3 From 5bbba490c4444f7977e7ad0ce4266acbd67eee86 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Tue, 12 Jul 2016 18:48:00 +0200 Subject: move some stuff over to the federatedfilesharing app --- apps/federatedfilesharing/appinfo/app.php | 15 +- apps/federatedfilesharing/appinfo/routes.php | 1 + apps/federatedfilesharing/js/external.js | 172 +++++++++++++++ .../lib/Controller/SaveToNextcloudController.php | 75 ++++++- .../Controller/SaveToNextcloudControllerTest.php | 30 ++- apps/federatedfilesharing/tests/js/externalSpec.js | 245 +++++++++++++++++++++ apps/files_sharing/ajax/external.php | 74 ------- apps/files_sharing/appinfo/app.php | 3 - apps/files_sharing/appinfo/routes.php | 2 - apps/files_sharing/js/external.js | 164 -------------- apps/files_sharing/js/public.js | 4 +- apps/files_sharing/tests/js/externalSpec.js | 245 --------------------- 12 files changed, 526 insertions(+), 504 deletions(-) create mode 100644 apps/federatedfilesharing/js/external.js create mode 100644 apps/federatedfilesharing/tests/js/externalSpec.js delete mode 100644 apps/files_sharing/ajax/external.php delete mode 100644 apps/files_sharing/js/external.js delete mode 100644 apps/files_sharing/tests/js/externalSpec.js (limited to 'apps') diff --git a/apps/federatedfilesharing/appinfo/app.php b/apps/federatedfilesharing/appinfo/app.php index 8abdf8cac19..e6fbe615e7f 100644 --- a/apps/federatedfilesharing/appinfo/app.php +++ b/apps/federatedfilesharing/appinfo/app.php @@ -20,11 +20,11 @@ * */ -$app = new \OCA\FederatedFileSharing\AppInfo\Application(); - use OCA\FederatedFileSharing\Notifier; +$app = new \OCA\FederatedFileSharing\AppInfo\Application(); $l = \OC::$server->getL10N('files_sharing'); +$eventDispatcher = \OC::$server->getEventDispatcher(); $app->registerSettings(); @@ -39,3 +39,14 @@ $manager->registerNotifier(function() { 'name' => $l->t('Federated sharing'), ]; }); + +$federatedShareProvider = $app->getFederatedShareProvider(); + +$eventDispatcher->addListener( + 'OCA\Files::loadAdditionalScripts', + function() use ($federatedShareProvider) { + if ($federatedShareProvider->isIncomingServer2serverShareEnabled()) { + \OCP\Util::addScript('federatedfilesharing', 'external'); + } + } +); diff --git a/apps/federatedfilesharing/appinfo/routes.php b/apps/federatedfilesharing/appinfo/routes.php index 2a90ef5b59b..c5822c6b653 100644 --- a/apps/federatedfilesharing/appinfo/routes.php +++ b/apps/federatedfilesharing/appinfo/routes.php @@ -22,5 +22,6 @@ return [ 'routes' => [ ['name' => 'SaveToNextcloud#saveToNextcloud', 'url' => '/saveToNextcloud', 'verb' => 'POST'], + ['name' => 'SaveToNextcloud#askForFederatedShare', 'url' => '/askForFederatedShare', 'verb' => 'POST'], ] ]; diff --git a/apps/federatedfilesharing/js/external.js b/apps/federatedfilesharing/js/external.js new file mode 100644 index 00000000000..e8262092ee8 --- /dev/null +++ b/apps/federatedfilesharing/js/external.js @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2014 Robin Appelman + * + * This file is licensed under the Affero General Public License version 3 + * or later. + * + * See the COPYING-README file. + * + */ +(function () { + /** + * Shows "add external share" dialog. + * + * @param {String} remote remote server URL + * @param {String} owner owner name + * @param {String} name name of the shared folder + * @param {String} token authentication token + * @param {bool} passwordProtected true if the share is password protected + */ + OCA.Sharing.showAddExternalDialog = function (share, passwordProtected, callback) { + var remote = share.remote; + var owner = share.ownerDisplayName || share.owner; + var name = share.name; + var remoteClean = (remote.substr(0, 8) === 'https://') ? remote.substr(8) : remote.substr(7); + + if (!passwordProtected) { + OC.dialogs.confirm( + t( + 'files_sharing', + 'Do you want to add the remote share {name} from {owner}@{remote}?', + {name: name, owner: owner, remote: remoteClean} + ), + t('files_sharing','Remote share'), + function (result) { + callback(result, share); + }, + true + ).then(this._adjustDialog); + } else { + OC.dialogs.prompt( + t( + 'files_sharing', + 'Do you want to add the remote share {name} from {owner}@{remote}?', + {name: name, owner: owner, remote: remoteClean} + ), + t('files_sharing','Remote share'), + function (result, password) { + share.password = password; + callback(result, share); + }, + true, + t('files_sharing','Remote share password'), + true + ).then(this._adjustDialog); + } + }; + + OCA.Sharing._adjustDialog = function() { + var $dialog = $('.oc-dialog:visible'); + var $buttons = $dialog.find('button'); + // hack the buttons + $dialog.find('.ui-icon').remove(); + $buttons.eq(0).text(t('core', 'Cancel')); + $buttons.eq(1).text(t('files_sharing', 'Add remote share')); + }; + + OCA.Sharing.ExternalShareDialogPlugin = { + + filesApp: null, + + attach: function(filesApp) { + var self = this; + this.filesApp = filesApp; + this.processIncomingShareFromUrl(); + + if (!$('#header').find('div.notifications').length) { + // No notification app, display the modal + this.processSharesToConfirm(); + } + + $('body').on('OCA.Notification.Action', function(e) { + if (e.notification.app === 'files_sharing' && e.notification.object_type === 'remote_share' && e.action.type === 'POST') { + // User accepted a remote share reload + self.filesApp.fileList.reload(); + } + }); + }, + + /** + * Process incoming remote share that might have been passed + * through the URL + */ + processIncomingShareFromUrl: function() { + var params = OC.Util.History.parseUrlQuery(); + //manually add server-to-server share + if (params.remote && params.token && params.owner && params.name) { + + var callbackAddShare = function(result, share) { + var password = share.password || ''; + if (result) { + $.post( + OC.generateUrl('apps/federatedfilesharing/askForFederatedShare'), + { + remote: share.remote, + token: share.token, + owner: share.owner, + ownerDisplayName: share.ownerDisplayName || share.owner, + name: share.name, + password: password + } + ).done( + function(data) { + OC.Notification.showTemporary(data.message); + } + ).fail( + function(data) { + OC.Notification.showTemporary(JSON.parse(data.responseText).message); + } + ); + } + }; + + // clear hash, it is unlikely that it contain any extra parameters + location.hash = ''; + params.passwordProtected = parseInt(params.protected, 10) === 1; + OCA.Sharing.showAddExternalDialog( + params, + params.passwordProtected, + callbackAddShare + ); + } + }, + + /** + * Retrieve a list of remote shares that need to be approved + */ + processSharesToConfirm: function() { + var fileList = this.filesApp.fileList; + // check for new server-to-server shares which need to be approved + $.get(OC.generateUrl('/apps/files_sharing/api/externalShares'), + {}, + function(shares) { + var index; + for (index = 0; index < shares.length; ++index) { + OCA.Sharing.showAddExternalDialog( + shares[index], + false, + function(result, share) { + if (result) { + // Accept + $.post(OC.generateUrl('/apps/files_sharing/api/externalShares'), {id: share.id}) + .then(function() { + fileList.reload(); + }); + } else { + // Delete + $.ajax({ + url: OC.generateUrl('/apps/files_sharing/api/externalShares/'+share.id), + type: 'DELETE' + }); + } + } + ); + } + + }); + + } + }; +})(); + +OC.Plugins.register('OCA.Files.App', OCA.Sharing.ExternalShareDialogPlugin); diff --git a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php index f2788cf1ccd..8801d7af4e4 100644 --- a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php +++ b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php @@ -28,8 +28,11 @@ use OCA\FederatedFileSharing\FederatedShareProvider; use OCP\AppFramework\Controller; use OCP\AppFramework\Http; use OCP\AppFramework\Http\JSONResponse; +use OCP\Http\Client\IClientService; +use OCP\IL10N; use OCP\IRequest; use OCP\ISession; +use OCP\IUserSession; use OCP\Share\IManager; class SaveToNextcloudController extends Controller { @@ -46,6 +49,15 @@ class SaveToNextcloudController extends Controller { /** @var ISession */ private $session; + /** @var IL10N */ + private $l; + + /** @var IUserSession */ + private $userSession; + + /** @var IClientService */ + private $clientService; + /** * SaveToNextcloudController constructor. * @@ -55,13 +67,19 @@ class SaveToNextcloudController extends Controller { * @param IManager $shareManager * @param AddressHandler $addressHandler * @param ISession $session + * @param IL10N $l + * @param IUserSession $userSession + * @param IClientService $clientService */ public function __construct($appName, - IRequest $request, - FederatedShareProvider $federatedShareProvider, - IManager $shareManager, - AddressHandler $addressHandler, - ISession $session + IRequest $request, + FederatedShareProvider $federatedShareProvider, + IManager $shareManager, + AddressHandler $addressHandler, + ISession $session, + IL10N $l, + IUserSession $userSession, + IClientService $clientService ) { parent::__construct($appName, $request); @@ -69,6 +87,9 @@ class SaveToNextcloudController extends Controller { $this->shareManager = $shareManager; $this->addressHandler = $addressHandler; $this->session = $session; + $this->l = $l; + $this->userSession = $userSession; + $this->clientService = $clientService; } /** @@ -111,4 +132,48 @@ class SaveToNextcloudController extends Controller { return new JSONResponse(['remoteUrl' => $server]); } + /** + * ask other server to get a federated share + * + * @NoAdminRequired + * + * @param string $token + * @param string $remote + * @param string $password + * @return JSONResponse + */ + public function askForFederatedShare($token, $remote, $password = '') { + // check if server admin allows to mount public links from other servers + if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) { + return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST); + } + + $shareWith = $this->userSession->getUser()->getUID() . '@' . $this->addressHandler->generateRemoteURL(); + + $httpClient = $this->clientService->newClient(); + + try { + $httpClient->post($remote . '/index.php/apps/federatedfilesharing/saveToNextcloud', + [ + 'body' => + [ + 'token' => $token, + 'shareWith' => rtrim($shareWith, '/'), + 'password' => $password + ] + ] + ); + } catch (\Exception $e) { + if (empty($password)) { + $message = $this->l->t("Couldn't establish a federated share."); + } else { + $message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong."); + } + return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST); + } + + return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]); + + } + } diff --git a/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php b/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php index 60136212c31..0e36df9b25a 100644 --- a/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php @@ -28,8 +28,11 @@ use OCA\FederatedFileSharing\Controller\SaveToNextcloudController; use OCA\FederatedFileSharing\FederatedShareProvider; use OCP\AppFramework\Http; use OCP\Files\IRootFolder; +use OCP\Http\Client\IClientService; +use OCP\IL10N; use OCP\ISession; use OCP\IUserManager; +use OCP\IUserSession; use OCP\Share; use OCP\Share\IManager; use OCP\Share\IShare; @@ -60,29 +63,44 @@ class SaveToNextcloudControllerTest extends \Test\TestCase { /** @var ISession | \PHPUnit_Framework_MockObject_MockObject */ private $session; + /** @var IL10N | \PHPUnit_Framework_MockObject_MockObject */ + private $l10n; + + /** @var IUserSession | \PHPUnit_Framework_MockObject_MockObject */ + private $userSession; + + /** @var IClientService | \PHPUnit_Framework_MockObject_MockObject */ + private $clientService; + /** @var IShare */ private $share; public function setUp() { parent::setUp(); - $this->request = $this->getMock('OCP\IRequest'); + $this->request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') ->disableOriginalConstructor()->getMock(); - $this->shareManager = $this->getMock('OCP\Share\IManager'); + $this->shareManager = $this->getMockBuilder('OCP\Share\IManager')->disableOriginalConstructor()->getMock(); $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') ->disableOriginalConstructor()->getMock(); - $this->rootFolder = $this->getMock('OCP\Files\IRootFolder'); - $this->userManager = $this->getMock('OCP\IUserManager'); + $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->disableOriginalConstructor()->getMock(); + $this->userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); - $this->session = $this->getMock('OCP\ISession'); + $this->session = $this->getMockBuilder('OCP\ISession')->disableOriginalConstructor()->getMock(); + $this->l10n = $this->getMockBuilder('OCP\IL10N')->disableOriginalConstructor()->getMock(); + $this->userSession = $this->getMockBuilder('OCP\IUserSession')->disableOriginalConstructor()->getMock(); + $this->clientService = $this->getMockBuilder('OCP\Http\Client\IClientService')->disableOriginalConstructor()->getMock(); $this->controller = new SaveToNextcloudController( 'federatedfilesharing', $this->request, $this->federatedShareProvider, $this->shareManager, $this->addressHandler, - $this->session + $this->session, + $this->l10n, + $this->userSession, + $this->clientService ); } diff --git a/apps/federatedfilesharing/tests/js/externalSpec.js b/apps/federatedfilesharing/tests/js/externalSpec.js new file mode 100644 index 00000000000..362df49252b --- /dev/null +++ b/apps/federatedfilesharing/tests/js/externalSpec.js @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2015 Vincent Petry + * + * This file is licensed under the Affero General Public License version 3 + * or later. + * + * See the COPYING-README file. + * + */ + +describe('OCA.Sharing external tests', function() { + var plugin; + var urlQueryStub; + var promptDialogStub; + var confirmDialogStub; + + function dummyShowDialog() { + var deferred = $.Deferred(); + deferred.resolve(); + return deferred.promise(); + } + + beforeEach(function() { + plugin = OCA.Sharing.ExternalShareDialogPlugin; + urlQueryStub = sinon.stub(OC.Util.History, 'parseUrlQuery'); + + confirmDialogStub = sinon.stub(OC.dialogs, 'confirm', dummyShowDialog); + promptDialogStub = sinon.stub(OC.dialogs, 'prompt', dummyShowDialog); + + plugin.filesApp = { + fileList: { + reload: sinon.stub() + } + }; + }); + afterEach(function() { + urlQueryStub.restore(); + confirmDialogStub.restore(); + promptDialogStub.restore(); + plugin = null; + }); + describe('confirmation dialog from URL', function() { + var testShare; + + /** + * Checks that the server call's query matches what is + * expected. + * + * @param {Object} expectedQuery expected query params + */ + function checkRequest(expectedQuery) { + var request = fakeServer.requests[0]; + var query = OC.parseQueryString(request.requestBody); + expect(request.method).toEqual('POST'); + expect(query).toEqual(expectedQuery); + + request.respond( + 200, + {'Content-Type': 'application/json'}, + JSON.stringify({status: 'success'}) + ); + expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); + } + + beforeEach(function() { + testShare = { + remote: 'http://example.com/owncloud', + token: 'abcdefg', + owner: 'theowner', + ownerDisplayName: 'The Generous Owner', + name: 'the share name' + }; + }); + it('does nothing when no share was passed in URL', function() { + urlQueryStub.returns({}); + plugin.processIncomingShareFromUrl(); + expect(promptDialogStub.notCalled).toEqual(true); + expect(confirmDialogStub.notCalled).toEqual(true); + expect(fakeServer.requests.length).toEqual(0); + }); + it('sends share info to server on confirm', function() { + urlQueryStub.returns(testShare); + plugin.processIncomingShareFromUrl(); + expect(promptDialogStub.notCalled).toEqual(true); + expect(confirmDialogStub.calledOnce).toEqual(true); + confirmDialogStub.getCall(0).args[2](true); + expect(fakeServer.requests.length).toEqual(1); + checkRequest({ + remote: 'http://example.com/owncloud', + token: 'abcdefg', + owner: 'theowner', + ownerDisplayName: 'The Generous Owner', + name: 'the share name', + password: '' + }); + }); + it('sends share info with password to server on confirm', function() { + testShare = _.extend(testShare, {protected: 1}); + urlQueryStub.returns(testShare); + plugin.processIncomingShareFromUrl(); + expect(promptDialogStub.calledOnce).toEqual(true); + expect(confirmDialogStub.notCalled).toEqual(true); + promptDialogStub.getCall(0).args[2](true, 'thepassword'); + expect(fakeServer.requests.length).toEqual(1); + checkRequest({ + remote: 'http://example.com/owncloud', + token: 'abcdefg', + owner: 'theowner', + ownerDisplayName: 'The Generous Owner', + name: 'the share name', + password: 'thepassword' + }); + }); + it('does not send share info on cancel', function() { + urlQueryStub.returns(testShare); + plugin.processIncomingShareFromUrl(); + expect(promptDialogStub.notCalled).toEqual(true); + expect(confirmDialogStub.calledOnce).toEqual(true); + confirmDialogStub.getCall(0).args[2](false); + expect(fakeServer.requests.length).toEqual(0); + }); + }); + describe('show dialog for each share to confirm', function() { + var testShare; + + /** + * Call processSharesToConfirm() and make the fake server + * return the passed response. + * + * @param {Array} response list of shares to process + */ + function processShares(response) { + plugin.processSharesToConfirm(); + + expect(fakeServer.requests.length).toEqual(1); + + var req = fakeServer.requests[0]; + expect(req.method).toEqual('GET'); + expect(req.url).toEqual(OC.webroot + '/index.php/apps/files_sharing/api/externalShares'); + + req.respond( + 200, + {'Content-Type': 'application/json'}, + JSON.stringify(response) + ); + } + + beforeEach(function() { + testShare = { + id: 123, + remote: 'http://example.com/owncloud', + token: 'abcdefg', + owner: 'theowner', + ownerDisplayName: 'The Generous Owner', + name: 'the share name' + }; + }); + + it('does not show any dialog if no shares to confirm', function() { + processShares([]); + expect(confirmDialogStub.notCalled).toEqual(true); + expect(promptDialogStub.notCalled).toEqual(true); + }); + it('sends accept info to server on confirm', function() { + processShares([testShare]); + + expect(promptDialogStub.notCalled).toEqual(true); + expect(confirmDialogStub.calledOnce).toEqual(true); + + confirmDialogStub.getCall(0).args[2](true); + + expect(fakeServer.requests.length).toEqual(2); + + var request = fakeServer.requests[1]; + var query = OC.parseQueryString(request.requestBody); + expect(request.method).toEqual('POST'); + expect(query).toEqual({id: '123'}); + expect(request.url).toEqual( + OC.webroot + '/index.php/apps/files_sharing/api/externalShares' + ); + + expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); + request.respond( + 200, + {'Content-Type': 'application/json'}, + JSON.stringify({status: 'success'}) + ); + expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); + }); + it('sends delete info to server on cancel', function() { + processShares([testShare]); + + expect(promptDialogStub.notCalled).toEqual(true); + expect(confirmDialogStub.calledOnce).toEqual(true); + + confirmDialogStub.getCall(0).args[2](false); + + expect(fakeServer.requests.length).toEqual(2); + + var request = fakeServer.requests[1]; + expect(request.method).toEqual('DELETE'); + expect(request.url).toEqual( + OC.webroot + '/index.php/apps/files_sharing/api/externalShares/123' + ); + + expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); + request.respond( + 200, + {'Content-Type': 'application/json'}, + JSON.stringify({status: 'success'}) + ); + expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); + }); + xit('shows another dialog when multiple shares need to be accepted', function() { + // TODO: enable this test when fixing multiple dialogs issue / confirm loop + var testShare2 = _.extend({}, testShare); + testShare2.id = 256; + processShares([testShare, testShare2]); + + // confirm first one + expect(confirmDialogStub.calledOnce).toEqual(true); + confirmDialogStub.getCall(0).args[2](true); + + // next dialog not shown yet + expect(confirmDialogStub.calledOnce); + + // respond to the first accept request + fakeServer.requests[1].respond( + 200, + {'Content-Type': 'application/json'}, + JSON.stringify({status: 'success'}) + ); + + // don't reload yet, there are other shares to confirm + expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); + + // cancel second share + expect(confirmDialogStub.calledTwice).toEqual(true); + confirmDialogStub.getCall(1).args[2](true); + + // reload only called at the very end + expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); + }); + }); +}); diff --git a/apps/files_sharing/ajax/external.php b/apps/files_sharing/ajax/external.php deleted file mode 100644 index 20c3706c12d..00000000000 --- a/apps/files_sharing/ajax/external.php +++ /dev/null @@ -1,74 +0,0 @@ - - * @author Joas Schilling - * @author Lukas Reschke - * @author Morris Jobke - * @author Robin Appelman - * @author Roeland Jago Douma - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -OCP\JSON::callCheck(); -OCP\JSON::checkLoggedIn(); -OCP\JSON::checkAppEnabled('files_sharing'); - -$l = \OC::$server->getL10N('files_sharing'); - -$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application('federatedfilesharing'); -$federatedShareProvider = $federatedSharingApp->getFederatedShareProvider(); - -// check if server admin allows to mount public links from other servers -if ($federatedShareProvider->isIncomingServer2serverShareEnabled() === false) { - \OCP\JSON::error(array('data' => array('message' => $l->t('Server to server sharing is not enabled on this server')))); - exit(); -} - -$token = $_POST['token']; -$remote = $_POST['remote']; -$password = isset($_POST['password']) ? $_POST['password'] : ''; - -$urlGenerator = \OC::$server->getURLGenerator(); - -$shareWith = \OCP\User::getUser() . '@' . $urlGenerator->getAbsoluteURL('/'); - -$httpClient = \OC::$server->getHTTPClientService()->newClient(); - -try { - $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/saveToNextcloud', - [ - 'body' => - [ - 'token' => $token, - 'shareWith' => rtrim($shareWith, '/'), - 'password' => $password - ] - ] - ); -} catch (\Exception $e) { - if (empty($password)) { - $message = $l->t("Couldn't establish a federated share."); - } else { - $message = $l->t("Couldn't establish a federated share, maybe the password was wrong."); - } - \OCP\JSON::error(array('data' => array('message' => $message))); - exit(); -} - -\OCP\JSON::success(array('data' => array('message' => $l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')))); diff --git a/apps/files_sharing/appinfo/app.php b/apps/files_sharing/appinfo/app.php index c6ae6903eec..219fa298d51 100644 --- a/apps/files_sharing/appinfo/app.php +++ b/apps/files_sharing/appinfo/app.php @@ -46,9 +46,6 @@ $eventDispatcher->addListener( function() { \OCP\Util::addScript('files_sharing', 'share'); \OCP\Util::addScript('files_sharing', 'sharetabview'); - if (\OC::$server->getConfig()->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'yes') { - \OCP\Util::addScript('files_sharing', 'external'); - } \OCP\Util::addStyle('files_sharing', 'sharetabview'); } ); diff --git a/apps/files_sharing/appinfo/routes.php b/apps/files_sharing/appinfo/routes.php index 0e72934d094..26d32c3a990 100644 --- a/apps/files_sharing/appinfo/routes.php +++ b/apps/files_sharing/appinfo/routes.php @@ -53,8 +53,6 @@ $this->create('files_sharing_ajax_publicpreview', 'ajax/publicpreview.php') ->actionInclude('files_sharing/ajax/publicpreview.php'); $this->create('sharing_external_shareinfo', '/shareinfo') ->actionInclude('files_sharing/ajax/shareinfo.php'); -$this->create('sharing_external_add', '/external') - ->actionInclude('files_sharing/ajax/external.php'); // OCS API diff --git a/apps/files_sharing/js/external.js b/apps/files_sharing/js/external.js deleted file mode 100644 index a04a5721f37..00000000000 --- a/apps/files_sharing/js/external.js +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2014 Robin Appelman - * - * This file is licensed under the Affero General Public License version 3 - * or later. - * - * See the COPYING-README file. - * - */ -(function () { - /** - * Shows "add external share" dialog. - * - * @param {String} remote remote server URL - * @param {String} owner owner name - * @param {String} name name of the shared folder - * @param {String} token authentication token - * @param {bool} passwordProtected true if the share is password protected - */ - OCA.Sharing.showAddExternalDialog = function (share, passwordProtected, callback) { - var remote = share.remote; - var owner = share.ownerDisplayName || share.owner; - var name = share.name; - var remoteClean = (remote.substr(0, 8) === 'https://') ? remote.substr(8) : remote.substr(7); - - if (!passwordProtected) { - OC.dialogs.confirm( - t( - 'files_sharing', - 'Do you want to add the remote share {name} from {owner}@{remote}?', - {name: name, owner: owner, remote: remoteClean} - ), - t('files_sharing','Remote share'), - function (result) { - callback(result, share); - }, - true - ).then(this._adjustDialog); - } else { - OC.dialogs.prompt( - t( - 'files_sharing', - 'Do you want to add the remote share {name} from {owner}@{remote}?', - {name: name, owner: owner, remote: remoteClean} - ), - t('files_sharing','Remote share'), - function (result, password) { - share.password = password; - callback(result, share); - }, - true, - t('files_sharing','Remote share password'), - true - ).then(this._adjustDialog); - } - }; - - OCA.Sharing._adjustDialog = function() { - var $dialog = $('.oc-dialog:visible'); - var $buttons = $dialog.find('button'); - // hack the buttons - $dialog.find('.ui-icon').remove(); - $buttons.eq(0).text(t('core', 'Cancel')); - $buttons.eq(1).text(t('files_sharing', 'Add remote share')); - }; - - OCA.Sharing.ExternalShareDialogPlugin = { - - filesApp: null, - - attach: function(filesApp) { - var self = this; - this.filesApp = filesApp; - this.processIncomingShareFromUrl(); - - if (!$('#header').find('div.notifications').length) { - // No notification app, display the modal - this.processSharesToConfirm(); - } - - $('body').on('OCA.Notification.Action', function(e) { - if (e.notification.app === 'files_sharing' && e.notification.object_type === 'remote_share' && e.action.type === 'POST') { - // User accepted a remote share reload - self.filesApp.fileList.reload(); - } - }); - }, - - /** - * Process incoming remote share that might have been passed - * through the URL - */ - processIncomingShareFromUrl: function() { - var fileList = this.filesApp.fileList; - var params = OC.Util.History.parseUrlQuery(); - //manually add server-to-server share - if (params.remote && params.token && params.owner && params.name) { - - var callbackAddShare = function(result, share) { - var password = share.password || ''; - if (result) { - $.post(OC.generateUrl('apps/files_sharing/external'), { - remote: share.remote, - token: share.token, - owner: share.owner, - ownerDisplayName: share.ownerDisplayName || share.owner, - name: share.name, - password: password}, function(result) { - OC.Notification.showTemporary(result.data.message); - }); - } - }; - - // clear hash, it is unlikely that it contain any extra parameters - location.hash = ''; - params.passwordProtected = parseInt(params.protected, 10) === 1; - OCA.Sharing.showAddExternalDialog( - params, - params.passwordProtected, - callbackAddShare - ); - } - }, - - /** - * Retrieve a list of remote shares that need to be approved - */ - processSharesToConfirm: function() { - var fileList = this.filesApp.fileList; - // check for new server-to-server shares which need to be approved - $.get(OC.generateUrl('/apps/files_sharing/api/externalShares'), - {}, - function(shares) { - var index; - for (index = 0; index < shares.length; ++index) { - OCA.Sharing.showAddExternalDialog( - shares[index], - false, - function(result, share) { - if (result) { - // Accept - $.post(OC.generateUrl('/apps/files_sharing/api/externalShares'), {id: share.id}) - .then(function() { - fileList.reload(); - }); - } else { - // Delete - $.ajax({ - url: OC.generateUrl('/apps/files_sharing/api/externalShares/'+share.id), - type: 'DELETE' - }); - } - } - ); - } - - }); - - } - }; -})(); - -OC.Plugins.register('OCA.Files.App', OCA.Sharing.ExternalShareDialogPlugin); - diff --git a/apps/files_sharing/js/public.js b/apps/files_sharing/js/public.js index 6bc31879d0f..a7d0c15a01a 100644 --- a/apps/files_sharing/js/public.js +++ b/apps/files_sharing/js/public.js @@ -356,7 +356,7 @@ OCA.Sharing.PublicApp = { toggleLoading(); - if (remote.indexOf('@') == -1) { + if (remote.indexOf('@') === -1) { this._legacySaveToNextcloud(remote, token, owner, ownerDisplayName, name, isProtected); toggleLoading(); return; @@ -380,8 +380,6 @@ OCA.Sharing.PublicApp = { } ).fail( function (jqXHR) { - console.log("ERROR!"); - console.log(jqXHR); OC.dialogs.alert(JSON.parse(jqXHR.responseText).message, t('files_sharing', 'Failed to add the public link to your Nextcloud')); toggleLoading(); diff --git a/apps/files_sharing/tests/js/externalSpec.js b/apps/files_sharing/tests/js/externalSpec.js deleted file mode 100644 index 362df49252b..00000000000 --- a/apps/files_sharing/tests/js/externalSpec.js +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (c) 2015 Vincent Petry - * - * This file is licensed under the Affero General Public License version 3 - * or later. - * - * See the COPYING-README file. - * - */ - -describe('OCA.Sharing external tests', function() { - var plugin; - var urlQueryStub; - var promptDialogStub; - var confirmDialogStub; - - function dummyShowDialog() { - var deferred = $.Deferred(); - deferred.resolve(); - return deferred.promise(); - } - - beforeEach(function() { - plugin = OCA.Sharing.ExternalShareDialogPlugin; - urlQueryStub = sinon.stub(OC.Util.History, 'parseUrlQuery'); - - confirmDialogStub = sinon.stub(OC.dialogs, 'confirm', dummyShowDialog); - promptDialogStub = sinon.stub(OC.dialogs, 'prompt', dummyShowDialog); - - plugin.filesApp = { - fileList: { - reload: sinon.stub() - } - }; - }); - afterEach(function() { - urlQueryStub.restore(); - confirmDialogStub.restore(); - promptDialogStub.restore(); - plugin = null; - }); - describe('confirmation dialog from URL', function() { - var testShare; - - /** - * Checks that the server call's query matches what is - * expected. - * - * @param {Object} expectedQuery expected query params - */ - function checkRequest(expectedQuery) { - var request = fakeServer.requests[0]; - var query = OC.parseQueryString(request.requestBody); - expect(request.method).toEqual('POST'); - expect(query).toEqual(expectedQuery); - - request.respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify({status: 'success'}) - ); - expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); - } - - beforeEach(function() { - testShare = { - remote: 'http://example.com/owncloud', - token: 'abcdefg', - owner: 'theowner', - ownerDisplayName: 'The Generous Owner', - name: 'the share name' - }; - }); - it('does nothing when no share was passed in URL', function() { - urlQueryStub.returns({}); - plugin.processIncomingShareFromUrl(); - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.notCalled).toEqual(true); - expect(fakeServer.requests.length).toEqual(0); - }); - it('sends share info to server on confirm', function() { - urlQueryStub.returns(testShare); - plugin.processIncomingShareFromUrl(); - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.calledOnce).toEqual(true); - confirmDialogStub.getCall(0).args[2](true); - expect(fakeServer.requests.length).toEqual(1); - checkRequest({ - remote: 'http://example.com/owncloud', - token: 'abcdefg', - owner: 'theowner', - ownerDisplayName: 'The Generous Owner', - name: 'the share name', - password: '' - }); - }); - it('sends share info with password to server on confirm', function() { - testShare = _.extend(testShare, {protected: 1}); - urlQueryStub.returns(testShare); - plugin.processIncomingShareFromUrl(); - expect(promptDialogStub.calledOnce).toEqual(true); - expect(confirmDialogStub.notCalled).toEqual(true); - promptDialogStub.getCall(0).args[2](true, 'thepassword'); - expect(fakeServer.requests.length).toEqual(1); - checkRequest({ - remote: 'http://example.com/owncloud', - token: 'abcdefg', - owner: 'theowner', - ownerDisplayName: 'The Generous Owner', - name: 'the share name', - password: 'thepassword' - }); - }); - it('does not send share info on cancel', function() { - urlQueryStub.returns(testShare); - plugin.processIncomingShareFromUrl(); - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.calledOnce).toEqual(true); - confirmDialogStub.getCall(0).args[2](false); - expect(fakeServer.requests.length).toEqual(0); - }); - }); - describe('show dialog for each share to confirm', function() { - var testShare; - - /** - * Call processSharesToConfirm() and make the fake server - * return the passed response. - * - * @param {Array} response list of shares to process - */ - function processShares(response) { - plugin.processSharesToConfirm(); - - expect(fakeServer.requests.length).toEqual(1); - - var req = fakeServer.requests[0]; - expect(req.method).toEqual('GET'); - expect(req.url).toEqual(OC.webroot + '/index.php/apps/files_sharing/api/externalShares'); - - req.respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify(response) - ); - } - - beforeEach(function() { - testShare = { - id: 123, - remote: 'http://example.com/owncloud', - token: 'abcdefg', - owner: 'theowner', - ownerDisplayName: 'The Generous Owner', - name: 'the share name' - }; - }); - - it('does not show any dialog if no shares to confirm', function() { - processShares([]); - expect(confirmDialogStub.notCalled).toEqual(true); - expect(promptDialogStub.notCalled).toEqual(true); - }); - it('sends accept info to server on confirm', function() { - processShares([testShare]); - - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.calledOnce).toEqual(true); - - confirmDialogStub.getCall(0).args[2](true); - - expect(fakeServer.requests.length).toEqual(2); - - var request = fakeServer.requests[1]; - var query = OC.parseQueryString(request.requestBody); - expect(request.method).toEqual('POST'); - expect(query).toEqual({id: '123'}); - expect(request.url).toEqual( - OC.webroot + '/index.php/apps/files_sharing/api/externalShares' - ); - - expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); - request.respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify({status: 'success'}) - ); - expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); - }); - it('sends delete info to server on cancel', function() { - processShares([testShare]); - - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.calledOnce).toEqual(true); - - confirmDialogStub.getCall(0).args[2](false); - - expect(fakeServer.requests.length).toEqual(2); - - var request = fakeServer.requests[1]; - expect(request.method).toEqual('DELETE'); - expect(request.url).toEqual( - OC.webroot + '/index.php/apps/files_sharing/api/externalShares/123' - ); - - expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); - request.respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify({status: 'success'}) - ); - expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); - }); - xit('shows another dialog when multiple shares need to be accepted', function() { - // TODO: enable this test when fixing multiple dialogs issue / confirm loop - var testShare2 = _.extend({}, testShare); - testShare2.id = 256; - processShares([testShare, testShare2]); - - // confirm first one - expect(confirmDialogStub.calledOnce).toEqual(true); - confirmDialogStub.getCall(0).args[2](true); - - // next dialog not shown yet - expect(confirmDialogStub.calledOnce); - - // respond to the first accept request - fakeServer.requests[1].respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify({status: 'success'}) - ); - - // don't reload yet, there are other shares to confirm - expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); - - // cancel second share - expect(confirmDialogStub.calledTwice).toEqual(true); - confirmDialogStub.getCall(1).args[2](true); - - // reload only called at the very end - expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); - }); - }); -}); -- cgit v1.2.3 From 55b990b544c3db1c8814bb541aababf4a23324f8 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Wed, 13 Jul 2016 11:32:27 +0200 Subject: allow to mount public link from Nextclouds <= 9 --- apps/federatedfilesharing/js/external.js | 7 +- .../lib/Controller/SaveToNextcloudController.php | 134 ++++++++++++++++++++- 2 files changed, 136 insertions(+), 5 deletions(-) (limited to 'apps') diff --git a/apps/federatedfilesharing/js/external.js b/apps/federatedfilesharing/js/external.js index e8262092ee8..1daecd2e744 100644 --- a/apps/federatedfilesharing/js/external.js +++ b/apps/federatedfilesharing/js/external.js @@ -91,6 +91,7 @@ * through the URL */ processIncomingShareFromUrl: function() { + var fileList = this.filesApp.fileList; var params = OC.Util.History.parseUrlQuery(); //manually add server-to-server share if (params.remote && params.token && params.owner && params.name) { @@ -110,7 +111,11 @@ } ).done( function(data) { - OC.Notification.showTemporary(data.message); + if (data.hasOwnProperty('legacyMount')) { + fileList.reload(); + } else { + OC.Notification.showTemporary(data.message); + } } ).fail( function(data) { diff --git a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php index 8801d7af4e4..5b05d196e26 100644 --- a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php +++ b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php @@ -1,6 +1,6 @@ + * @author Björn Schießle * * @copyright Copyright (c) 2016, ownCloud, Inc. * @license AGPL-3.0 @@ -140,9 +140,12 @@ class SaveToNextcloudController extends Controller { * @param string $token * @param string $remote * @param string $password + * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink()) + * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink()) + * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink()) * @return JSONResponse */ - public function askForFederatedShare($token, $remote, $password = '') { + public function askForFederatedShare($token, $remote, $password = '', $owner='', $ownerDisplayName = '', $name = '') { // check if server admin allows to mount public links from other servers if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) { return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST); @@ -153,7 +156,7 @@ class SaveToNextcloudController extends Controller { $httpClient = $this->clientService->newClient(); try { - $httpClient->post($remote . '/index.php/apps/federatedfilesharing/saveToNextcloud', + $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/saveToNextcloud', [ 'body' => [ @@ -172,7 +175,130 @@ class SaveToNextcloudController extends Controller { return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST); } - return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]); + $body = $response->getBody(); + $result = json_decode($body, true); + + if (is_array($result) && isset($result['remoteUrl'])) { + return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]); + } + + // if we doesn't get the expected response we assume that we try to add + // a federated share from a Nextcloud <= 9 server + return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName); + } + + /** + * Allow Nextcloud to mount a public link directly + * + * This code was copied from the apps/files_sharing/ajax/external.php with + * minimal changes, just to guarantee backward compatibility + * + * ToDo: Remove this method once Nextcloud 9 reaches end of life + * + * @param string $token + * @param string $remote + * @param string $password + * @param string $name + * @param string $owner + * @param string $ownerDisplayName + * @return JSONResponse + */ + private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) { + + // Check for invalid name + if (!\OCP\Util::isValidFileName($name)) { + return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST); + } + $currentUser = $this->userSession->getUser()->getUID(); + $currentServer = $this->addressHandler->generateRemoteURL(); + if (\OC\Share\Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) { + return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST); + } + $discoveryManager = new \OCA\FederatedFileSharing\DiscoveryManager( + \OC::$server->getMemCacheFactory(), + \OC::$server->getHTTPClientService() + ); + $externalManager = new \OCA\Files_Sharing\External\Manager( + \OC::$server->getDatabaseConnection(), + \OC\Files\Filesystem::getMountManager(), + \OC\Files\Filesystem::getLoader(), + \OC::$server->getHTTPHelper(), + \OC::$server->getNotificationManager(), + $discoveryManager, + \OC::$server->getUserSession()->getUser()->getUID() + ); + + // check for ssl cert + if (substr($remote, 0, 5) === 'https') { + try { + $client = $this->clientService->newClient(); + $client->get($remote, [ + 'timeout' => 10, + 'connect_timeout' => 10, + ])->getBody(); + } catch (\Exception $e) { + return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST); + } + } + $mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true); + /** + * @var \OCA\Files_Sharing\External\Storage $storage + */ + $storage = $mount->getStorage(); + try { + // check if storage exists + $storage->checkStorageAvailability(); + } catch (\OCP\Files\StorageInvalidException $e) { + // note: checkStorageAvailability will already remove the invalid share + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), + \OCP\Util::DEBUG + ); + return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST); + } catch (\Exception $e) { + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), + \OCP\Util::DEBUG + ); + $externalManager->removeShare($mount->getMountPoint()); + return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST); + } + $result = $storage->file_exists(''); + if ($result) { + try { + $storage->getScanner()->scanAll(); + return new JSONResponse( + [ + 'message' => $this->l->t('Federated Share successfully added'), + 'legacyMount' => '1' + ] + ); + } catch (\OCP\Files\StorageInvalidException $e) { + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), + \OCP\Util::DEBUG + ); + return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST); + } catch (\Exception $e) { + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), + \OCP\Util::DEBUG + ); + return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST); + } + } else { + $externalManager->removeShare($mount->getMountPoint()); + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Couldn\'t add remote share', + \OCP\Util::DEBUG + ); + return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST); + } } -- cgit v1.2.3 From dc53788711316fc5d812dc059567813f656a0fa5 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Wed, 13 Jul 2016 12:39:20 +0200 Subject: remove unused parameter --- apps/dav/appinfo/v1/publicwebdav.php | 2 +- apps/federatedfilesharing/settings-admin.php | 2 +- apps/federatedfilesharing/settings-personal.php | 2 +- apps/files_sharing/ajax/shareinfo.php | 2 +- apps/files_sharing/lib/AppInfo/Application.php | 2 +- apps/files_sharing/lib/share/file.php | 2 +- ocs/routes.php | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) (limited to 'apps') diff --git a/apps/dav/appinfo/v1/publicwebdav.php b/apps/dav/appinfo/v1/publicwebdav.php index 261a4d4b96d..2202cbb977c 100644 --- a/apps/dav/appinfo/v1/publicwebdav.php +++ b/apps/dav/appinfo/v1/publicwebdav.php @@ -57,7 +57,7 @@ $linkCheckPlugin = new \OCA\DAV\Files\Sharing\PublicLinkCheckPlugin(); $server = $serverFactory->createServer($baseuri, $requestUri, $authBackend, function (\Sabre\DAV\Server $server) use ($authBackend, $linkCheckPlugin) { $isAjax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'); - $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application('federatedfilesharing'); + $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application(); $federatedShareProvider = $federatedSharingApp->getFederatedShareProvider(); if ($federatedShareProvider->isOutgoingServer2serverShareEnabled() === false && !$isAjax) { // this is what is thrown when trying to access a non-existing share diff --git a/apps/federatedfilesharing/settings-admin.php b/apps/federatedfilesharing/settings-admin.php index 9875dcf3b5b..dc5a4d6826c 100644 --- a/apps/federatedfilesharing/settings-admin.php +++ b/apps/federatedfilesharing/settings-admin.php @@ -22,7 +22,7 @@ use OCA\FederatedFileSharing\AppInfo\Application; -$app = new Application('federatedfilesharing'); +$app = new Application(); $federatedShareProvider = $app->getFederatedShareProvider(); $tmpl = new OCP\Template('federatedfilesharing', 'settings-admin'); diff --git a/apps/federatedfilesharing/settings-personal.php b/apps/federatedfilesharing/settings-personal.php index a36cdd712c4..261d540f48d 100644 --- a/apps/federatedfilesharing/settings-personal.php +++ b/apps/federatedfilesharing/settings-personal.php @@ -27,7 +27,7 @@ use OCA\FederatedFileSharing\AppInfo\Application; $l = \OC::$server->getL10N('federatedfilesharing'); -$app = new Application('federatedfilesharing'); +$app = new Application(); $federatedShareProvider = $app->getFederatedShareProvider(); $isIE8 = false; diff --git a/apps/files_sharing/ajax/shareinfo.php b/apps/files_sharing/ajax/shareinfo.php index 0b93e3d2ee9..31b8e00f496 100644 --- a/apps/files_sharing/ajax/shareinfo.php +++ b/apps/files_sharing/ajax/shareinfo.php @@ -31,7 +31,7 @@ if (!isset($_GET['t'])) { exit; } -$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application('federatedfilesharing'); +$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application(); $federatedShareProvider = $federatedSharingApp->getFederatedShareProvider(); if ($federatedShareProvider->isOutgoingServer2serverShareEnabled() === false) { diff --git a/apps/files_sharing/lib/AppInfo/Application.php b/apps/files_sharing/lib/AppInfo/Application.php index fda16c7acac..5ed8d886e2e 100644 --- a/apps/files_sharing/lib/AppInfo/Application.php +++ b/apps/files_sharing/lib/AppInfo/Application.php @@ -46,7 +46,7 @@ class Application extends App { * Controllers */ $container->registerService('ShareController', function (SimpleContainer $c) use ($server) { - $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application('federatedfilesharing'); + $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application(); return new ShareController( $c->query('AppName'), $c->query('Request'), diff --git a/apps/files_sharing/lib/share/file.php b/apps/files_sharing/lib/share/file.php index 4643e46eeb2..e7588a589e8 100644 --- a/apps/files_sharing/lib/share/file.php +++ b/apps/files_sharing/lib/share/file.php @@ -77,7 +77,7 @@ class OC_Share_Backend_File implements OCP\Share_Backend_File_Dependent { if ($federatedShareProvider) { $this->federatedShareProvider = $federatedShareProvider; } else { - $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application('federatedfilesharing'); + $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application(); $this->federatedShareProvider = $federatedSharingApp->getFederatedShareProvider(); } } diff --git a/ocs/routes.php b/ocs/routes.php index d9c78a4a16a..c465e08e877 100644 --- a/ocs/routes.php +++ b/ocs/routes.php @@ -99,7 +99,7 @@ API::register( // Server-to-Server Sharing if (\OC::$server->getAppManager()->isEnabledForUser('files_sharing')) { - $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application('federatedfilesharing'); + $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application(); $addressHandler = new \OCA\FederatedFileSharing\AddressHandler( \OC::$server->getURLGenerator(), \OC::$server->getL10N('federatedfilesharing') -- cgit v1.2.3 From 56d3100f44e5541c2b19ee24fa37df372a809372 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Wed, 13 Jul 2016 17:50:06 +0200 Subject: adjust copyright notices --- apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php | 2 ++ .../tests/Controller/SaveToNextcloudControllerTest.php | 2 ++ apps/files_sharing/js/public.js | 1 + 3 files changed, 5 insertions(+) (limited to 'apps') diff --git a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php index 5b05d196e26..c95b50ecf46 100644 --- a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php +++ b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php @@ -3,6 +3,8 @@ * @author Björn Schießle * * @copyright Copyright (c) 2016, ownCloud, Inc. + * @copyright Copyright (c) 2016, Björn Schießle + * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify diff --git a/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php b/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php index 0e36df9b25a..a98e4e4d09e 100644 --- a/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php @@ -3,6 +3,8 @@ * @author Björn Schießle * * @copyright Copyright (c) 2016, ownCloud, Inc. + * @copyright Copyright (c) 2016, Björn Schießle + * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify diff --git a/apps/files_sharing/js/public.js b/apps/files_sharing/js/public.js index a7d0c15a01a..5746f4dbb8c 100644 --- a/apps/files_sharing/js/public.js +++ b/apps/files_sharing/js/public.js @@ -1,5 +1,6 @@ /* * Copyright (c) 2014 + * @copyright Copyright (c) 2016, Björn Schießle * * This file is licensed under the Affero General Public License version 3 * or later. -- cgit v1.2.3 From c7f6461c53e1d432f268305e63eb9a604e12cba4 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Thu, 14 Jul 2016 11:01:25 +0200 Subject: rename SaveToNextcloudController to MountPublicLinkController --- apps/federatedfilesharing/appinfo/routes.php | 4 +- .../lib/Controller/MountPublicLinkController.php | 314 +++++++++++++++++++++ .../lib/Controller/SaveToNextcloudController.php | 307 -------------------- .../Controller/MountPublicLinkControllerTest.php | 186 ++++++++++++ .../Controller/SaveToNextcloudControllerTest.php | 187 ------------ apps/files_sharing/js/public.js | 10 +- 6 files changed, 507 insertions(+), 501 deletions(-) create mode 100644 apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php delete mode 100644 apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php create mode 100644 apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php delete mode 100644 apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php (limited to 'apps') diff --git a/apps/federatedfilesharing/appinfo/routes.php b/apps/federatedfilesharing/appinfo/routes.php index c5822c6b653..ec7b662686f 100644 --- a/apps/federatedfilesharing/appinfo/routes.php +++ b/apps/federatedfilesharing/appinfo/routes.php @@ -21,7 +21,7 @@ return [ 'routes' => [ - ['name' => 'SaveToNextcloud#saveToNextcloud', 'url' => '/saveToNextcloud', 'verb' => 'POST'], - ['name' => 'SaveToNextcloud#askForFederatedShare', 'url' => '/askForFederatedShare', 'verb' => 'POST'], + ['name' => 'MountPublicLink#createFederatedShare', 'url' => '/createFederatedShare', 'verb' => 'POST'], + ['name' => 'MountPublicLink#askForFederatedShare', 'url' => '/askForFederatedShare', 'verb' => 'POST'], ] ]; diff --git a/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php new file mode 100644 index 00000000000..ec70090f97a --- /dev/null +++ b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php @@ -0,0 +1,314 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @copyright Copyright (c) 2016, Björn Schießle + * + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + + +namespace OCA\FederatedFileSharing\Controller; + +use OC\HintException; +use OCA\FederatedFileSharing\AddressHandler; +use OCA\FederatedFileSharing\FederatedShareProvider; +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\JSONResponse; +use OCP\Http\Client\IClientService; +use OCP\IL10N; +use OCP\IRequest; +use OCP\ISession; +use OCP\IUserSession; +use OCP\Share\IManager; + +/** + * Class MountPublicLinkController + * + * convert public links to federated shares + * + * @package OCA\FederatedFileSharing\Controller + */ +class MountPublicLinkController extends Controller { + + /** @var FederatedShareProvider */ + private $federatedShareProvider; + + /** @var AddressHandler */ + private $addressHandler; + + /** @var IManager */ + private $shareManager; + + /** @var ISession */ + private $session; + + /** @var IL10N */ + private $l; + + /** @var IUserSession */ + private $userSession; + + /** @var IClientService */ + private $clientService; + + /** + * MountPublicLinkController constructor. + * + * @param string $appName + * @param IRequest $request + * @param FederatedShareProvider $federatedShareProvider + * @param IManager $shareManager + * @param AddressHandler $addressHandler + * @param ISession $session + * @param IL10N $l + * @param IUserSession $userSession + * @param IClientService $clientService + */ + public function __construct($appName, + IRequest $request, + FederatedShareProvider $federatedShareProvider, + IManager $shareManager, + AddressHandler $addressHandler, + ISession $session, + IL10N $l, + IUserSession $userSession, + IClientService $clientService + ) { + parent::__construct($appName, $request); + + $this->federatedShareProvider = $federatedShareProvider; + $this->shareManager = $shareManager; + $this->addressHandler = $addressHandler; + $this->session = $session; + $this->l = $l; + $this->userSession = $userSession; + $this->clientService = $clientService; + } + + /** + * send federated share to a user of a public link + * + * @NoCSRFRequired + * @PublicPage + * + * @param string $shareWith + * @param string $token + * @param string $password + * @return JSONResponse + */ + public function createFederatedShare($shareWith, $token, $password = '') { + + try { + list(, $server) = $this->addressHandler->splitUserRemote($shareWith); + $share = $this->shareManager->getShareByToken($token); + } catch (HintException $e) { + return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST); + } + + // make sure that user is authenticated in case of a password protected link + $storedPassword = $share->getPassword(); + $authenticated = $this->session->get('public_link_authenticated') === $share->getId() || + $this->shareManager->checkPassword($share, $password); + if (!empty($storedPassword) && !$authenticated ) { + return new JSONResponse(['message' => 'No permission to access the share'], Http::STATUS_BAD_REQUEST); + } + + $share->setSharedWith($shareWith); + + try { + $this->federatedShareProvider->create($share); + } catch (\Exception $e) { + return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); + } + + return new JSONResponse(['remoteUrl' => $server]); + } + + /** + * ask other server to get a federated share + * + * @NoAdminRequired + * + * @param string $token + * @param string $remote + * @param string $password + * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink()) + * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink()) + * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink()) + * @return JSONResponse + */ + public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') { + // check if server admin allows to mount public links from other servers + if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) { + return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST); + } + + $shareWith = $this->userSession->getUser()->getUID() . '@' . $this->addressHandler->generateRemoteURL(); + + $httpClient = $this->clientService->newClient(); + + try { + $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare', + [ + 'body' => + [ + 'token' => $token, + 'shareWith' => rtrim($shareWith, '/'), + 'password' => $password + ], + 'connect_timeout' => 10, + ] + ); + } catch (\Exception $e) { + if (empty($password)) { + $message = $this->l->t("Couldn't establish a federated share."); + } else { + $message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong."); + } + return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST); + } + + $body = $response->getBody(); + $result = json_decode($body, true); + + if (is_array($result) && isset($result['remoteUrl'])) { + return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]); + } + + // if we doesn't get the expected response we assume that we try to add + // a federated share from a Nextcloud <= 9 server + return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName); + } + + /** + * Allow Nextcloud to mount a public link directly + * + * This code was copied from the apps/files_sharing/ajax/external.php with + * minimal changes, just to guarantee backward compatibility + * + * ToDo: Remove this method once Nextcloud 9 reaches end of life + * + * @param string $token + * @param string $remote + * @param string $password + * @param string $name + * @param string $owner + * @param string $ownerDisplayName + * @return JSONResponse + */ + private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) { + + // Check for invalid name + if (!\OCP\Util::isValidFileName($name)) { + return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST); + } + $currentUser = $this->userSession->getUser()->getUID(); + $currentServer = $this->addressHandler->generateRemoteURL(); + if (\OC\Share\Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) { + return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST); + } + $discoveryManager = new \OCA\FederatedFileSharing\DiscoveryManager( + \OC::$server->getMemCacheFactory(), + \OC::$server->getHTTPClientService() + ); + $externalManager = new \OCA\Files_Sharing\External\Manager( + \OC::$server->getDatabaseConnection(), + \OC\Files\Filesystem::getMountManager(), + \OC\Files\Filesystem::getLoader(), + \OC::$server->getHTTPHelper(), + \OC::$server->getNotificationManager(), + $discoveryManager, + \OC::$server->getUserSession()->getUser()->getUID() + ); + + // check for ssl cert + if (substr($remote, 0, 5) === 'https') { + try { + $client = $this->clientService->newClient(); + $client->get($remote, [ + 'timeout' => 10, + 'connect_timeout' => 10, + ])->getBody(); + } catch (\Exception $e) { + return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST); + } + } + $mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true); + /** + * @var \OCA\Files_Sharing\External\Storage $storage + */ + $storage = $mount->getStorage(); + try { + // check if storage exists + $storage->checkStorageAvailability(); + } catch (\OCP\Files\StorageInvalidException $e) { + // note: checkStorageAvailability will already remove the invalid share + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), + \OCP\Util::DEBUG + ); + return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST); + } catch (\Exception $e) { + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), + \OCP\Util::DEBUG + ); + $externalManager->removeShare($mount->getMountPoint()); + return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST); + } + $result = $storage->file_exists(''); + if ($result) { + try { + $storage->getScanner()->scanAll(); + return new JSONResponse( + [ + 'message' => $this->l->t('Federated Share successfully added'), + 'legacyMount' => '1' + ] + ); + } catch (\OCP\Files\StorageInvalidException $e) { + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), + \OCP\Util::DEBUG + ); + return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST); + } catch (\Exception $e) { + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), + \OCP\Util::DEBUG + ); + return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST); + } + } else { + $externalManager->removeShare($mount->getMountPoint()); + \OCP\Util::writeLog( + 'federatedfilesharing', + 'Couldn\'t add remote share', + \OCP\Util::DEBUG + ); + return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST); + } + + } + +} diff --git a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php b/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php deleted file mode 100644 index c95b50ecf46..00000000000 --- a/apps/federatedfilesharing/lib/Controller/SaveToNextcloudController.php +++ /dev/null @@ -1,307 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @copyright Copyright (c) 2016, Björn Schießle - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - - -namespace OCA\FederatedFileSharing\Controller; - -use OC\HintException; -use OCA\FederatedFileSharing\AddressHandler; -use OCA\FederatedFileSharing\FederatedShareProvider; -use OCP\AppFramework\Controller; -use OCP\AppFramework\Http; -use OCP\AppFramework\Http\JSONResponse; -use OCP\Http\Client\IClientService; -use OCP\IL10N; -use OCP\IRequest; -use OCP\ISession; -use OCP\IUserSession; -use OCP\Share\IManager; - -class SaveToNextcloudController extends Controller { - - /** @var FederatedShareProvider */ - private $federatedShareProvider; - - /** @var AddressHandler */ - private $addressHandler; - - /** @var IManager */ - private $shareManager; - - /** @var ISession */ - private $session; - - /** @var IL10N */ - private $l; - - /** @var IUserSession */ - private $userSession; - - /** @var IClientService */ - private $clientService; - - /** - * SaveToNextcloudController constructor. - * - * @param string $appName - * @param IRequest $request - * @param FederatedShareProvider $federatedShareProvider - * @param IManager $shareManager - * @param AddressHandler $addressHandler - * @param ISession $session - * @param IL10N $l - * @param IUserSession $userSession - * @param IClientService $clientService - */ - public function __construct($appName, - IRequest $request, - FederatedShareProvider $federatedShareProvider, - IManager $shareManager, - AddressHandler $addressHandler, - ISession $session, - IL10N $l, - IUserSession $userSession, - IClientService $clientService - ) { - parent::__construct($appName, $request); - - $this->federatedShareProvider = $federatedShareProvider; - $this->shareManager = $shareManager; - $this->addressHandler = $addressHandler; - $this->session = $session; - $this->l = $l; - $this->userSession = $userSession; - $this->clientService = $clientService; - } - - /** - * save public link to my Nextcloud by asking the owner to create a federated - * share with me - * - * @NoCSRFRequired - * @PublicPage - * - * @param string $shareWith - * @param string $token - * @param string $password - * @return JSONResponse - */ - public function saveToNextcloud($shareWith, $token, $password = '') { - - try { - list(, $server) = $this->addressHandler->splitUserRemote($shareWith); - $share = $this->shareManager->getShareByToken($token); - } catch (HintException $e) { - return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST); - } - - // make sure that user is authenticated in case of a password protected link - $storedPassword = $share->getPassword(); - $authenticated = $this->session->get('public_link_authenticated') === $share->getId() || - $this->shareManager->checkPassword($share, $password); - if (!empty($storedPassword) && !$authenticated ) { - return new JSONResponse(['message' => 'No permission to access the share'], Http::STATUS_BAD_REQUEST); - } - - $share->setSharedWith($shareWith); - - try { - $this->federatedShareProvider->create($share); - } catch (\Exception $e) { - return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); - } - - return new JSONResponse(['remoteUrl' => $server]); - } - - /** - * ask other server to get a federated share - * - * @NoAdminRequired - * - * @param string $token - * @param string $remote - * @param string $password - * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink()) - * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink()) - * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink()) - * @return JSONResponse - */ - public function askForFederatedShare($token, $remote, $password = '', $owner='', $ownerDisplayName = '', $name = '') { - // check if server admin allows to mount public links from other servers - if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) { - return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST); - } - - $shareWith = $this->userSession->getUser()->getUID() . '@' . $this->addressHandler->generateRemoteURL(); - - $httpClient = $this->clientService->newClient(); - - try { - $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/saveToNextcloud', - [ - 'body' => - [ - 'token' => $token, - 'shareWith' => rtrim($shareWith, '/'), - 'password' => $password - ] - ] - ); - } catch (\Exception $e) { - if (empty($password)) { - $message = $this->l->t("Couldn't establish a federated share."); - } else { - $message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong."); - } - return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST); - } - - $body = $response->getBody(); - $result = json_decode($body, true); - - if (is_array($result) && isset($result['remoteUrl'])) { - return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]); - } - - // if we doesn't get the expected response we assume that we try to add - // a federated share from a Nextcloud <= 9 server - return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName); - } - - /** - * Allow Nextcloud to mount a public link directly - * - * This code was copied from the apps/files_sharing/ajax/external.php with - * minimal changes, just to guarantee backward compatibility - * - * ToDo: Remove this method once Nextcloud 9 reaches end of life - * - * @param string $token - * @param string $remote - * @param string $password - * @param string $name - * @param string $owner - * @param string $ownerDisplayName - * @return JSONResponse - */ - private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) { - - // Check for invalid name - if (!\OCP\Util::isValidFileName($name)) { - return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST); - } - $currentUser = $this->userSession->getUser()->getUID(); - $currentServer = $this->addressHandler->generateRemoteURL(); - if (\OC\Share\Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) { - return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST); - } - $discoveryManager = new \OCA\FederatedFileSharing\DiscoveryManager( - \OC::$server->getMemCacheFactory(), - \OC::$server->getHTTPClientService() - ); - $externalManager = new \OCA\Files_Sharing\External\Manager( - \OC::$server->getDatabaseConnection(), - \OC\Files\Filesystem::getMountManager(), - \OC\Files\Filesystem::getLoader(), - \OC::$server->getHTTPHelper(), - \OC::$server->getNotificationManager(), - $discoveryManager, - \OC::$server->getUserSession()->getUser()->getUID() - ); - - // check for ssl cert - if (substr($remote, 0, 5) === 'https') { - try { - $client = $this->clientService->newClient(); - $client->get($remote, [ - 'timeout' => 10, - 'connect_timeout' => 10, - ])->getBody(); - } catch (\Exception $e) { - return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST); - } - } - $mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true); - /** - * @var \OCA\Files_Sharing\External\Storage $storage - */ - $storage = $mount->getStorage(); - try { - // check if storage exists - $storage->checkStorageAvailability(); - } catch (\OCP\Files\StorageInvalidException $e) { - // note: checkStorageAvailability will already remove the invalid share - \OCP\Util::writeLog( - 'federatedfilesharing', - 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), - \OCP\Util::DEBUG - ); - return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST); - } catch (\Exception $e) { - \OCP\Util::writeLog( - 'federatedfilesharing', - 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), - \OCP\Util::DEBUG - ); - $externalManager->removeShare($mount->getMountPoint()); - return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST); - } - $result = $storage->file_exists(''); - if ($result) { - try { - $storage->getScanner()->scanAll(); - return new JSONResponse( - [ - 'message' => $this->l->t('Federated Share successfully added'), - 'legacyMount' => '1' - ] - ); - } catch (\OCP\Files\StorageInvalidException $e) { - \OCP\Util::writeLog( - 'federatedfilesharing', - 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), - \OCP\Util::DEBUG - ); - return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST); - } catch (\Exception $e) { - \OCP\Util::writeLog( - 'federatedfilesharing', - 'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(), - \OCP\Util::DEBUG - ); - return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST); - } - } else { - $externalManager->removeShare($mount->getMountPoint()); - \OCP\Util::writeLog( - 'federatedfilesharing', - 'Couldn\'t add remote share', - \OCP\Util::DEBUG - ); - return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST); - } - - } - -} diff --git a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php new file mode 100644 index 00000000000..816fc90c4e1 --- /dev/null +++ b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php @@ -0,0 +1,186 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @copyright Copyright (c) 2016, Björn Schießle + * + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + + +namespace OCA\FederatedFileSharing\Tests\Controller; + +use OC\HintException; +use OCA\FederatedFileSharing\AddressHandler; +use OCA\FederatedFileSharing\Controller\MountPublicLinkController; +use OCA\FederatedFileSharing\FederatedShareProvider; +use OCP\AppFramework\Http; +use OCP\Files\IRootFolder; +use OCP\Http\Client\IClientService; +use OCP\IL10N; +use OCP\ISession; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Share\IManager; +use OCP\Share\IShare; + +class MountPublicLinkControllerTest extends \Test\TestCase { + + /** @var MountPublicLinkController */ + private $controller; + + /** @var \OCP\IRequest | \PHPUnit_Framework_MockObject_MockObject */ + private $request; + + /** @var FederatedShareProvider | \PHPUnit_Framework_MockObject_MockObject */ + private $federatedShareProvider; + + /** @var IManager | \PHPUnit_Framework_MockObject_MockObject */ + private $shareManager; + + /** @var AddressHandler | \PHPUnit_Framework_MockObject_MockObject */ + private $addressHandler; + + /** @var IRootFolder | \PHPUnit_Framework_MockObject_MockObject */ + private $rootFolder; + + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */ + private $userManager; + + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject */ + private $session; + + /** @var IL10N | \PHPUnit_Framework_MockObject_MockObject */ + private $l10n; + + /** @var IUserSession | \PHPUnit_Framework_MockObject_MockObject */ + private $userSession; + + /** @var IClientService | \PHPUnit_Framework_MockObject_MockObject */ + private $clientService; + + /** @var IShare */ + private $share; + + public function setUp() { + parent::setUp(); + + $this->request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); + $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') + ->disableOriginalConstructor()->getMock(); + $this->shareManager = $this->getMockBuilder('OCP\Share\IManager')->disableOriginalConstructor()->getMock(); + $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') + ->disableOriginalConstructor()->getMock(); + $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->disableOriginalConstructor()->getMock(); + $this->userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); + $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); + $this->session = $this->getMockBuilder('OCP\ISession')->disableOriginalConstructor()->getMock(); + $this->l10n = $this->getMockBuilder('OCP\IL10N')->disableOriginalConstructor()->getMock(); + $this->userSession = $this->getMockBuilder('OCP\IUserSession')->disableOriginalConstructor()->getMock(); + $this->clientService = $this->getMockBuilder('OCP\Http\Client\IClientService')->disableOriginalConstructor()->getMock(); + + $this->controller = new MountPublicLinkController( + 'federatedfilesharing', $this->request, + $this->federatedShareProvider, + $this->shareManager, + $this->addressHandler, + $this->session, + $this->l10n, + $this->userSession, + $this->clientService + ); + } + + /** + * @dataProvider dataTestCreateFederatedShare + * + * @param string $shareWith + * @param bool $validShareWith + * @param string $token + * @param bool $validToken + * @param bool $createSuccessful + * @param string $expectedReturnData + */ + public function testCreateFederatedShare($shareWith, $validShareWith, $token, $validToken, $createSuccessful, $expectedReturnData) { + $this->addressHandler->expects($this->any())->method('splitUserRemote') + ->with($shareWith) + ->willReturnCallback( + function($shareWith) use ($validShareWith, $expectedReturnData) { + if ($validShareWith) { + return ['user', 'server']; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $share = $this->share; + + $this->shareManager->expects($this->any())->method('getShareByToken') + ->with($token) + ->willReturnCallback( + function ($token) use ($validToken, $share, $expectedReturnData) { + if ($validToken) { + return $share; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $this->federatedShareProvider->expects($this->any())->method('create') + ->with($share) + ->willReturnCallback( + function (IShare $share) use ($createSuccessful, $shareWith, $expectedReturnData) { + $this->assertEquals($shareWith, $share->getSharedWith()); + if ($createSuccessful) { + return $share; + } + throw new HintException($expectedReturnData, $expectedReturnData); + } + ); + + $result = $this->controller->createFederatedShare($shareWith, $token); + + $errorCase = !$validShareWith || !$validToken || !$createSuccessful; + + if ($errorCase) { + $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus()); + $this->assertTrue(isset($result->getData()['message'])); + $this->assertSame($expectedReturnData, $result->getData()['message']); + } else { + $this->assertSame(Http::STATUS_OK, $result->getStatus()); + $this->assertTrue(isset($result->getData()['remoteUrl'])); + $this->assertSame($expectedReturnData, $result->getData()['remoteUrl']); + + } + + } + + public function dataTestCreateFederatedShare() { + return [ + //shareWith, validShareWith, token, validToken, createSuccessful, expectedReturnData + ['user@server', true, 'token', true, true, 'server'], + ['user@server', false, 'token', true, true, 'invalid federated cloud id'], + ['user@server', false, 'token', false, true, 'invalid federated cloud id'], + ['user@server', false, 'token', false, false, 'invalid federated cloud id'], + ['user@server', false, 'token', true, false, 'invalid federated cloud id'], + ['user@server', true, 'token', false, true, 'invalid token'], + ['user@server', true, 'token', false, false, 'invalid token'], + ['user@server', true, 'token', true, false, 'can not create share'] + ]; + } + +} diff --git a/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php b/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php deleted file mode 100644 index a98e4e4d09e..00000000000 --- a/apps/federatedfilesharing/tests/Controller/SaveToNextcloudControllerTest.php +++ /dev/null @@ -1,187 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @copyright Copyright (c) 2016, Björn Schießle - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - - -namespace OCA\FederatedFileSharing\Tests\Controller; - -use OC\HintException; -use OCA\FederatedFileSharing\AddressHandler; -use OCA\FederatedFileSharing\Controller\SaveToNextcloudController; -use OCA\FederatedFileSharing\FederatedShareProvider; -use OCP\AppFramework\Http; -use OCP\Files\IRootFolder; -use OCP\Http\Client\IClientService; -use OCP\IL10N; -use OCP\ISession; -use OCP\IUserManager; -use OCP\IUserSession; -use OCP\Share; -use OCP\Share\IManager; -use OCP\Share\IShare; - -class SaveToNextcloudControllerTest extends \Test\TestCase { - - /** @var SaveToNextcloudController */ - private $controller; - - /** @var \OCP\IRequest | \PHPUnit_Framework_MockObject_MockObject */ - private $request; - - /** @var FederatedShareProvider | \PHPUnit_Framework_MockObject_MockObject */ - private $federatedShareProvider; - - /** @var IManager | \PHPUnit_Framework_MockObject_MockObject */ - private $shareManager; - - /** @var AddressHandler | \PHPUnit_Framework_MockObject_MockObject */ - private $addressHandler; - - /** @var IRootFolder | \PHPUnit_Framework_MockObject_MockObject */ - private $rootFolder; - - /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */ - private $userManager; - - /** @var ISession | \PHPUnit_Framework_MockObject_MockObject */ - private $session; - - /** @var IL10N | \PHPUnit_Framework_MockObject_MockObject */ - private $l10n; - - /** @var IUserSession | \PHPUnit_Framework_MockObject_MockObject */ - private $userSession; - - /** @var IClientService | \PHPUnit_Framework_MockObject_MockObject */ - private $clientService; - - /** @var IShare */ - private $share; - - public function setUp() { - parent::setUp(); - - $this->request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); - $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') - ->disableOriginalConstructor()->getMock(); - $this->shareManager = $this->getMockBuilder('OCP\Share\IManager')->disableOriginalConstructor()->getMock(); - $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') - ->disableOriginalConstructor()->getMock(); - $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->disableOriginalConstructor()->getMock(); - $this->userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); - $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); - $this->session = $this->getMockBuilder('OCP\ISession')->disableOriginalConstructor()->getMock(); - $this->l10n = $this->getMockBuilder('OCP\IL10N')->disableOriginalConstructor()->getMock(); - $this->userSession = $this->getMockBuilder('OCP\IUserSession')->disableOriginalConstructor()->getMock(); - $this->clientService = $this->getMockBuilder('OCP\Http\Client\IClientService')->disableOriginalConstructor()->getMock(); - - $this->controller = new SaveToNextcloudController( - 'federatedfilesharing', $this->request, - $this->federatedShareProvider, - $this->shareManager, - $this->addressHandler, - $this->session, - $this->l10n, - $this->userSession, - $this->clientService - ); - } - - /** - * @dataProvider dataTestSaveToNextcloud - * - * @param string $shareWith - * @param bool $validShareWith - * @param string $token - * @param bool $validToken - * @param bool $createSuccessful - * @param string $expectedReturnData - */ - public function testSaveToNextcloud($shareWith, $validShareWith, $token, $validToken, $createSuccessful, $expectedReturnData) { - $this->addressHandler->expects($this->any())->method('splitUserRemote') - ->with($shareWith) - ->willReturnCallback( - function($shareWith) use ($validShareWith, $expectedReturnData) { - if ($validShareWith) { - return ['user', 'server']; - } - throw new HintException($expectedReturnData, $expectedReturnData); - } - ); - - $share = $this->share; - - $this->shareManager->expects($this->any())->method('getShareByToken') - ->with($token) - ->willReturnCallback( - function ($token) use ($validToken, $share, $expectedReturnData) { - if ($validToken) { - return $share; - } - throw new HintException($expectedReturnData, $expectedReturnData); - } - ); - - $this->federatedShareProvider->expects($this->any())->method('create') - ->with($share) - ->willReturnCallback( - function (IShare $share) use ($createSuccessful, $shareWith, $expectedReturnData) { - $this->assertEquals($shareWith, $share->getSharedWith()); - if ($createSuccessful) { - return $share; - } - throw new HintException($expectedReturnData, $expectedReturnData); - } - ); - - $result = $this->controller->saveToNextcloud($shareWith, $token); - - $errorCase = !$validShareWith || !$validToken || !$createSuccessful; - - if ($errorCase) { - $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus()); - $this->assertTrue(isset($result->getData()['message'])); - $this->assertSame($expectedReturnData, $result->getData()['message']); - } else { - $this->assertSame(Http::STATUS_OK, $result->getStatus()); - $this->assertTrue(isset($result->getData()['remoteUrl'])); - $this->assertSame($expectedReturnData, $result->getData()['remoteUrl']); - - } - - } - - public function dataTestSaveToNextcloud() { - return [ - //shareWith, validShareWith, token, validToken, createSuccessful, expectedReturnData - ['user@server', true, 'token', true, true, 'server'], - ['user@server', false, 'token', true, true, 'invalid federated cloud id'], - ['user@server', false, 'token', false, true, 'invalid federated cloud id'], - ['user@server', false, 'token', false, false, 'invalid federated cloud id'], - ['user@server', false, 'token', true, false, 'invalid federated cloud id'], - ['user@server', true, 'token', false, true, 'invalid token'], - ['user@server', true, 'token', false, false, 'invalid token'], - ['user@server', true, 'token', true, false, 'can not create share'] - ]; - } - -} diff --git a/apps/files_sharing/js/public.js b/apps/files_sharing/js/public.js index 5746f4dbb8c..0dfff235998 100644 --- a/apps/files_sharing/js/public.js +++ b/apps/files_sharing/js/public.js @@ -248,7 +248,7 @@ OCA.Sharing.PublicApp = { var ownerDisplayName = $('#save').data('owner-display-name'); var name = $('#save').data('name'); var isProtected = $('#save').data('protected') ? 1 : 0; - OCA.Sharing.PublicApp._saveToNextcloud(remote, token, owner, ownerDisplayName, name, isProtected); + OCA.Sharing.PublicApp._createFederatedShare(remote, token, owner, ownerDisplayName, name, isProtected); }); $('#remote_address').on("keyup paste", function() { @@ -308,7 +308,7 @@ OCA.Sharing.PublicApp = { * @param isProtected * @private */ - _legacySaveToNextcloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { + _legacyCreateFederatedShare: function (remote, token, owner, ownerDisplayName, name, isProtected) { var location = window.location.protocol + '//' + window.location.host + OC.webroot; @@ -336,7 +336,7 @@ OCA.Sharing.PublicApp = { } }, - _saveToNextcloud: function (remote, token, owner, ownerDisplayName, name, isProtected) { + _createFederatedShare: function (remote, token, owner, ownerDisplayName, name, isProtected) { var toggleLoading = function() { var iconClass = $('#save-button-confirm').attr('class'); @@ -358,13 +358,13 @@ OCA.Sharing.PublicApp = { toggleLoading(); if (remote.indexOf('@') === -1) { - this._legacySaveToNextcloud(remote, token, owner, ownerDisplayName, name, isProtected); + this._legacyCreateFederatedShare(remote, token, owner, ownerDisplayName, name, isProtected); toggleLoading(); return; } $.post( - OC.generateUrl('/apps/federatedfilesharing/saveToNextcloud'), + OC.generateUrl('/apps/federatedfilesharing/createFederatedShare'), { 'shareWith': remote, 'token': token -- cgit v1.2.3 From f8a531c06c8095be4edcbd70063437e67833668e Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Thu, 14 Jul 2016 20:41:10 +0200 Subject: don't convert link share to federated share if outgoing federated shares are forbidden --- .../lib/Controller/MountPublicLinkController.php | 12 +++++++- .../Controller/MountPublicLinkControllerTest.php | 36 +++++++++++++++------- 2 files changed, 36 insertions(+), 12 deletions(-) (limited to 'apps') diff --git a/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php index ec70090f97a..3e61d355b63 100644 --- a/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php +++ b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php @@ -114,6 +114,13 @@ class MountPublicLinkController extends Controller { */ public function createFederatedShare($shareWith, $token, $password = '') { + if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) { + return new JSONResponse( + ['message' => 'This server doesn\'t support outgoing federated shares'], + Http::STATUS_BAD_REQUEST + ); + } + try { list(, $server) = $this->addressHandler->splitUserRemote($shareWith); $share = $this->shareManager->getShareByToken($token); @@ -126,7 +133,10 @@ class MountPublicLinkController extends Controller { $authenticated = $this->session->get('public_link_authenticated') === $share->getId() || $this->shareManager->checkPassword($share, $password); if (!empty($storedPassword) && !$authenticated ) { - return new JSONResponse(['message' => 'No permission to access the share'], Http::STATUS_BAD_REQUEST); + return new JSONResponse( + ['message' => 'No permission to access the share'], + Http::STATUS_BAD_REQUEST + ); } $share->setSharedWith($shareWith); diff --git a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php index 816fc90c4e1..3fe05e72cf4 100644 --- a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php @@ -109,13 +109,26 @@ class MountPublicLinkControllerTest extends \Test\TestCase { * @dataProvider dataTestCreateFederatedShare * * @param string $shareWith + * @param bool $outgoingSharesAllowed * @param bool $validShareWith * @param string $token * @param bool $validToken * @param bool $createSuccessful * @param string $expectedReturnData */ - public function testCreateFederatedShare($shareWith, $validShareWith, $token, $validToken, $createSuccessful, $expectedReturnData) { + public function testCreateFederatedShare($shareWith, + $outgoingSharesAllowed, + $validShareWith, + $token, + $validToken, + $createSuccessful, + $expectedReturnData + ) { + + $this->federatedShareProvider->expects($this->any()) + ->method('isOutgoingServer2serverShareEnabled') + ->willReturn($outgoingSharesAllowed); + $this->addressHandler->expects($this->any())->method('splitUserRemote') ->with($shareWith) ->willReturnCallback( @@ -154,7 +167,7 @@ class MountPublicLinkControllerTest extends \Test\TestCase { $result = $this->controller->createFederatedShare($shareWith, $token); - $errorCase = !$validShareWith || !$validToken || !$createSuccessful; + $errorCase = !$validShareWith || !$validToken || !$createSuccessful || !$outgoingSharesAllowed; if ($errorCase) { $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus()); @@ -171,15 +184,16 @@ class MountPublicLinkControllerTest extends \Test\TestCase { public function dataTestCreateFederatedShare() { return [ - //shareWith, validShareWith, token, validToken, createSuccessful, expectedReturnData - ['user@server', true, 'token', true, true, 'server'], - ['user@server', false, 'token', true, true, 'invalid federated cloud id'], - ['user@server', false, 'token', false, true, 'invalid federated cloud id'], - ['user@server', false, 'token', false, false, 'invalid federated cloud id'], - ['user@server', false, 'token', true, false, 'invalid federated cloud id'], - ['user@server', true, 'token', false, true, 'invalid token'], - ['user@server', true, 'token', false, false, 'invalid token'], - ['user@server', true, 'token', true, false, 'can not create share'] + //shareWith, outgoingSharesAllowed, validShareWith, token, validToken, createSuccessful, expectedReturnData + ['user@server', true, true, 'token', true, true, 'server'], + ['user@server', true, false, 'token', true, true, 'invalid federated cloud id'], + ['user@server', true, false, 'token', false, true, 'invalid federated cloud id'], + ['user@server', true, false, 'token', false, false, 'invalid federated cloud id'], + ['user@server', true, false, 'token', true, false, 'invalid federated cloud id'], + ['user@server', true, true, 'token', false, true, 'invalid token'], + ['user@server', true, true, 'token', false, false, 'invalid token'], + ['user@server', true, true, 'token', true, false, 'can not create share'], + ['user@server', false, true, 'token', true, true, 'This server doesn\'t support outgoing federated shares'], ]; } -- cgit v1.2.3