diff options
author | Morris Jobke <hey@morrisjobke.de> | 2016-07-18 09:22:48 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2016-07-18 09:22:48 +0200 |
commit | 40328114f9a3625a554a9f8ed842272809485f08 (patch) | |
tree | 9a0af3e8e0d13b4b05acaa6344e1b9321b027ed1 /apps/federatedfilesharing | |
parent | 2526c227ed9613ad9fd965e117d2342ddb97cf29 (diff) | |
parent | f8a531c06c8095be4edcbd70063437e67833668e (diff) | |
download | nextcloud-server-40328114f9a3625a554a9f8ed842272809485f08.tar.gz nextcloud-server-40328114f9a3625a554a9f8ed842272809485f08.zip |
Merge pull request #379 from nextcloud/create_federated_share_on_mount
Create federated share on mount
Diffstat (limited to 'apps/federatedfilesharing')
10 files changed, 996 insertions, 8 deletions
diff --git a/apps/federatedfilesharing/appinfo/app.php b/apps/federatedfilesharing/appinfo/app.php index 5891b9cbbc1..e6fbe615e7f 100644 --- a/apps/federatedfilesharing/appinfo/app.php +++ b/apps/federatedfilesharing/appinfo/app.php @@ -20,11 +20,11 @@ * */ -$app = new \OCA\FederatedFileSharing\AppInfo\Application('federatedfilesharing'); - 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 new file mode 100644 index 00000000000..ec7b662686f --- /dev/null +++ b/apps/federatedfilesharing/appinfo/routes.php @@ -0,0 +1,27 @@ +<?php +/** + * @copyright Copyright (c) 2016 Bjoern Schiessle <bjoern@schiessle.org> + * + * @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 <http://www.gnu.org/licenses/>. + * + */ + +return [ + 'routes' => [ + ['name' => 'MountPublicLink#createFederatedShare', 'url' => '/createFederatedShare', 'verb' => 'POST'], + ['name' => 'MountPublicLink#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..1daecd2e744 --- /dev/null +++ b/apps/federatedfilesharing/js/external.js @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com> + * + * 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/federatedfilesharing/askForFederatedShare'), + { + remote: share.remote, + token: share.token, + owner: share.owner, + ownerDisplayName: share.ownerDisplayName || share.owner, + name: share.name, + password: password + } + ).done( + function(data) { + if (data.hasOwnProperty('legacyMount')) { + fileList.reload(); + } else { + 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/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/MountPublicLinkController.php b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php new file mode 100644 index 00000000000..3e61d355b63 --- /dev/null +++ b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php @@ -0,0 +1,324 @@ +<?php +/** + * @author Björn Schießle <bjoern@schiessle.org> + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @copyright Copyright (c) 2016, Björn Schießle <bjoern@schiessle.org> + * + * @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 <http://www.gnu.org/licenses/> + * + */ + + +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 = '') { + + 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); + } 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/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/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/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php new file mode 100644 index 00000000000..3fe05e72cf4 --- /dev/null +++ b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php @@ -0,0 +1,200 @@ +<?php +/** + * @author Björn Schießle <schiessle@owncloud.com> + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @copyright Copyright (c) 2016, Björn Schießle <bjoern@schiessle.org> + * + * @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 <http://www.gnu.org/licenses/> + * + */ + + +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 $outgoingSharesAllowed + * @param bool $validShareWith + * @param string $token + * @param bool $validToken + * @param bool $createSuccessful + * @param string $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( + 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 || !$outgoingSharesAllowed; + + 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, 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'], + ]; + } + +} 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 <pvince81@owncloud.com> + * + * 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); + }); + }); +}); |