diff options
Diffstat (limited to 'apps/files_external')
47 files changed, 716 insertions, 65 deletions
diff --git a/apps/files_external/appinfo/application.php b/apps/files_external/appinfo/application.php index 1571178596b..1bf258c48b4 100644 --- a/apps/files_external/appinfo/application.php +++ b/apps/files_external/appinfo/application.php @@ -109,6 +109,7 @@ class Application extends App { $container->query('OCA\Files_External\Lib\Auth\Password\Password'), $container->query('OCA\Files_External\Lib\Auth\Password\SessionCredentials'), $container->query('OCA\Files_External\Lib\Auth\Password\LoginCredentials'), + $container->query('OCA\Files_External\Lib\Auth\Password\UserProvided'), // AuthMechanism::SCHEME_OAUTH1 mechanisms $container->query('OCA\Files_External\Lib\Auth\OAuth1\OAuth1'), diff --git a/apps/files_external/appinfo/register_command.php b/apps/files_external/appinfo/register_command.php index be32cd410f8..d85906e3831 100644 --- a/apps/files_external/appinfo/register_command.php +++ b/apps/files_external/appinfo/register_command.php @@ -25,6 +25,7 @@ use OCA\Files_External\Command\Config; use OCA\Files_External\Command\Option; use OCA\Files_External\Command\Import; use OCA\Files_External\Command\Export; +use OCA\Files_External\Command\Delete; $userManager = OC::$server->getUserManager(); $userSession = OC::$server->getUserSession(); @@ -42,3 +43,4 @@ $application->add(new Config($globalStorageService)); $application->add(new Option($globalStorageService)); $application->add(new Import($globalStorageService, $userStorageService, $userSession, $userManager, $importLegacyStorageService, $backendService)); $application->add(new Export($globalStorageService, $userStorageService, $userSession, $userManager)); +$application->add(new Delete($globalStorageService, $userStorageService, $userSession, $userManager)); diff --git a/apps/files_external/command/delete.php b/apps/files_external/command/delete.php new file mode 100644 index 00000000000..bdbfcf8bb55 --- /dev/null +++ b/apps/files_external/command/delete.php @@ -0,0 +1,114 @@ +<?php +/** + * @author Robin Appelman <icewind@owncloud.com> + * + * @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 <http://www.gnu.org/licenses/> + * + */ + +namespace OCA\Files_External\Command; + +use OC\Core\Command\Base; +use OCA\Files_external\Lib\StorageConfig; +use OCA\Files_external\NotFoundException; +use OCA\Files_external\Service\GlobalStoragesService; +use OCA\Files_external\Service\UserStoragesService; +use OCP\IUserManager; +use OCP\IUserSession; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Helper\Table; +use Symfony\Component\Console\Helper\TableHelper; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ConfirmationQuestion; + +class Delete extends Base { + /** + * @var GlobalStoragesService + */ + protected $globalService; + + /** + * @var UserStoragesService + */ + protected $userService; + + /** + * @var IUserSession + */ + protected $userSession; + + /** + * @var IUserManager + */ + protected $userManager; + + function __construct(GlobalStoragesService $globalService, UserStoragesService $userService, IUserSession $userSession, IUserManager $userManager) { + parent::__construct(); + $this->globalService = $globalService; + $this->userService = $userService; + $this->userSession = $userSession; + $this->userManager = $userManager; + } + + protected function configure() { + $this + ->setName('files_external:delete') + ->setDescription('Delete an external mount') + ->addArgument( + 'mount_id', + InputArgument::REQUIRED, + 'The id of the mount to edit' + )->addOption( + 'yes', + 'y', + InputOption::VALUE_NONE, + 'Skip confirmation' + ); + parent::configure(); + } + + protected function execute(InputInterface $input, OutputInterface $output) { + $mountId = $input->getArgument('mount_id'); + try { + $mount = $this->globalService->getStorage($mountId); + } catch (NotFoundException $e) { + $output->writeln('<error>Mount with id "' . $mountId . ' not found, check "occ files_external:list" to get available mounts"</error>'); + return 404; + } + + $noConfirm = $input->getOption('yes'); + + if (!$noConfirm) { + $listCommand = new ListCommand($this->globalService, $this->userService, $this->userSession, $this->userManager); + $listInput = new ArrayInput([], $listCommand->getDefinition()); + $listInput->setOption('output', $input->getOption('output')); + $listCommand->listMounts(null, [$mount], $listInput, $output); + + $questionHelper = $this->getHelper('question'); + $question = new ConfirmationQuestion('Delete this mount? [y/N] ', false); + + if (!$questionHelper->ask($input, $output, $question)) { + return; + } + } + + $this->globalService->removeStorage($mountId); + } +} diff --git a/apps/files_external/controller/globalstoragescontroller.php b/apps/files_external/controller/globalstoragescontroller.php index 64bbf0feb3f..069e41a96b8 100644 --- a/apps/files_external/controller/globalstoragescontroller.php +++ b/apps/files_external/controller/globalstoragescontroller.php @@ -24,6 +24,7 @@ namespace OCA\Files_External\Controller; use \OCP\IConfig; +use OCP\ILogger; use \OCP\IUserSession; use \OCP\IRequest; use \OCP\IL10N; @@ -46,18 +47,21 @@ class GlobalStoragesController extends StoragesController { * @param IRequest $request request object * @param IL10N $l10n l10n service * @param GlobalStoragesService $globalStoragesService storage service + * @param ILogger $logger */ public function __construct( $AppName, IRequest $request, IL10N $l10n, - GlobalStoragesService $globalStoragesService + GlobalStoragesService $globalStoragesService, + ILogger $logger ) { parent::__construct( $AppName, $request, $l10n, - $globalStoragesService + $globalStoragesService, + $logger ); } diff --git a/apps/files_external/controller/storagescontroller.php b/apps/files_external/controller/storagescontroller.php index cbdb27a972b..db1cdeb23b9 100644 --- a/apps/files_external/controller/storagescontroller.php +++ b/apps/files_external/controller/storagescontroller.php @@ -25,6 +25,8 @@ namespace OCA\Files_External\Controller; use \OCP\IConfig; +use OCP\ILogger; +use OCP\IUser; use \OCP\IUserSession; use \OCP\IRequest; use \OCP\IL10N; @@ -60,22 +62,30 @@ abstract class StoragesController extends Controller { protected $service; /** + * @var ILogger + */ + protected $logger; + + /** * Creates a new storages controller. * * @param string $AppName application name * @param IRequest $request request object * @param IL10N $l10n l10n service * @param StoragesService $storagesService storage service + * @param ILogger $logger */ public function __construct( $AppName, IRequest $request, IL10N $l10n, - StoragesService $storagesService + StoragesService $storagesService, + ILogger $logger ) { parent::__construct($AppName, $request); $this->l10n = $l10n; $this->service = $storagesService; + $this->logger = $logger; } /** @@ -114,6 +124,7 @@ abstract class StoragesController extends Controller { $priority ); } catch (\InvalidArgumentException $e) { + $this->logger->logException($e); return new DataResponse( [ 'message' => (string)$this->l10n->t('Invalid backend or authentication mechanism class') @@ -127,7 +138,7 @@ abstract class StoragesController extends Controller { * Validate storage config * * @param StorageConfig $storage storage config - * + *1 * @return DataResponse|null returns response in case of validation error */ protected function validate(StorageConfig $storage) { diff --git a/apps/files_external/controller/userglobalstoragescontroller.php b/apps/files_external/controller/userglobalstoragescontroller.php index 6d4548754df..c6b51d94047 100644 --- a/apps/files_external/controller/userglobalstoragescontroller.php +++ b/apps/files_external/controller/userglobalstoragescontroller.php @@ -22,10 +22,12 @@ namespace OCA\Files_External\Controller; use OCA\Files_External\Lib\Auth\AuthMechanism; +use OCA\Files_External\Lib\Auth\IUserProvided; +use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException; +use OCP\ILogger; use \OCP\IRequest; use \OCP\IL10N; use \OCP\AppFramework\Http\DataResponse; -use \OCP\AppFramework\Controller; use \OCP\AppFramework\Http; use \OCA\Files_external\Service\UserGlobalStoragesService; use \OCA\Files_external\NotFoundException; @@ -56,13 +58,15 @@ class UserGlobalStoragesController extends StoragesController { IRequest $request, IL10N $l10n, UserGlobalStoragesService $userGlobalStoragesService, - IUserSession $userSession + IUserSession $userSession, + ILogger $logger ) { parent::__construct( $AppName, $request, $l10n, - $userGlobalStoragesService + $userGlobalStoragesService, + $logger ); $this->userSession = $userSession; } @@ -128,6 +132,54 @@ class UserGlobalStoragesController extends StoragesController { } /** + * Update an external storage entry. + * Only allows setting user provided backend fields + * + * @param int $id storage id + * @param array $backendOptions backend-specific options + * + * @return DataResponse + * + * @NoAdminRequired + */ + public function update( + $id, + $backendOptions + ) { + try { + $storage = $this->service->getStorage($id); + $authMechanism = $storage->getAuthMechanism(); + if ($authMechanism instanceof IUserProvided) { + $authMechanism->saveBackendOptions($this->userSession->getUser(), $id, $backendOptions); + $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser()); + } else { + return new DataResponse( + [ + 'message' => (string)$this->l10n->t('Storage with id "%i" is not user editable', array($id)) + ], + Http::STATUS_FORBIDDEN + ); + } + } catch (NotFoundException $e) { + return new DataResponse( + [ + 'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id)) + ], + Http::STATUS_NOT_FOUND + ); + } + + $this->updateStorageStatus($storage); + $this->sanitizeStorage($storage); + + return new DataResponse( + $storage, + Http::STATUS_OK + ); + + } + + /** * Remove sensitive data from a StorageConfig before returning it to the user * * @param StorageConfig $storage @@ -135,6 +187,14 @@ class UserGlobalStoragesController extends StoragesController { protected function sanitizeStorage(StorageConfig $storage) { $storage->setBackendOptions([]); $storage->setMountOptions([]); + + if ($storage->getAuthMechanism() instanceof IUserProvided) { + try { + $storage->getAuthMechanism()->manipulateStorageConfig($storage, $this->userSession->getUser()); + } catch (InsufficientDataForMeaningfulAnswerException $e) { + // not configured yet + } + } } } diff --git a/apps/files_external/controller/userstoragescontroller.php b/apps/files_external/controller/userstoragescontroller.php index 741e906dec1..2a2a0bc63a6 100644 --- a/apps/files_external/controller/userstoragescontroller.php +++ b/apps/files_external/controller/userstoragescontroller.php @@ -25,6 +25,8 @@ namespace OCA\Files_External\Controller; use OCA\Files_External\Lib\Auth\AuthMechanism; use \OCP\IConfig; +use OCP\ILogger; +use OCP\IUser; use \OCP\IUserSession; use \OCP\IRequest; use \OCP\IL10N; @@ -54,19 +56,22 @@ class UserStoragesController extends StoragesController { * @param IL10N $l10n l10n service * @param UserStoragesService $userStoragesService storage service * @param IUserSession $userSession + * @param ILogger $logger */ public function __construct( $AppName, IRequest $request, IL10N $l10n, UserStoragesService $userStoragesService, - IUserSession $userSession + IUserSession $userSession, + ILogger $logger ) { parent::__construct( $AppName, $request, $l10n, - $userStoragesService + $userStoragesService, + $logger ); $this->userSession = $userSession; } diff --git a/apps/files_external/js/settings.js b/apps/files_external/js/settings.js index 2f879e1c850..ccb1e858fa0 100644 --- a/apps/files_external/js/settings.js +++ b/apps/files_external/js/settings.js @@ -59,10 +59,24 @@ function highlightBorder($element, highlight) { return highlight; } +function isInputValid($input) { + var optional = $input.hasClass('optional'); + switch ($input.attr('type')) { + case 'text': + case 'password': + if ($input.val() === '' && !optional) { + return false; + } + break; + } + return true; +} + function highlightInput($input) { - if ($input.attr('type') === 'text' || $input.attr('type') === 'password') { - return highlightBorder($input, - ($input.val() === '' && !$input.hasClass('optional'))); + switch ($input.attr('type')) { + case 'text': + case 'password': + return highlightBorder($input, !isInputValid($input)); } } @@ -192,6 +206,12 @@ StorageConfig.Status = { ERROR: 1, INDETERMINATE: 2 }; +StorageConfig.Visibility = { + NONE: 0, + PERSONAL: 1, + ADMIN: 2, + DEFAULT: 3 +}; /** * @memberof OCA.External.Settings */ @@ -343,6 +363,9 @@ StorageConfig.prototype = { if (this.mountPoint === '') { return false; } + if (!this.backend) { + return false; + } if (this.errors) { return false; } @@ -419,6 +442,21 @@ UserStorageConfig.prototype = _.extend({}, StorageConfig.prototype, }); /** + * @class OCA.External.Settings.UserGlobalStorageConfig + * @augments OCA.External.Settings.StorageConfig + * + * @classdesc User external storage config + */ +var UserGlobalStorageConfig = function (id) { + this.id = id; +}; +UserGlobalStorageConfig.prototype = _.extend({}, StorageConfig.prototype, + /** @lends OCA.External.Settings.UserStorageConfig.prototype */ { + + _url: 'apps/files_external/userglobalstorages' +}); + +/** * @class OCA.External.Settings.MountOptionsDropdown * * @classdesc Dropdown for mount options @@ -734,7 +772,7 @@ MountConfigListView.prototype = _.extend({ $.each(authMechanismConfiguration['configuration'], _.partial( this.writeParameterInput, $td, _, _, ['auth-param'] - )); + ).bind(this)); this.trigger('selectAuthMechanism', $tr, authMechanism, authMechanismConfiguration['scheme'], onCompletion @@ -756,6 +794,7 @@ MountConfigListView.prototype = _.extend({ var $tr = this.$el.find('tr#addMountPoint'); this.$el.find('tbody').append($tr.clone()); + $tr.data('storageConfig', storageConfig); $tr.find('td').last().attr('class', 'remove'); $tr.find('td.mountOptionsToggle').removeClass('hidden'); $tr.find('td').last().removeAttr('style'); @@ -776,8 +815,9 @@ MountConfigListView.prototype = _.extend({ $tr.find('.backend').data('identifier', backend.identifier); var selectAuthMechanism = $('<select class="selectAuthMechanism"></select>'); + var neededVisibility = (this._isPersonal) ? StorageConfig.Visibility.PERSONAL : StorageConfig.Visibility.ADMIN; $.each(this._allAuthMechanisms, function(authIdentifier, authMechanism) { - if (backend.authSchemes[authMechanism.scheme]) { + if (backend.authSchemes[authMechanism.scheme] && (authMechanism.visibility & neededVisibility)) { selectAuthMechanism.append( $('<option value="'+authMechanism.identifier+'" data-scheme="'+authMechanism.scheme+'">'+authMechanism.name+'</option>') ); @@ -791,7 +831,7 @@ MountConfigListView.prototype = _.extend({ $tr.find('td.authentication').append(selectAuthMechanism); var $td = $tr.find('td.configuration'); - $.each(backend.configuration, _.partial(this.writeParameterInput, $td)); + $.each(backend.configuration, _.partial(this.writeParameterInput, $td).bind(this)); this.trigger('selectBackend', $tr, backend.identifier, onCompletion); this.configureAuthMechanism($tr, storageConfig.authMechanism, onCompletion); @@ -852,8 +892,14 @@ MountConfigListView.prototype = _.extend({ success: function(result) { var onCompletion = jQuery.Deferred(); $.each(result, function(i, storageParams) { + var storageConfig; + var isUserGlobal = storageParams.type === 'system' && self._isPersonal; storageParams.mountPoint = storageParams.mountPoint.substr(1); // trim leading slash - var storageConfig = new self._storageConfigClass(); + if (isUserGlobal) { + storageConfig = new UserGlobalStorageConfig(); + } else { + storageConfig = new self._storageConfigClass(); + } _.extend(storageConfig, storageParams); var $tr = self.newStorage(storageConfig, onCompletion); @@ -864,12 +910,16 @@ MountConfigListView.prototype = _.extend({ var $authentication = $tr.find('.authentication'); $authentication.text($authentication.find('select option:selected').text()); - // userglobal storages do not expose configuration data - $tr.find('.configuration').text(t('files_external', 'Admin defined')); - // disable any other inputs $tr.find('.mountOptionsToggle, .remove').empty(); - $tr.find('input, select, button').attr('disabled', 'disabled'); + $tr.find('input:not(.user_provided), select:not(.user_provided)').attr('disabled', 'disabled'); + + if (isUserGlobal) { + $tr.find('.configuration').find(':not(.user_provided)').remove(); + } else { + // userglobal storages do not expose configuration data + $tr.find('.configuration').text(t('files_external', 'Admin defined')); + } }); onCompletion.resolve(); } @@ -904,22 +954,40 @@ MountConfigListView.prototype = _.extend({ * @return {jQuery} newly created input */ writeParameterInput: function($td, parameter, placeholder, classes) { + var hasFlag = function(flag) { + return placeholder.indexOf(flag) !== -1; + }; classes = $.isArray(classes) ? classes : []; classes.push('added'); if (placeholder.indexOf('&') === 0) { classes.push('optional'); placeholder = placeholder.substring(1); } + + if (hasFlag('@')) { + if (this._isPersonal) { + classes.push('user_provided'); + } else { + return; + } + } + var newElement; - if (placeholder.indexOf('*') === 0) { - newElement = $('<input type="password" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" placeholder="'+placeholder.substring(1)+'" />'); - } else if (placeholder.indexOf('!') === 0) { + + var trimmedPlaceholder = placeholder; + var flags = ['@', '*', '!', '#', '&']; // used to determine what kind of parameter + while(flags.indexOf(trimmedPlaceholder[0]) !== -1) { + trimmedPlaceholder = trimmedPlaceholder.substr(1); + } + if (hasFlag('*')) { + newElement = $('<input type="password" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" placeholder="'+ trimmedPlaceholder+'" />'); + } else if (hasFlag('!')) { var checkboxId = _.uniqueId('checkbox_'); - newElement = $('<input type="checkbox" id="'+checkboxId+'" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" /><label for="'+checkboxId+'">'+placeholder.substring(1)+'</label>'); - } else if (placeholder.indexOf('#') === 0) { + newElement = $('<input type="checkbox" id="'+checkboxId+'" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" /><label for="'+checkboxId+'">'+ trimmedPlaceholder+'</label>'); + } else if (hasFlag('#')) { newElement = $('<input type="hidden" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" />'); } else { - newElement = $('<input type="text" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" placeholder="'+placeholder+'" />'); + newElement = $('<input type="text" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" placeholder="'+ trimmedPlaceholder+'" />'); } highlightInput(newElement); $td.append(newElement); @@ -938,7 +1006,12 @@ MountConfigListView.prototype = _.extend({ // new entry storageId = null; } - var storage = new this._storageConfigClass(storageId); + + var storage = $tr.data('storageConfig'); + if (!storage) { + storage = new this._storageConfigClass(storageId); + } + storage.errors = null; storage.mountPoint = $tr.find('.mountPoint input').val(); storage.backend = $tr.find('.backend').data('identifier'); storage.authMechanism = $tr.find('.selectAuthMechanism').val(); @@ -952,7 +1025,7 @@ MountConfigListView.prototype = _.extend({ if ($input.attr('type') === 'button') { return; } - if ($input.val() === '' && !$input.hasClass('optional')) { + if (!isInputValid($input) && !$input.hasClass('optional')) { missingOptions.push(parameter); return; } @@ -980,7 +1053,7 @@ MountConfigListView.prototype = _.extend({ var users = []; var multiselect = getSelection($tr); $.each(multiselect, function(index, value) { - var pos = value.indexOf('(group)'); + var pos = (value.indexOf)?value.indexOf('(group)'): -1; if (pos !== -1) { groups.push(value.substr(0, pos)); } else { @@ -1043,7 +1116,7 @@ MountConfigListView.prototype = _.extend({ saveStorageConfig:function($tr, callback, concurrentTimer) { var self = this; var storage = this.getStorageConfig($tr); - if (!storage.validate()) { + if (!storage || !storage.validate()) { return false; } diff --git a/apps/files_external/l10n/cs_CZ.js b/apps/files_external/l10n/cs_CZ.js index e9a24ba73f8..5ac3b82d67f 100644 --- a/apps/files_external/l10n/cs_CZ.js +++ b/apps/files_external/l10n/cs_CZ.js @@ -18,6 +18,7 @@ OC.L10N.register( "Unsatisfied authentication mechanism parameters" : "Neuspokojivé parametry ověřovacího mechanismu", "Insufficient data: %s" : "Nedostatečná data: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Úložiště s id \"%i\" uživatelé nemohou upravovat", "Personal" : "Osobní", "System" : "Systém", "Grant access" : "Povolit přístup", @@ -63,6 +64,7 @@ OC.L10N.register( "Login credentials" : "Přihlašovací údaje", "Username and password" : "Uživatelské jméno a heslo", "Session credentials" : "Přihlašovací údaje sezení", + "User provided" : "Poskytnuto uživatelem", "RSA public key" : "RSA veřejný klíč", "Public key" : "Veřejný klíč", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/cs_CZ.json b/apps/files_external/l10n/cs_CZ.json index aa991682b7d..a21b78f02c7 100644 --- a/apps/files_external/l10n/cs_CZ.json +++ b/apps/files_external/l10n/cs_CZ.json @@ -16,6 +16,7 @@ "Unsatisfied authentication mechanism parameters" : "Neuspokojivé parametry ověřovacího mechanismu", "Insufficient data: %s" : "Nedostatečná data: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Úložiště s id \"%i\" uživatelé nemohou upravovat", "Personal" : "Osobní", "System" : "Systém", "Grant access" : "Povolit přístup", @@ -61,6 +62,7 @@ "Login credentials" : "Přihlašovací údaje", "Username and password" : "Uživatelské jméno a heslo", "Session credentials" : "Přihlašovací údaje sezení", + "User provided" : "Poskytnuto uživatelem", "RSA public key" : "RSA veřejný klíč", "Public key" : "Veřejný klíč", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/de_DE.js b/apps/files_external/l10n/de_DE.js index f3cbcd2be6e..ef860918474 100644 --- a/apps/files_external/l10n/de_DE.js +++ b/apps/files_external/l10n/de_DE.js @@ -73,6 +73,7 @@ OC.L10N.register( "Scope" : "Anwendungsbereich", "External Storage" : "Externer Speicher", "Folder name" : "Ordnername", + "Authentication" : "Authentifizierung", "Configuration" : "Konfiguration", "Available for" : "Verfügbar für", "Add storage" : "Speicher hinzufügen", diff --git a/apps/files_external/l10n/de_DE.json b/apps/files_external/l10n/de_DE.json index d366b1f0d9f..75a84334764 100644 --- a/apps/files_external/l10n/de_DE.json +++ b/apps/files_external/l10n/de_DE.json @@ -71,6 +71,7 @@ "Scope" : "Anwendungsbereich", "External Storage" : "Externer Speicher", "Folder name" : "Ordnername", + "Authentication" : "Authentifizierung", "Configuration" : "Konfiguration", "Available for" : "Verfügbar für", "Add storage" : "Speicher hinzufügen", diff --git a/apps/files_external/l10n/fi_FI.js b/apps/files_external/l10n/fi_FI.js index f7ec6fea3b3..23b9227348c 100644 --- a/apps/files_external/l10n/fi_FI.js +++ b/apps/files_external/l10n/fi_FI.js @@ -45,6 +45,7 @@ OC.L10N.register( "Password" : "Salasana", "Rackspace" : "Rackspace", "API key" : "API-avain", + "Login credentials" : "Kirjautumistiedot", "Username and password" : "Käyttäjätunnus ja salasana", "Session credentials" : "Istunnon tunnistetiedot", "RSA public key" : "Julkinen RSA-avain", diff --git a/apps/files_external/l10n/fi_FI.json b/apps/files_external/l10n/fi_FI.json index 368121feae8..2c778205e10 100644 --- a/apps/files_external/l10n/fi_FI.json +++ b/apps/files_external/l10n/fi_FI.json @@ -43,6 +43,7 @@ "Password" : "Salasana", "Rackspace" : "Rackspace", "API key" : "API-avain", + "Login credentials" : "Kirjautumistiedot", "Username and password" : "Käyttäjätunnus ja salasana", "Session credentials" : "Istunnon tunnistetiedot", "RSA public key" : "Julkinen RSA-avain", diff --git a/apps/files_external/l10n/fr.js b/apps/files_external/l10n/fr.js index 63d443a4f18..0c2bb063b29 100644 --- a/apps/files_external/l10n/fr.js +++ b/apps/files_external/l10n/fr.js @@ -40,7 +40,7 @@ OC.L10N.register( "Couldn't get the information from the ownCloud server: {code} {type}" : "Impossible d'obtenir l'information depuis le serveur ownCloud : {code} {type}", "Couldn't get the list of external mount points: {type}" : "Impossible de récupérer la liste des points de montage externes : {type}", "There was an error with message: " : "Il y a eu une erreur avec le message :", - "External mount error" : "Erreur de montage externe", + "External mount error" : "Erreur de point de montage externe", "Couldn't get the list of Windows network drive mount points: empty response from the server" : "Impossible d'obtenir la liste des points de montage des disques réseaux Windows : Réponse vide du serveur", "Some of the configured external mount points are not connected. Please click on the red row(s) for more information" : "Certains points de montage externes configurés ne sont pas connectés. Veuillez cliquer sur la(les) ligne(s) rouge(s) pour plus d'informations", "Access key" : "Clé d'accès", diff --git a/apps/files_external/l10n/fr.json b/apps/files_external/l10n/fr.json index a1366cc3764..6f2fb0615bd 100644 --- a/apps/files_external/l10n/fr.json +++ b/apps/files_external/l10n/fr.json @@ -38,7 +38,7 @@ "Couldn't get the information from the ownCloud server: {code} {type}" : "Impossible d'obtenir l'information depuis le serveur ownCloud : {code} {type}", "Couldn't get the list of external mount points: {type}" : "Impossible de récupérer la liste des points de montage externes : {type}", "There was an error with message: " : "Il y a eu une erreur avec le message :", - "External mount error" : "Erreur de montage externe", + "External mount error" : "Erreur de point de montage externe", "Couldn't get the list of Windows network drive mount points: empty response from the server" : "Impossible d'obtenir la liste des points de montage des disques réseaux Windows : Réponse vide du serveur", "Some of the configured external mount points are not connected. Please click on the red row(s) for more information" : "Certains points de montage externes configurés ne sont pas connectés. Veuillez cliquer sur la(les) ligne(s) rouge(s) pour plus d'informations", "Access key" : "Clé d'accès", diff --git a/apps/files_external/l10n/he.js b/apps/files_external/l10n/he.js index 354d646e77b..83ff5a524d0 100644 --- a/apps/files_external/l10n/he.js +++ b/apps/files_external/l10n/he.js @@ -18,6 +18,7 @@ OC.L10N.register( "Unsatisfied authentication mechanism parameters" : "פרמטרים של מכניזם אימות אינם מספקים", "Insufficient data: %s" : "מידע לא מספק: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "האחסון עם זהות \"%i\" לא ניתן לעריכה", "Personal" : "אישי", "System" : "מערכת", "Grant access" : "הענקת גישה", @@ -60,8 +61,10 @@ OC.L10N.register( "Identity endpoint URL" : "זהות נתיב נקודת קצה", "Rackspace" : "חץ אחורה", "API key" : "מפתח API", + "Login credentials" : "פרטי הכניסה", "Username and password" : "שם משתמש וסיסמא", "Session credentials" : "אישורי סשן", + "User provided" : "סופק על ידי משתמש", "RSA public key" : "מפתח ציבורי RSA", "Public key" : "מפתח ציבורי", "Amazon S3" : "אמזון S3", diff --git a/apps/files_external/l10n/he.json b/apps/files_external/l10n/he.json index 20f0d0a0797..71e07d5f6af 100644 --- a/apps/files_external/l10n/he.json +++ b/apps/files_external/l10n/he.json @@ -16,6 +16,7 @@ "Unsatisfied authentication mechanism parameters" : "פרמטרים של מכניזם אימות אינם מספקים", "Insufficient data: %s" : "מידע לא מספק: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "האחסון עם זהות \"%i\" לא ניתן לעריכה", "Personal" : "אישי", "System" : "מערכת", "Grant access" : "הענקת גישה", @@ -58,8 +59,10 @@ "Identity endpoint URL" : "זהות נתיב נקודת קצה", "Rackspace" : "חץ אחורה", "API key" : "מפתח API", + "Login credentials" : "פרטי הכניסה", "Username and password" : "שם משתמש וסיסמא", "Session credentials" : "אישורי סשן", + "User provided" : "סופק על ידי משתמש", "RSA public key" : "מפתח ציבורי RSA", "Public key" : "מפתח ציבורי", "Amazon S3" : "אמזון S3", diff --git a/apps/files_external/l10n/it.js b/apps/files_external/l10n/it.js index 54192813b2a..c27a92d76f4 100644 --- a/apps/files_external/l10n/it.js +++ b/apps/files_external/l10n/it.js @@ -18,6 +18,7 @@ OC.L10N.register( "Unsatisfied authentication mechanism parameters" : "Parametri del meccanismo di autenticazione non soddisfatti", "Insufficient data: %s" : "Dati insufficienti: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "L'archiviazione con ID \"%i\" non è modificabile dall'utente", "Personal" : "Personale", "System" : "Sistema", "Grant access" : "Concedi l'accesso", @@ -63,6 +64,7 @@ OC.L10N.register( "Login credentials" : "Credenziali di accesso", "Username and password" : "Nome utente e password", "Session credentials" : "Credenziali di sessione", + "User provided" : "Fornita dall'utente", "RSA public key" : "Chiave pubblica RSA", "Public key" : "Chiave pubblica", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/it.json b/apps/files_external/l10n/it.json index 3bc5ee133fc..cf7775f1d0e 100644 --- a/apps/files_external/l10n/it.json +++ b/apps/files_external/l10n/it.json @@ -16,6 +16,7 @@ "Unsatisfied authentication mechanism parameters" : "Parametri del meccanismo di autenticazione non soddisfatti", "Insufficient data: %s" : "Dati insufficienti: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "L'archiviazione con ID \"%i\" non è modificabile dall'utente", "Personal" : "Personale", "System" : "Sistema", "Grant access" : "Concedi l'accesso", @@ -61,6 +62,7 @@ "Login credentials" : "Credenziali di accesso", "Username and password" : "Nome utente e password", "Session credentials" : "Credenziali di sessione", + "User provided" : "Fornita dall'utente", "RSA public key" : "Chiave pubblica RSA", "Public key" : "Chiave pubblica", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/ja.js b/apps/files_external/l10n/ja.js index 1deff5971a9..fafe03c4fa0 100644 --- a/apps/files_external/l10n/ja.js +++ b/apps/files_external/l10n/ja.js @@ -18,6 +18,7 @@ OC.L10N.register( "Unsatisfied authentication mechanism parameters" : "認証のためのパラメータが不十分です", "Insufficient data: %s" : "データが不足しています: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "ストレージID \"%i\" はユーザーが編集できません", "Personal" : "個人", "System" : "システム", "Grant access" : "アクセスを許可", @@ -60,6 +61,7 @@ OC.L10N.register( "Identity endpoint URL" : "認証エンドポイントURL", "Rackspace" : "Rackspace", "API key" : "APIキー", + "Login credentials" : "ログイン資格情報", "Username and password" : "ユーザー名とパスワード", "Session credentials" : "セッション資格情報", "RSA public key" : "RSA公開鍵", diff --git a/apps/files_external/l10n/ja.json b/apps/files_external/l10n/ja.json index 744a63c929b..0d1f1729dae 100644 --- a/apps/files_external/l10n/ja.json +++ b/apps/files_external/l10n/ja.json @@ -16,6 +16,7 @@ "Unsatisfied authentication mechanism parameters" : "認証のためのパラメータが不十分です", "Insufficient data: %s" : "データが不足しています: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "ストレージID \"%i\" はユーザーが編集できません", "Personal" : "個人", "System" : "システム", "Grant access" : "アクセスを許可", @@ -58,6 +59,7 @@ "Identity endpoint URL" : "認証エンドポイントURL", "Rackspace" : "Rackspace", "API key" : "APIキー", + "Login credentials" : "ログイン資格情報", "Username and password" : "ユーザー名とパスワード", "Session credentials" : "セッション資格情報", "RSA public key" : "RSA公開鍵", diff --git a/apps/files_external/l10n/nl.js b/apps/files_external/l10n/nl.js index adc2302d9c6..a6dd5164992 100644 --- a/apps/files_external/l10n/nl.js +++ b/apps/files_external/l10n/nl.js @@ -18,6 +18,7 @@ OC.L10N.register( "Unsatisfied authentication mechanism parameters" : "Onvoldoende authenticatiemechanisme parameters", "Insufficient data: %s" : "Onvoldoende gegevens: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Opslag met id \"%i\" is niet te bewerken door gebruiker", "Personal" : "Persoonlijk", "System" : "Systeem", "Grant access" : "Sta toegang toe", @@ -63,6 +64,7 @@ OC.L10N.register( "Login credentials" : "Inloggegevens", "Username and password" : "Gebruikersnaam en wachtwoord", "Session credentials" : "Sessie inloggegevens", + "User provided" : "Gebruiker gaf op", "RSA public key" : "RSA publieke sleutel", "Public key" : "Publieke sleutel", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/nl.json b/apps/files_external/l10n/nl.json index da7353a4bde..03b8953a62b 100644 --- a/apps/files_external/l10n/nl.json +++ b/apps/files_external/l10n/nl.json @@ -16,6 +16,7 @@ "Unsatisfied authentication mechanism parameters" : "Onvoldoende authenticatiemechanisme parameters", "Insufficient data: %s" : "Onvoldoende gegevens: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Opslag met id \"%i\" is niet te bewerken door gebruiker", "Personal" : "Persoonlijk", "System" : "Systeem", "Grant access" : "Sta toegang toe", @@ -61,6 +62,7 @@ "Login credentials" : "Inloggegevens", "Username and password" : "Gebruikersnaam en wachtwoord", "Session credentials" : "Sessie inloggegevens", + "User provided" : "Gebruiker gaf op", "RSA public key" : "RSA publieke sleutel", "Public key" : "Publieke sleutel", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/pt_BR.js b/apps/files_external/l10n/pt_BR.js index 46b10051238..4a301a306ab 100644 --- a/apps/files_external/l10n/pt_BR.js +++ b/apps/files_external/l10n/pt_BR.js @@ -18,6 +18,7 @@ OC.L10N.register( "Unsatisfied authentication mechanism parameters" : "Parâmetros de mecanismos de autenticação não satisfeitos", "Insufficient data: %s" : "Dados insuficientes: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Armazenamento com ID \"%i\" não é editável pelo usuário", "Personal" : "Pessoal", "System" : "Sistema", "Grant access" : "Permitir acesso", diff --git a/apps/files_external/l10n/pt_BR.json b/apps/files_external/l10n/pt_BR.json index af71fdb1b47..26c20fcb3c1 100644 --- a/apps/files_external/l10n/pt_BR.json +++ b/apps/files_external/l10n/pt_BR.json @@ -16,6 +16,7 @@ "Unsatisfied authentication mechanism parameters" : "Parâmetros de mecanismos de autenticação não satisfeitos", "Insufficient data: %s" : "Dados insuficientes: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Armazenamento com ID \"%i\" não é editável pelo usuário", "Personal" : "Pessoal", "System" : "Sistema", "Grant access" : "Permitir acesso", diff --git a/apps/files_external/l10n/pt_PT.js b/apps/files_external/l10n/pt_PT.js index e80971ccff5..3065f6780af 100644 --- a/apps/files_external/l10n/pt_PT.js +++ b/apps/files_external/l10n/pt_PT.js @@ -18,6 +18,7 @@ OC.L10N.register( "Unsatisfied authentication mechanism parameters" : "Parâmetros do mecanismo de autenticação inválidos", "Insufficient data: %s" : "Dados insuficientes: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Armazenamento com id \"%i\" não é editável pelo utilizador", "Personal" : "Pessoal", "System" : "Sistema", "Grant access" : "Conceder acesso", @@ -63,6 +64,7 @@ OC.L10N.register( "Login credentials" : "Credenciais de login", "Username and password" : "Nome de utilizador e palavra-passe", "Session credentials" : "Credenciais da sessão", + "User provided" : "Utilizador fornecido", "RSA public key" : "Chave pública RSA", "Public key" : "Chave pública", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/pt_PT.json b/apps/files_external/l10n/pt_PT.json index c2a4dd9848d..2525f001dea 100644 --- a/apps/files_external/l10n/pt_PT.json +++ b/apps/files_external/l10n/pt_PT.json @@ -16,6 +16,7 @@ "Unsatisfied authentication mechanism parameters" : "Parâmetros do mecanismo de autenticação inválidos", "Insufficient data: %s" : "Dados insuficientes: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Armazenamento com id \"%i\" não é editável pelo utilizador", "Personal" : "Pessoal", "System" : "Sistema", "Grant access" : "Conceder acesso", @@ -61,6 +62,7 @@ "Login credentials" : "Credenciais de login", "Username and password" : "Nome de utilizador e palavra-passe", "Session credentials" : "Credenciais da sessão", + "User provided" : "Utilizador fornecido", "RSA public key" : "Chave pública RSA", "Public key" : "Chave pública", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/sq.js b/apps/files_external/l10n/sq.js index da6ccf917f5..96438f293bd 100644 --- a/apps/files_external/l10n/sq.js +++ b/apps/files_external/l10n/sq.js @@ -18,6 +18,7 @@ OC.L10N.register( "Unsatisfied authentication mechanism parameters" : "Parametra mekanizmi mirëfilltësimi të papërmbushur", "Insufficient data: %s" : "Të dhëna të pamjaftueshme: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Depozita me id \"%i\" s’është e përpunueshme nga përdoruesi", "Personal" : "Personale", "System" : "Sistem", "Grant access" : "Akordoji hyrje", @@ -62,6 +63,7 @@ OC.L10N.register( "Login credentials" : "Kredenciale hyrjesh", "Username and password" : "Emër përdoruesi dhe fjalëkalim", "Session credentials" : "Kredenciale sesioni", + "User provided" : "Dhënë nga përdoruesi", "RSA public key" : "Kyç publik RSA ", "Public key" : "Kyç publik", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/sq.json b/apps/files_external/l10n/sq.json index 068dfd351b5..e3e21598d7a 100644 --- a/apps/files_external/l10n/sq.json +++ b/apps/files_external/l10n/sq.json @@ -16,6 +16,7 @@ "Unsatisfied authentication mechanism parameters" : "Parametra mekanizmi mirëfilltësimi të papërmbushur", "Insufficient data: %s" : "Të dhëna të pamjaftueshme: %s", "%s" : "%s", + "Storage with id \"%i\" is not user editable" : "Depozita me id \"%i\" s’është e përpunueshme nga përdoruesi", "Personal" : "Personale", "System" : "Sistem", "Grant access" : "Akordoji hyrje", @@ -60,6 +61,7 @@ "Login credentials" : "Kredenciale hyrjesh", "Username and password" : "Emër përdoruesi dhe fjalëkalim", "Session credentials" : "Kredenciale sesioni", + "User provided" : "Dhënë nga përdoruesi", "RSA public key" : "Kyç publik RSA ", "Public key" : "Kyç publik", "Amazon S3" : "Amazon S3", diff --git a/apps/files_external/l10n/th_TH.js b/apps/files_external/l10n/th_TH.js index 5bf00934608..90db47a31d7 100644 --- a/apps/files_external/l10n/th_TH.js +++ b/apps/files_external/l10n/th_TH.js @@ -60,6 +60,7 @@ OC.L10N.register( "Identity endpoint URL" : "ตัวตนของ URL ปลายทาง", "Rackspace" : "Rackspace", "API key" : "รหัส API", + "Login credentials" : "เข้าสู่ระบบด้วยข้อมูลประจำตัว", "Username and password" : "ชื่อผู้ใช้และรหัสผ่าน", "Session credentials" : "ข้อมูลของเซสชั่น", "RSA public key" : "RSA คีย์สาธารณะ", diff --git a/apps/files_external/l10n/th_TH.json b/apps/files_external/l10n/th_TH.json index 935a0380a52..4f327592ab8 100644 --- a/apps/files_external/l10n/th_TH.json +++ b/apps/files_external/l10n/th_TH.json @@ -58,6 +58,7 @@ "Identity endpoint URL" : "ตัวตนของ URL ปลายทาง", "Rackspace" : "Rackspace", "API key" : "รหัส API", + "Login credentials" : "เข้าสู่ระบบด้วยข้อมูลประจำตัว", "Username and password" : "ชื่อผู้ใช้และรหัสผ่าน", "Session credentials" : "ข้อมูลของเซสชั่น", "RSA public key" : "RSA คีย์สาธารณะ", diff --git a/apps/files_external/lib/auth/authmechanism.php b/apps/files_external/lib/auth/authmechanism.php index 72b56e0bc06..36e55de92c5 100644 --- a/apps/files_external/lib/auth/authmechanism.php +++ b/apps/files_external/lib/auth/authmechanism.php @@ -95,6 +95,7 @@ class AuthMechanism implements \JsonSerializable { $data += $this->jsonSerializeIdentifier(); $data['scheme'] = $this->getScheme(); + $data['visibility'] = $this->getVisibility(); return $data; } diff --git a/apps/files_external/lib/auth/iuserprovided.php b/apps/files_external/lib/auth/iuserprovided.php new file mode 100644 index 00000000000..6b7eab4e2a7 --- /dev/null +++ b/apps/files_external/lib/auth/iuserprovided.php @@ -0,0 +1,36 @@ +<?php +/** + * @author Robin Appelman <icewind@owncloud.com> + * + * @copyright Copyright (c) 2015, 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 <http://www.gnu.org/licenses/> + * + */ + +namespace OCA\Files_External\Lib\Auth; + +use OCP\IUser; + +/** + * For auth mechanisms where the user needs to provide credentials + */ +interface IUserProvided { + /** + * @param IUser $user the user for which to save the user provided options + * @param int $mountId the mount id to save the options for + * @param array $options the user provided options + */ + public function saveBackendOptions(IUser $user, $mountId, array $options); +} diff --git a/apps/files_external/lib/auth/password/logincredentials.php b/apps/files_external/lib/auth/password/logincredentials.php index 99cac3f4202..25bd66fb41a 100644 --- a/apps/files_external/lib/auth/password/logincredentials.php +++ b/apps/files_external/lib/auth/password/logincredentials.php @@ -52,7 +52,7 @@ class LoginCredentials extends AuthMechanism { $this ->setIdentifier('password::logincredentials') ->setScheme(self::SCHEME_PASSWORD) - ->setText($l->t('Login credentials')) + ->setText($l->t('Log-in credentials, save in database')) ->addParameters([ ]) ; diff --git a/apps/files_external/lib/auth/password/sessioncredentials.php b/apps/files_external/lib/auth/password/sessioncredentials.php index 3fb8b8526cc..d8e8443418a 100644 --- a/apps/files_external/lib/auth/password/sessioncredentials.php +++ b/apps/files_external/lib/auth/password/sessioncredentials.php @@ -50,7 +50,7 @@ class SessionCredentials extends AuthMechanism { $this ->setIdentifier('password::sessioncredentials') ->setScheme(self::SCHEME_PASSWORD) - ->setText($l->t('Session credentials')) + ->setText($l->t('Log-in credentials, save in session')) ->addParameters([ ]) ; diff --git a/apps/files_external/lib/auth/password/userprovided.php b/apps/files_external/lib/auth/password/userprovided.php new file mode 100644 index 00000000000..2f277163184 --- /dev/null +++ b/apps/files_external/lib/auth/password/userprovided.php @@ -0,0 +1,88 @@ +<?php +/** + * @author Robin Appelman <icewind@owncloud.com> + * + * @copyright Copyright (c) 2015, 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 <http://www.gnu.org/licenses/> + * + */ + +namespace OCA\Files_External\Lib\Auth\Password; + +use OCA\Files_External\Lib\Auth\IUserProvided; +use OCA\Files_External\Lib\DefinitionParameter; +use OCA\Files_External\Service\BackendService; +use OCP\IL10N; +use OCP\IUser; +use OCA\Files_External\Lib\Auth\AuthMechanism; +use OCA\Files_External\Lib\StorageConfig; +use OCP\Security\ICredentialsManager; +use OCP\Files\Storage; +use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException; + +/** + * User provided Username and Password + */ +class UserProvided extends AuthMechanism implements IUserProvided { + + const CREDENTIALS_IDENTIFIER_PREFIX = 'password::userprovided/'; + + /** @var ICredentialsManager */ + protected $credentialsManager; + + public function __construct(IL10N $l, ICredentialsManager $credentialsManager) { + $this->credentialsManager = $credentialsManager; + + $this + ->setIdentifier('password::userprovided') + ->setVisibility(BackendService::VISIBILITY_ADMIN) + ->setScheme(self::SCHEME_PASSWORD) + ->setText($l->t('User entered, store in database')) + ->addParameters([ + (new DefinitionParameter('user', $l->t('Username'))) + ->setFlag(DefinitionParameter::FLAG_USER_PROVIDED), + (new DefinitionParameter('password', $l->t('Password'))) + ->setType(DefinitionParameter::VALUE_PASSWORD) + ->setFlag(DefinitionParameter::FLAG_USER_PROVIDED), + ]); + } + + private function getCredentialsIdentifier($storageId) { + return self::CREDENTIALS_IDENTIFIER_PREFIX . $storageId; + } + + public function saveBackendOptions(IUser $user, $id, array $options) { + $this->credentialsManager->store($user->getUID(), $this->getCredentialsIdentifier($id), [ + 'user' => $options['user'], // explicitly copy the fields we want instead of just passing the entire $options array + 'password' => $options['password'] // this way we prevent users from being able to modify any other field + ]); + } + + public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = null) { + if (!isset($user)) { + throw new InsufficientDataForMeaningfulAnswerException('No credentials saved'); + } + $uid = $user->getUID(); + $credentials = $this->credentialsManager->retrieve($uid, $this->getCredentialsIdentifier($storage->getId())); + + if (!isset($credentials)) { + throw new InsufficientDataForMeaningfulAnswerException('No credentials saved'); + } + + $storage->setBackendOption('user', $credentials['user']); + $storage->setBackendOption('password', $credentials['password']); + } + +} diff --git a/apps/files_external/lib/definitionparameter.php b/apps/files_external/lib/definitionparameter.php index 59a098e6320..dc7985837f5 100644 --- a/apps/files_external/lib/definitionparameter.php +++ b/apps/files_external/lib/definitionparameter.php @@ -35,6 +35,7 @@ class DefinitionParameter implements \JsonSerializable { /** Flag constants */ const FLAG_NONE = 0; const FLAG_OPTIONAL = 1; + const FLAG_USER_PROVIDED = 2; /** @var string name of parameter */ private $name; @@ -121,7 +122,7 @@ class DefinitionParameter implements \JsonSerializable { * @return bool */ public function isFlagSet($flag) { - return (bool) $this->flags & $flag; + return (bool)($this->flags & $flag); } /** @@ -143,15 +144,20 @@ class DefinitionParameter implements \JsonSerializable { break; } - switch ($this->getFlags()) { - case self::FLAG_OPTIONAL: - $prefix = '&' . $prefix; - break; + if ($this->isFlagSet(self::FLAG_OPTIONAL)) { + $prefix = '&' . $prefix; + } + if ($this->isFlagSet(self::FLAG_USER_PROVIDED)) { + $prefix = '@' . $prefix; } return $prefix . $this->getText(); } + public function isOptional() { + return $this->isFlagSet(self::FLAG_OPTIONAL) || $this->isFlagSet(self::FLAG_USER_PROVIDED); + } + /** * Validate a parameter value against this * Convert type as necessary @@ -160,28 +166,26 @@ class DefinitionParameter implements \JsonSerializable { * @return bool success */ public function validateValue(&$value) { - $optional = $this->getFlags() & self::FLAG_OPTIONAL; - switch ($this->getType()) { - case self::VALUE_BOOLEAN: - if (!is_bool($value)) { - switch ($value) { - case 'true': - $value = true; - break; - case 'false': - $value = false; - break; - default: + case self::VALUE_BOOLEAN: + if (!is_bool($value)) { + switch ($value) { + case 'true': + $value = true; + break; + case 'false': + $value = false; + break; + default: + return false; + } + } + break; + default: + if (!$value && !$this->isOptional()) { return false; } - } - break; - default: - if (!$value && !$optional) { - return false; - } - break; + break; } return true; } diff --git a/apps/files_external/lib/failedcache.php b/apps/files_external/lib/failedcache.php new file mode 100644 index 00000000000..9e24c12f4b5 --- /dev/null +++ b/apps/files_external/lib/failedcache.php @@ -0,0 +1,126 @@ +<?php +/** + * @author Robin Appelman <icewind@owncloud.com> + * + * @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 <http://www.gnu.org/licenses/> + * + */ + +namespace OCA\Files_External\Lib; + +use OC\Files\Cache\CacheEntry; +use OCP\Files\Cache\ICache; + +/** + * Storage placeholder to represent a missing precondition, storage unavailable + */ +class FailedCache implements ICache { + + public function getNumericStorageId() { + return -1; + } + + public function get($file) { + if ($file === '') { + return new CacheEntry([ + 'fileid' => -1, + 'size' => 0, + 'mimetype' => 'httpd/unix-directory', + 'mimepart' => 'httpd', + 'permissions' => 0, + 'mtime' => time() + ]); + } else { + return false; + } + } + + public function getFolderContents($folder) { + return []; + } + + public function getFolderContentsById($fileId) { + return []; + } + + public function put($file, array $data) { + return; + } + + public function update($id, array $data) { + return; + } + + public function getId($file) { + return -1; + } + + public function getParentId($file) { + return -1; + } + + public function inCache($file) { + return false; + } + + public function remove($file) { + return; + } + + public function move($source, $target) { + return; + } + + public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) { + return; + } + + public function clear() { + return; + } + + public function getStatus($file) { + return ICache::NOT_FOUND; + } + + public function search($pattern) { + return []; + } + + public function searchByMime($mimetype) { + return []; + } + + public function searchByTag($tag, $userId) { + return []; + } + + public function getAll() { + return []; + } + + public function getIncomplete() { + return []; + } + + public function getPathById($id) { + return null; + } + + public function normalize($path) { + return $path; + } +} diff --git a/apps/files_external/lib/failedstorage.php b/apps/files_external/lib/failedstorage.php index 95fe179f570..7bcbfc31902 100644 --- a/apps/files_external/lib/failedstorage.php +++ b/apps/files_external/lib/failedstorage.php @@ -174,7 +174,7 @@ class FailedStorage extends Common { } public function verifyPath($path, $fileName) { - throw new StorageNotAvailableException($this->e->getMessage(), $this->e->getCode(), $this->e); + return true; } public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) { @@ -205,4 +205,7 @@ class FailedStorage extends Common { throw new StorageNotAvailableException($this->e->getMessage(), $this->e->getCode(), $this->e); } + public function getCache($path = '', $storage = null) { + return new FailedCache(); + } } diff --git a/apps/files_external/lib/frontenddefinitiontrait.php b/apps/files_external/lib/frontenddefinitiontrait.php index eedd433f2d7..fc47a9515f3 100644 --- a/apps/files_external/lib/frontenddefinitiontrait.php +++ b/apps/files_external/lib/frontenddefinitiontrait.php @@ -136,10 +136,12 @@ trait FrontendDefinitionTrait { public function validateStorageDefinition(StorageConfig $storage) { foreach ($this->getParameters() as $name => $parameter) { $value = $storage->getBackendOption($name); - if (!$parameter->validateValue($value)) { - return false; + if (!is_null($value) || !$parameter->isOptional()) { + if (!$parameter->validateValue($value)) { + return false; + } + $storage->setBackendOption($name, $value); } - $storage->setBackendOption($name, $value); } return true; } diff --git a/apps/files_external/lib/sftp.php b/apps/files_external/lib/sftp.php index ec808cd76dc..09d743ff93d 100644 --- a/apps/files_external/lib/sftp.php +++ b/apps/files_external/lib/sftp.php @@ -85,6 +85,9 @@ class SFTP extends \OC\Files\Storage\Common { $this->host = $parsedHost[0]; $this->port = $parsedHost[1]; + if (!isset($params['user'])) { + throw new \UnexpectedValueException('no authentication parameters specified'); + } $this->user = $params['user']; if (isset($params['public_key_auth'])) { diff --git a/apps/files_external/lib/storageconfig.php b/apps/files_external/lib/storageconfig.php index 33646e603c3..7f716893842 100644 --- a/apps/files_external/lib/storageconfig.php +++ b/apps/files_external/lib/storageconfig.php @@ -406,6 +406,7 @@ class StorageConfig implements \JsonSerializable { if (!is_null($this->statusMessage)) { $result['statusMessage'] = $this->statusMessage; } + $result['type'] = ($this->getType() === self::MOUNT_TYPE_PERSONAl) ? 'personal': 'system'; return $result; } } diff --git a/apps/files_external/tests/controller/globalstoragescontrollertest.php b/apps/files_external/tests/controller/globalstoragescontrollertest.php index a3c911b511c..9256569f22a 100644 --- a/apps/files_external/tests/controller/globalstoragescontrollertest.php +++ b/apps/files_external/tests/controller/globalstoragescontrollertest.php @@ -41,7 +41,8 @@ class GlobalStoragesControllerTest extends StoragesControllerTest { 'files_external', $this->getMock('\OCP\IRequest'), $this->getMock('\OCP\IL10N'), - $this->service + $this->service, + $this->getMock('\OCP\ILogger') ); } } diff --git a/apps/files_external/tests/controller/userstoragescontrollertest.php b/apps/files_external/tests/controller/userstoragescontrollertest.php index 671e019fea0..342f6b85385 100644 --- a/apps/files_external/tests/controller/userstoragescontrollertest.php +++ b/apps/files_external/tests/controller/userstoragescontrollertest.php @@ -49,7 +49,8 @@ class UserStoragesControllerTest extends StoragesControllerTest { $this->getMock('\OCP\IRequest'), $this->getMock('\OCP\IL10N'), $this->service, - $this->getMock('\OCP\IUserSession') + $this->getMock('\OCP\IUserSession'), + $this->getMock('\OCP\ILogger') ); } diff --git a/apps/files_external/tests/frontenddefinitiontraittest.php b/apps/files_external/tests/frontenddefinitiontraittest.php index 209b1abc7e0..27f49556330 100644 --- a/apps/files_external/tests/frontenddefinitiontraittest.php +++ b/apps/files_external/tests/frontenddefinitiontraittest.php @@ -61,6 +61,8 @@ class FrontendDefinitionTraitTest extends \Test\TestCase { ->getMock(); $param->method('getName') ->willReturn($name); + $param->method('isOptional') + ->willReturn(false); $param->expects($this->once()) ->method('validateValue') ->willReturn($valid); diff --git a/apps/files_external/tests/js/settingsSpec.js b/apps/files_external/tests/js/settingsSpec.js index b6372649fb8..b2b5e1f57ec 100644 --- a/apps/files_external/tests/js/settingsSpec.js +++ b/apps/files_external/tests/js/settingsSpec.js @@ -37,6 +37,7 @@ describe('OCA.External.Settings tests', function() { '<option disable selected>Add storage</option>' + '<option value="\\OC\\TestBackend">Test Backend</option>' + '<option value="\\OC\\AnotherTestBackend">Another Test Backend</option>' + + '<option value="\\OC\\InputsTestBackend">Inputs test backend</option>' + '</select>' + '</td>' + '<td class="authentication"></td>' + @@ -76,6 +77,22 @@ describe('OCA.External.Settings tests', function() { 'builtin': true, }, 'priority': 12 + }, + '\\OC\\InputsTestBackend': { + 'identifier': '\\OC\\InputsTestBackend', + 'name': 'Inputs test backend', + 'configuration': { + 'field_text': 'Text field', + 'field_password': '*Password field', + 'field_bool': '!Boolean field', + 'field_hidden': '#Hidden field', + 'field_text_optional': '&Text field optional', + 'field_password_optional': '&*Password field optional' + }, + 'authSchemes': { + 'builtin': true, + }, + 'priority': 13 } } ); @@ -87,6 +104,7 @@ describe('OCA.External.Settings tests', function() { 'configuration': { }, 'scheme': 'builtin', + 'visibility': 3 }, }); @@ -190,13 +208,70 @@ describe('OCA.External.Settings tests', function() { expect(fakeServer.requests.length).toEqual(1); }); // TODO: tests with "applicableUsers" and "applicableGroups" - // TODO: test with non-optional config parameters // TODO: test with missing mount point value // TODO: test with personal mounts (no applicable fields) // TODO: test save triggers: paste, keyup, checkbox // TODO: test "custom" field with addScript // TODO: status indicator }); + describe('validate storage configuration', function() { + var $tr; + + beforeEach(function() { + $tr = view.$el.find('tr:first'); + selectBackend('\\OC\\InputsTestBackend'); + }); + + it('lists missing fields in storage errors', function() { + var storage = view.getStorageConfig($tr); + + expect(storage.errors).toEqual({ + backendOptions: ['field_text', 'field_password'] + }); + }); + + it('highlights missing non-optional fields', function() { + _.each([ + 'field_text', + 'field_password' + ], function(param) { + expect($tr.find('input[data-parameter='+param+']').hasClass('warning-input')).toBe(true); + }); + _.each([ + 'field_bool', + 'field_hidden', + 'field_text_optional', + 'field_password_optional' + ], function(param) { + expect($tr.find('input[data-parameter='+param+']').hasClass('warning-input')).toBe(false); + }); + }); + + it('validates correct storage', function() { + $tr.find('[name=mountPoint]').val('mountpoint'); + + $tr.find('input[data-parameter=field_text]').val('foo'); + $tr.find('input[data-parameter=field_password]').val('bar'); + $tr.find('input[data-parameter=field_text_optional]').val('foobar'); + // don't set field_password_optional + $tr.find('input[data-parameter=field_hidden]').val('baz'); + + var storage = view.getStorageConfig($tr); + + expect(storage.validate()).toBe(true); + }); + + it('checks missing mount point', function() { + $tr.find('[name=mountPoint]').val(''); + + $tr.find('input[data-parameter=field_text]').val('foo'); + $tr.find('input[data-parameter=field_password]').val('bar'); + + var storage = view.getStorageConfig($tr); + + expect(storage.validate()).toBe(false); + }); + }); describe('update storage', function() { // TODO }); |