summaryrefslogtreecommitdiffstats
path: root/apps
diff options
context:
space:
mode:
authorMorris Jobke <hey@morrisjobke.de>2016-06-30 16:47:29 +0200
committerGitHub <noreply@github.com>2016-06-30 16:47:29 +0200
commit07c43751d145ccd95a9313628d3194f2ecb26f23 (patch)
treedfcc167c31b40f5c89e4faf2a821c6400a3cfef1 /apps
parent212ff8ef6fcffb6b580f8c804bcaeb507043ad78 (diff)
parenta80af7079da80f033c465b446ca62d2393408c08 (diff)
downloadnextcloud-server-07c43751d145ccd95a9313628d3194f2ecb26f23.tar.gz
nextcloud-server-07c43751d145ccd95a9313628d3194f2ecb26f23.zip
Merge pull request #265 from nextcloud/stable9-add-wnd
[stable9] Backport WND
Diffstat (limited to 'apps')
-rw-r--r--apps/files_external/appinfo/application.php3
-rw-r--r--apps/files_external/appinfo/routes.php7
-rw-r--r--apps/files_external/controller/ajaxcontroller.php60
-rw-r--r--apps/files_external/js/settings.js27
-rw-r--r--apps/files_external/lib/auth/password/globalauth.php87
-rw-r--r--apps/files_external/lib/auth/password/logincredentials.php92
-rw-r--r--apps/files_external/lib/auth/password/userprovided.php88
-rw-r--r--apps/files_external/personal.php4
-rw-r--r--apps/files_external/settings.php3
-rw-r--r--apps/files_external/templates/settings.php19
-rw-r--r--apps/files_external/tests/auth/password/globalauth.php117
-rw-r--r--apps/files_external/tests/controller/ajaxcontrollertest.php177
12 files changed, 679 insertions, 5 deletions
diff --git a/apps/files_external/appinfo/application.php b/apps/files_external/appinfo/application.php
index cdc58aed7e8..90da98bcf5d 100644
--- a/apps/files_external/appinfo/application.php
+++ b/apps/files_external/appinfo/application.php
@@ -107,6 +107,9 @@ class Application extends App {
// AuthMechanism::SCHEME_PASSWORD mechanisms
$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'),
+ $container->query('OCA\Files_External\Lib\Auth\Password\GlobalAuth'),
// AuthMechanism::SCHEME_OAUTH1 mechanisms
$container->query('OCA\Files_External\Lib\Auth\OAuth1\OAuth1'),
diff --git a/apps/files_external/appinfo/routes.php b/apps/files_external/appinfo/routes.php
index 2d2e6ddf607..b6aa9224392 100644
--- a/apps/files_external/appinfo/routes.php
+++ b/apps/files_external/appinfo/routes.php
@@ -45,7 +45,12 @@ namespace OCA\Files_External\AppInfo;
'url' => '/ajax/public_key.php',
'verb' => 'POST',
'requirements' => array()
- )
+ ),
+ [
+ 'name' => 'Ajax#saveGlobalCredentials',
+ 'url' => '/globalcredentials',
+ 'verb' => 'POST',
+ ],
)
)
);
diff --git a/apps/files_external/controller/ajaxcontroller.php b/apps/files_external/controller/ajaxcontroller.php
index c3df3fa8522..b16c49f8897 100644
--- a/apps/files_external/controller/ajaxcontroller.php
+++ b/apps/files_external/controller/ajaxcontroller.php
@@ -24,20 +24,50 @@
namespace OCA\Files_External\Controller;
+use OCA\Files_External\Lib\Auth\Password\GlobalAuth;
use OCP\AppFramework\Controller;
+use OCP\AppFramework\Http;
+use OCP\AppFramework\Http\Response;
+use OCP\IGroupManager;
use OCP\IRequest;
use OCP\AppFramework\Http\JSONResponse;
use OCA\Files_External\Lib\Auth\PublicKey\RSA;
+use OCP\IUserSession;
class AjaxController extends Controller {
/** @var RSA */
private $rsaMechanism;
+ /** @var GlobalAuth */
+ private $globalAuth;
+ /** @var IUserSession */
+ private $userSession;
+ /** @var IGroupManager */
+ private $groupManager;
- public function __construct($appName, IRequest $request, RSA $rsaMechanism) {
+ /**
+ * @param string $appName
+ * @param IRequest $request
+ * @param RSA $rsaMechanism
+ * @param GlobalAuth $globalAuth
+ * @param IUserSession $userSession
+ * @param IGroupManager $groupManager
+ */
+ public function __construct($appName,
+ IRequest $request,
+ RSA $rsaMechanism,
+ GlobalAuth $globalAuth,
+ IUserSession $userSession,
+ IGroupManager $groupManager) {
parent::__construct($appName, $request);
$this->rsaMechanism = $rsaMechanism;
+ $this->globalAuth = $globalAuth;
+ $this->userSession = $userSession;
+ $this->groupManager = $groupManager;
}
+ /**
+ * @return array
+ */
private function generateSshKeys() {
$key = $this->rsaMechanism->createKey();
// Replace the placeholder label with a more meaningful one
@@ -58,7 +88,31 @@ class AjaxController extends Controller {
'private_key' => $key['privatekey'],
'public_key' => $key['publickey']
),
- 'status' => 'success'
- ));
+ 'status' => 'success'
+ ));
+ }
+
+ /**
+ * @NoAdminRequired
+ *
+ * @param string $uid
+ * @param string $user
+ * @param string $password
+ * @return bool
+ */
+ public function saveGlobalCredentials($uid, $user, $password) {
+ $currentUser = $this->userSession->getUser();
+
+ // Non-admins can only edit their own credentials
+ $allowedToEdit = (
+ $this->groupManager->isAdmin($currentUser->getUID()) || $currentUser->getUID() === $uid
+ ) ? true : false;
+
+ if ($allowedToEdit) {
+ $this->globalAuth->saveAuth($uid, $user, $password);
+ return true;
+ } else {
+ return false;
+ }
}
}
diff --git a/apps/files_external/js/settings.js b/apps/files_external/js/settings.js
index 6262245688b..b27388e4418 100644
--- a/apps/files_external/js/settings.js
+++ b/apps/files_external/js/settings.js
@@ -1345,6 +1345,33 @@ $(document).ready(function() {
}
});
+ $('#global_credentials').on('submit', function() {
+ var $form = $(this);
+ var uid = $form.find('[name=uid]').val();
+ var user = $form.find('[name=username]').val();
+ var password = $form.find('[name=password]').val();
+ var $submit = $form.find('[type=submit]');
+ $submit.val(t('files_external', 'Saving...'));
+ $.ajax({
+ type: 'POST',
+ contentType: 'application/json',
+ data: JSON.stringify({
+ uid: uid,
+ user: user,
+ password: password
+ }),
+ url: OC.generateUrl('apps/files_external/globalcredentials'),
+ dataType: 'json',
+ success: function() {
+ $submit.val(t('files_external', 'Saved'));
+ setTimeout(function(){
+ $submit.val(t('files_external', 'Save'));
+ }, 2500);
+ }
+ });
+ return false;
+ });
+
// global instance
OCA.External.Settings.mountConfig = mountConfigListView;
diff --git a/apps/files_external/lib/auth/password/globalauth.php b/apps/files_external/lib/auth/password/globalauth.php
new file mode 100644
index 00000000000..c261a385f9a
--- /dev/null
+++ b/apps/files_external/lib/auth/password/globalauth.php
@@ -0,0 +1,87 @@
+<?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\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;
+
+/**
+ * Global Username and Password
+ */
+class GlobalAuth extends AuthMechanism {
+
+ const CREDENTIALS_IDENTIFIER = 'password::global';
+
+ /** @var ICredentialsManager */
+ protected $credentialsManager;
+
+ public function __construct(IL10N $l, ICredentialsManager $credentialsManager) {
+ $this->credentialsManager = $credentialsManager;
+
+ $this
+ ->setIdentifier('password::global')
+ ->setVisibility(BackendService::VISIBILITY_DEFAULT)
+ ->setScheme(self::SCHEME_PASSWORD)
+ ->setText($l->t('Global Credentials'));
+ }
+
+ public function getAuth($uid) {
+ $auth = $this->credentialsManager->retrieve($uid, self::CREDENTIALS_IDENTIFIER);
+ if (!is_array($auth)) {
+ return [
+ 'user' => '',
+ 'password' => ''
+ ];
+ } else {
+ return $auth;
+ }
+ }
+
+ public function saveAuth($uid, $user, $password) {
+ $this->credentialsManager->store($uid, self::CREDENTIALS_IDENTIFIER, [
+ 'user' => $user,
+ 'password' => $password
+ ]);
+ }
+
+ public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = null) {
+ if ($storage->getType() === StorageConfig::MOUNT_TYPE_ADMIN) {
+ $uid = '';
+ } elseif (is_null($user)) {
+ throw new InsufficientDataForMeaningfulAnswerException('No credentials saved');
+ } else {
+ $uid = $user->getUID();
+ }
+ $credentials = $this->credentialsManager->retrieve($uid, self::CREDENTIALS_IDENTIFIER);
+ if (is_array($credentials)) {
+ $storage->setBackendOption('user', $credentials['user']);
+ $storage->setBackendOption('password', $credentials['password']);
+ }
+ }
+
+}
diff --git a/apps/files_external/lib/auth/password/logincredentials.php b/apps/files_external/lib/auth/password/logincredentials.php
new file mode 100644
index 00000000000..25bd66fb41a
--- /dev/null
+++ b/apps/files_external/lib/auth/password/logincredentials.php
@@ -0,0 +1,92 @@
+<?php
+/**
+ * @author Robin McCorkell <rmccorkell@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 \OCP\IL10N;
+use \OCP\IUser;
+use \OCA\Files_External\Lib\DefinitionParameter;
+use \OCA\Files_External\Lib\Auth\AuthMechanism;
+use \OCA\Files_External\Lib\StorageConfig;
+use \OCP\ISession;
+use \OCP\Security\ICredentialsManager;
+use \OCP\Files\Storage;
+use \OCA\Files_External\Lib\SessionStorageWrapper;
+use \OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException;
+
+/**
+ * Username and password from login credentials, saved in DB
+ */
+class LoginCredentials extends AuthMechanism {
+
+ const CREDENTIALS_IDENTIFIER = 'password::logincredentials/credentials';
+
+ /** @var ISession */
+ protected $session;
+
+ /** @var ICredentialsManager */
+ protected $credentialsManager;
+
+ public function __construct(IL10N $l, ISession $session, ICredentialsManager $credentialsManager) {
+ $this->session = $session;
+ $this->credentialsManager = $credentialsManager;
+
+ $this
+ ->setIdentifier('password::logincredentials')
+ ->setScheme(self::SCHEME_PASSWORD)
+ ->setText($l->t('Log-in credentials, save in database'))
+ ->addParameters([
+ ])
+ ;
+
+ \OCP\Util::connectHook('OC_User', 'post_login', $this, 'authenticate');
+ }
+
+ /**
+ * Hook listener on post login
+ *
+ * @param array $params
+ */
+ public function authenticate(array $params) {
+ $userId = $params['uid'];
+ $credentials = [
+ 'user' => $this->session->get('loginname'),
+ 'password' => $params['password']
+ ];
+ $this->credentialsManager->store($userId, self::CREDENTIALS_IDENTIFIER, $credentials);
+ }
+
+ public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = null) {
+ if (!isset($user)) {
+ throw new InsufficientDataForMeaningfulAnswerException('No login credentials saved');
+ }
+ $uid = $user->getUID();
+ $credentials = $this->credentialsManager->retrieve($uid, self::CREDENTIALS_IDENTIFIER);
+
+ if (!isset($credentials)) {
+ throw new InsufficientDataForMeaningfulAnswerException('No login credentials saved');
+ }
+
+ $storage->setBackendOption('user', $credentials['user']);
+ $storage->setBackendOption('password', $credentials['password']);
+ }
+
+}
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/personal.php b/apps/files_external/personal.php
index 5c568f45b7d..df715c67420 100644
--- a/apps/files_external/personal.php
+++ b/apps/files_external/personal.php
@@ -30,6 +30,7 @@ use \OCA\Files_External\Service\BackendService;
$appContainer = \OC_Mount_Config::$app->getContainer();
$backendService = $appContainer->query('OCA\Files_External\Service\BackendService');
$userStoragesService = $appContainer->query('OCA\Files_external\Service\UserStoragesService');
+$globalAuth = $appContainer->query('OCA\Files_External\Lib\Auth\Password\GlobalAuth');
$tmpl = new OCP\Template('files_external', 'settings');
$tmpl->assign('encryptionEnabled', \OC::$server->getEncryptionManager()->isEnabled());
@@ -38,5 +39,8 @@ $tmpl->assign('storages', $userStoragesService->getStorages());
$tmpl->assign('dependencies', OC_Mount_Config::dependencyMessage($backendService->getBackends()));
$tmpl->assign('backends', $backendService->getAvailableBackends());
$tmpl->assign('authMechanisms', $backendService->getAuthMechanisms());
+$uid = \OC::$server->getUserSession()->getUser()->getUID();
+$tmpl->assign('globalCredentials', $globalAuth->getAuth($uid));
+$tmpl->assign('globalCredentialsUid', $uid);
$tmpl->assign('allowUserMounting', $backendService->isUserMountingAllowed());
return $tmpl->fetchPage();
diff --git a/apps/files_external/settings.php b/apps/files_external/settings.php
index 0d83d26ff97..997e56b6184 100644
--- a/apps/files_external/settings.php
+++ b/apps/files_external/settings.php
@@ -32,6 +32,7 @@ use \OCA\Files_External\Service\BackendService;
$appContainer = \OC_Mount_Config::$app->getContainer();
$backendService = $appContainer->query('OCA\Files_External\Service\BackendService');
$globalStoragesService = $appContainer->query('OCA\Files_external\Service\GlobalStoragesService');
+$globalAuth = $appContainer->query('OCA\Files_External\Lib\Auth\Password\GlobalAuth');
\OC_Util::addVendorScript('select2/select2');
\OC_Util::addVendorStyle('select2/select2');
@@ -44,4 +45,6 @@ $tmpl->assign('backends', $backendService->getAvailableBackends());
$tmpl->assign('authMechanisms', $backendService->getAuthMechanisms());
$tmpl->assign('dependencies', OC_Mount_Config::dependencyMessage($backendService->getBackends()));
$tmpl->assign('allowUserMounting', $backendService->isUserMountingAllowed());
+$tmpl->assign('globalCredentials', $globalAuth->getAuth(''));
+$tmpl->assign('globalCredentialsUid', '');
return $tmpl->fetchPage();
diff --git a/apps/files_external/templates/settings.php b/apps/files_external/templates/settings.php
index 697a145131c..c08b90cd1b4 100644
--- a/apps/files_external/templates/settings.php
+++ b/apps/files_external/templates/settings.php
@@ -68,8 +68,25 @@
}
}
?>
-<form id="files_external" class="section" data-encryption-enabled="<?php echo $_['encryptionEnabled']?'true': 'false'; ?>">
+
+<form autocomplete="false" class="section" action="#"
+ id="global_credentials">
<h2><?php p($l->t('External Storage')); ?></h2>
+ <p><?php p($l->t('Global Credentials')); ?></p>
+ <input type="text" name="username"
+ autocomplete="false"
+ value="<?php p($_['globalCredentials']['user']); ?>"
+ placeholder="<?php p($l->t('Username')) ?>"/>
+ <input type="password" name="password"
+ autocomplete="false"
+ value="<?php p($_['globalCredentials']['password']); ?>"
+ placeholder="<?php p($l->t('Password')) ?>"/>
+ <input type="hidden" name="uid"
+ value="<?php p($_['globalCredentialsUid']); ?>"/>
+ <input type="submit" value="<?php p($l->t('Save')) ?>"/>
+</form>
+
+<form id="files_external" class="section" data-encryption-enabled="<?php echo $_['encryptionEnabled']?'true': 'false'; ?>">
<?php if (isset($_['dependencies']) and ($_['dependencies']<>'')) print_unescaped(''.$_['dependencies'].''); ?>
<table id="externalStorage" class="grid" data-admin='<?php print_unescaped(json_encode($_['visibilityType'] === BackendService::VISIBILITY_ADMIN)); ?>'>
<thead>
diff --git a/apps/files_external/tests/auth/password/globalauth.php b/apps/files_external/tests/auth/password/globalauth.php
new file mode 100644
index 00000000000..912bfd1574d
--- /dev/null
+++ b/apps/files_external/tests/auth/password/globalauth.php
@@ -0,0 +1,117 @@
+<?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\Tests\Auth\Password;
+
+use OCA\Files_External\Lib\Auth\Password\GlobalAuth;
+use OCA\Files_external\Lib\StorageConfig;
+use Test\TestCase;
+
+class GlobalAuthTest extends TestCase {
+ /**
+ * @var \OCP\IL10N|\PHPUnit_Framework_MockObject_MockObject
+ */
+ private $l10n;
+
+ /**
+ * @var \OCP\Security\ICredentialsManager|\PHPUnit_Framework_MockObject_MockObject
+ */
+ private $credentialsManager;
+
+ /**
+ * @var GlobalAuth
+ */
+ private $instance;
+
+ protected function setUp() {
+ parent::setUp();
+ $this->l10n = $this->getMock('\OCP\IL10N');
+ $this->credentialsManager = $this->getMock('\OCP\Security\ICredentialsManager');
+ $this->instance = new GlobalAuth($this->l10n, $this->credentialsManager);
+ }
+
+ private function getStorageConfig($type, $config = []) {
+ /** @var \OCA\Files_External\Lib\StorageConfig|\PHPUnit_Framework_MockObject_MockObject $storageConfig */
+ $storageConfig = $this->getMock('\OCA\Files_External\Lib\StorageConfig');
+ $storageConfig->expects($this->any())
+ ->method('getType')
+ ->will($this->returnValue($type));
+ $storageConfig->expects($this->any())
+ ->method('getBackendOptions')
+ ->will($this->returnCallback(function () use (&$config) {
+ return $config;
+ }));
+ $storageConfig->expects($this->any())
+ ->method('getBackendOption')
+ ->will($this->returnCallback(function ($key) use (&$config) {
+ return $config[$key];
+ }));
+ $storageConfig->expects($this->any())
+ ->method('setBackendOption')
+ ->will($this->returnCallback(function ($key, $value) use (&$config) {
+ $config[$key] = $value;
+ }));
+
+ return $storageConfig;
+ }
+
+ public function testNoCredentials() {
+ $this->credentialsManager->expects($this->once())
+ ->method('retrieve')
+ ->will($this->returnValue(null));
+
+ $storage = $this->getStorageConfig(StorageConfig::MOUNT_TYPE_ADMIN);
+
+ $this->instance->manipulateStorageConfig($storage);
+ $this->assertEquals([], $storage->getBackendOptions());
+ }
+
+ public function testSavedCredentials() {
+ $this->credentialsManager->expects($this->once())
+ ->method('retrieve')
+ ->will($this->returnValue([
+ 'user' => 'a',
+ 'password' => 'b'
+ ]));
+
+ $storage = $this->getStorageConfig(StorageConfig::MOUNT_TYPE_ADMIN);
+
+ $this->instance->manipulateStorageConfig($storage);
+ $this->assertEquals([
+ 'user' => 'a',
+ 'password' => 'b'
+ ], $storage->getBackendOptions());
+ }
+
+ /**
+ * @expectedException \OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException
+ */
+ public function testNoCredentialsPersonal() {
+ $this->credentialsManager->expects($this->never())
+ ->method('retrieve');
+
+ $storage = $this->getStorageConfig(StorageConfig::MOUNT_TYPE_PERSONAl);
+
+ $this->instance->manipulateStorageConfig($storage);
+ $this->assertEquals([], $storage->getBackendOptions());
+ }
+
+}
diff --git a/apps/files_external/tests/controller/ajaxcontrollertest.php b/apps/files_external/tests/controller/ajaxcontrollertest.php
new file mode 100644
index 00000000000..c51172f8995
--- /dev/null
+++ b/apps/files_external/tests/controller/ajaxcontrollertest.php
@@ -0,0 +1,177 @@
+<?php
+/**
+ * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch>
+ *
+ * @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/>.
+ *
+ */
+namespace OCA\Files_External\Tests\Controller;
+
+use OCA\Files_External\Controller\AjaxController;
+use OCA\Files_External\Lib\Auth\Password\GlobalAuth;
+use OCA\Files_External\Lib\Auth\PublicKey\RSA;
+use OCP\AppFramework\Http\JSONResponse;
+use OCP\IGroupManager;
+use OCP\IRequest;
+use OCP\IUserSession;
+use Test\TestCase;
+
+class AjaxControllerTest extends TestCase {
+ /** @var IRequest */
+ private $request;
+ /** @var RSA */
+ private $rsa;
+ /** @var GlobalAuth */
+ private $globalAuth;
+ /** @var IUserSession */
+ private $userSession;
+ /** @var IGroupManager */
+ private $groupManager;
+ /** @var AjaxController */
+ private $ajaxController;
+
+ public function setUp() {
+ $this->request = $this->getMock('\\OCP\\IRequest');
+ $this->rsa = $this->getMockBuilder('\\OCA\\Files_External\\Lib\\Auth\\PublicKey\\RSA')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->globalAuth = $this->getMockBuilder('\\OCA\\Files_External\\Lib\\Auth\\Password\GlobalAuth')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->userSession = $this->getMock('\\OCP\\IUserSession');
+ $this->groupManager = $this->getMock('\\OCP\\IGroupManager');
+
+ $this->ajaxController = new AjaxController(
+ 'files_external',
+ $this->request,
+ $this->rsa,
+ $this->globalAuth,
+ $this->userSession,
+ $this->groupManager
+ );
+
+ parent::setUp();
+ }
+
+ public function testGetSshKeys() {
+ $this->rsa
+ ->expects($this->once())
+ ->method('createKey')
+ ->willReturn([
+ 'privatekey' => 'MyPrivateKey',
+ 'publickey' => 'MyPublicKey',
+ ]);
+
+ $expected = new JSONResponse(
+ [
+ 'data' => [
+ 'private_key' => 'MyPrivateKey',
+ 'public_key' => 'MyPublicKey',
+ ],
+ 'status' => 'success',
+ ]
+ );
+ $this->assertEquals($expected, $this->ajaxController->getSshKeys());
+ }
+
+ public function testSaveGlobalCredentialsAsAdminForAnotherUser() {
+ $user = $this->getMock('\\OCP\\IUser');
+ $user
+ ->expects($this->once())
+ ->method('getUID')
+ ->willReturn('MyAdminUid');
+ $this->userSession
+ ->expects($this->once())
+ ->method('getUser')
+ ->willReturn($user);
+ $this->groupManager
+ ->expects($this->once())
+ ->method('isAdmin')
+ ->with('MyAdminUid')
+ ->willReturn(true);
+ $this->globalAuth
+ ->expects($this->once())
+ ->method('saveAuth')
+ ->with('UidOfTestUser', 'test', 'password');
+
+ $this->assertSame(true, $this->ajaxController->saveGlobalCredentials('UidOfTestUser', 'test', 'password'));
+ }
+
+ public function testSaveGlobalCredentialsAsAdminForSelf() {
+ $user = $this->getMock('\\OCP\\IUser');
+ $user
+ ->expects($this->once())
+ ->method('getUID')
+ ->willReturn('MyAdminUid');
+ $this->userSession
+ ->expects($this->once())
+ ->method('getUser')
+ ->willReturn($user);
+ $this->groupManager
+ ->expects($this->once())
+ ->method('isAdmin')
+ ->with('MyAdminUid')
+ ->willReturn(true);
+ $this->globalAuth
+ ->expects($this->once())
+ ->method('saveAuth')
+ ->with('MyAdminUid', 'test', 'password');
+
+ $this->assertSame(true, $this->ajaxController->saveGlobalCredentials('MyAdminUid', 'test', 'password'));
+ }
+
+ public function testSaveGlobalCredentialsAsNormalUserForSelf() {
+ $user = $this->getMock('\\OCP\\IUser');
+ $user
+ ->expects($this->exactly(2))
+ ->method('getUID')
+ ->willReturn('MyUserUid');
+ $this->userSession
+ ->expects($this->once())
+ ->method('getUser')
+ ->willReturn($user);
+ $this->groupManager
+ ->expects($this->once())
+ ->method('isAdmin')
+ ->with('MyUserUid')
+ ->willReturn(false);
+ $this->globalAuth
+ ->expects($this->once())
+ ->method('saveAuth')
+ ->with('MyUserUid', 'test', 'password');
+
+ $this->assertSame(true, $this->ajaxController->saveGlobalCredentials('MyUserUid', 'test', 'password'));
+ }
+
+ public function testSaveGlobalCredentialsAsNormalUserForAnotherUser() {
+ $user = $this->getMock('\\OCP\\IUser');
+ $user
+ ->expects($this->exactly(2))
+ ->method('getUID')
+ ->willReturn('MyUserUid');
+ $this->userSession
+ ->expects($this->once())
+ ->method('getUser')
+ ->willReturn($user);
+ $this->groupManager
+ ->expects($this->once())
+ ->method('isAdmin')
+ ->with('MyUserUid')
+ ->willReturn(false);
+
+ $this->assertSame(false, $this->ajaxController->saveGlobalCredentials('AnotherUserUid', 'test', 'password'));
+ }
+}