Completed
Push — master ( a5225b...08d4cc )
by
unknown
30:16
created
apps/files_external/lib/Lib/Auth/PublicKey/RSA.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -20,56 +20,56 @@
 block discarded – undo
20 20
  */
21 21
 class RSA extends AuthMechanism {
22 22
 
23
-	public function __construct(
24
-		IL10N $l,
25
-		private IConfig $config,
26
-	) {
27
-		$this
28
-			->setIdentifier('publickey::rsa')
29
-			->setScheme(self::SCHEME_PUBLICKEY)
30
-			->setText($l->t('RSA public key'))
31
-			->addParameters([
32
-				new DefinitionParameter('user', $l->t('Login')),
33
-				new DefinitionParameter('public_key', $l->t('Public key')),
34
-				(new DefinitionParameter('private_key', 'private_key'))
35
-					->setType(DefinitionParameter::VALUE_PASSWORD)
36
-					->setFlag(DefinitionParameter::FLAG_HIDDEN),
37
-			])
38
-			->addCustomJs('auth_rsa')
39
-		;
40
-	}
23
+    public function __construct(
24
+        IL10N $l,
25
+        private IConfig $config,
26
+    ) {
27
+        $this
28
+            ->setIdentifier('publickey::rsa')
29
+            ->setScheme(self::SCHEME_PUBLICKEY)
30
+            ->setText($l->t('RSA public key'))
31
+            ->addParameters([
32
+                new DefinitionParameter('user', $l->t('Login')),
33
+                new DefinitionParameter('public_key', $l->t('Public key')),
34
+                (new DefinitionParameter('private_key', 'private_key'))
35
+                    ->setType(DefinitionParameter::VALUE_PASSWORD)
36
+                    ->setFlag(DefinitionParameter::FLAG_HIDDEN),
37
+            ])
38
+            ->addCustomJs('auth_rsa')
39
+        ;
40
+    }
41 41
 
42
-	/**
43
-	 * @return void
44
-	 */
45
-	public function manipulateStorageConfig(StorageConfig &$storage, ?IUser $user = null) {
46
-		$auth = new RSACrypt();
47
-		$auth->setPassword($this->config->getSystemValue('secret', ''));
48
-		if (!$auth->loadKey($storage->getBackendOption('private_key'))) {
49
-			// Add fallback routine for a time where secret was not enforced to be exists
50
-			$auth->setPassword('');
51
-			if (!$auth->loadKey($storage->getBackendOption('private_key'))) {
52
-				throw new \RuntimeException('unable to load private key');
53
-			}
54
-		}
55
-		$storage->setBackendOption('public_key_auth', $auth);
56
-	}
42
+    /**
43
+     * @return void
44
+     */
45
+    public function manipulateStorageConfig(StorageConfig &$storage, ?IUser $user = null) {
46
+        $auth = new RSACrypt();
47
+        $auth->setPassword($this->config->getSystemValue('secret', ''));
48
+        if (!$auth->loadKey($storage->getBackendOption('private_key'))) {
49
+            // Add fallback routine for a time where secret was not enforced to be exists
50
+            $auth->setPassword('');
51
+            if (!$auth->loadKey($storage->getBackendOption('private_key'))) {
52
+                throw new \RuntimeException('unable to load private key');
53
+            }
54
+        }
55
+        $storage->setBackendOption('public_key_auth', $auth);
56
+    }
57 57
 
58
-	/**
59
-	 * Generate a keypair
60
-	 *
61
-	 * @param int $keyLenth
62
-	 * @return array ['privatekey' => $privateKey, 'publickey' => $publicKey]
63
-	 */
64
-	public function createKey($keyLength) {
65
-		$rsa = new RSACrypt();
66
-		$rsa->setPublicKeyFormat(RSACrypt::PUBLIC_FORMAT_OPENSSH);
67
-		$rsa->setPassword($this->config->getSystemValue('secret', ''));
58
+    /**
59
+     * Generate a keypair
60
+     *
61
+     * @param int $keyLenth
62
+     * @return array ['privatekey' => $privateKey, 'publickey' => $publicKey]
63
+     */
64
+    public function createKey($keyLength) {
65
+        $rsa = new RSACrypt();
66
+        $rsa->setPublicKeyFormat(RSACrypt::PUBLIC_FORMAT_OPENSSH);
67
+        $rsa->setPassword($this->config->getSystemValue('secret', ''));
68 68
 
69
-		if ($keyLength !== 1024 && $keyLength !== 2048 && $keyLength !== 4096) {
70
-			$keyLength = 1024;
71
-		}
69
+        if ($keyLength !== 1024 && $keyLength !== 2048 && $keyLength !== 4096) {
70
+            $keyLength = 1024;
71
+        }
72 72
 
73
-		return $rsa->createKey($keyLength);
74
-	}
73
+        return $rsa->createKey($keyLength);
74
+    }
75 75
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Backend/SFTP.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -13,23 +13,23 @@
 block discarded – undo
13 13
 use OCP\IL10N;
14 14
 
15 15
 class SFTP extends Backend {
16
-	public function __construct(IL10N $l, Password $legacyAuth) {
17
-		$this
18
-			->setIdentifier('sftp')
19
-			->addIdentifierAlias('\OC\Files\Storage\SFTP') // legacy compat
20
-			->setStorageClass('\OCA\Files_External\Lib\Storage\SFTP')
21
-			->setText($l->t('SFTP'))
22
-			->addParameters([
23
-				new DefinitionParameter('host', $l->t('Host')),
24
-				(new DefinitionParameter('port', $l->t('Port')))
25
-					->setFlag(DefinitionParameter::FLAG_OPTIONAL),
26
-				(new DefinitionParameter('root', $l->t('Root')))
27
-					->setFlag(DefinitionParameter::FLAG_OPTIONAL),
28
-			])
29
-			->addAuthScheme(AuthMechanism::SCHEME_PASSWORD)
30
-			->addAuthScheme(AuthMechanism::SCHEME_PUBLICKEY)
31
-			->addAuthScheme(AuthMechanism::SCHEME_OAUTH2)
32
-			->setLegacyAuthMechanism($legacyAuth)
33
-		;
34
-	}
16
+    public function __construct(IL10N $l, Password $legacyAuth) {
17
+        $this
18
+            ->setIdentifier('sftp')
19
+            ->addIdentifierAlias('\OC\Files\Storage\SFTP') // legacy compat
20
+            ->setStorageClass('\OCA\Files_External\Lib\Storage\SFTP')
21
+            ->setText($l->t('SFTP'))
22
+            ->addParameters([
23
+                new DefinitionParameter('host', $l->t('Host')),
24
+                (new DefinitionParameter('port', $l->t('Port')))
25
+                    ->setFlag(DefinitionParameter::FLAG_OPTIONAL),
26
+                (new DefinitionParameter('root', $l->t('Root')))
27
+                    ->setFlag(DefinitionParameter::FLAG_OPTIONAL),
28
+            ])
29
+            ->addAuthScheme(AuthMechanism::SCHEME_PASSWORD)
30
+            ->addAuthScheme(AuthMechanism::SCHEME_PUBLICKEY)
31
+            ->addAuthScheme(AuthMechanism::SCHEME_OAUTH2)
32
+            ->setLegacyAuthMechanism($legacyAuth)
33
+        ;
34
+    }
35 35
 }
Please login to merge, or discard this patch.
apps/files_external/lib/AppInfo/Application.php 1 patch
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -59,95 +59,95 @@
 block discarded – undo
59 59
  * @package OCA\Files_External\AppInfo
60 60
  */
61 61
 class Application extends App implements IBackendProvider, IAuthMechanismProvider, IBootstrap {
62
-	public const APP_ID = 'files_external';
63
-
64
-	/**
65
-	 * Application constructor.
66
-	 *
67
-	 * @throws QueryException
68
-	 */
69
-	public function __construct(array $urlParams = []) {
70
-		parent::__construct(self::APP_ID, $urlParams);
71
-	}
72
-
73
-	public function register(IRegistrationContext $context): void {
74
-		$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class);
75
-		$context->registerEventListener(GroupDeletedEvent::class, GroupDeletedListener::class);
76
-		$context->registerEventListener(LoadAdditionalScriptsEvent::class, LoadAdditionalListener::class);
77
-		$context->registerEventListener(UserLoggedInEvent::class, StorePasswordListener::class);
78
-		$context->registerEventListener(PasswordUpdatedEvent::class, StorePasswordListener::class);
79
-		$context->registerConfigLexicon(ConfigLexicon::class);
80
-	}
81
-
82
-	public function boot(IBootContext $context): void {
83
-		$context->injectFn(function (IMountProviderCollection $mountProviderCollection, ConfigAdapter $configAdapter): void {
84
-			$mountProviderCollection->registerProvider($configAdapter);
85
-		});
86
-		$context->injectFn(function (BackendService $backendService, UserPlaceholderHandler $userConfigHandler): void {
87
-			$backendService->registerBackendProvider($this);
88
-			$backendService->registerAuthMechanismProvider($this);
89
-			$backendService->registerConfigHandler('user', function () use ($userConfigHandler) {
90
-				return $userConfigHandler;
91
-			});
92
-		});
93
-	}
94
-
95
-	/**
96
-	 * @{inheritdoc}
97
-	 */
98
-	public function getBackends() {
99
-		$container = $this->getContainer();
100
-
101
-		$backends = [
102
-			$container->get(Local::class),
103
-			$container->get(FTP::class),
104
-			$container->get(DAV::class),
105
-			$container->get(OwnCloud::class),
106
-			$container->get(SFTP::class),
107
-			$container->get(AmazonS3::class),
108
-			$container->get(Swift::class),
109
-			$container->get(SFTP_Key::class),
110
-			$container->get(SMB::class),
111
-			$container->get(SMB_OC::class),
112
-		];
113
-
114
-		return $backends;
115
-	}
116
-
117
-	/**
118
-	 * @{inheritdoc}
119
-	 */
120
-	public function getAuthMechanisms() {
121
-		$container = $this->getContainer();
122
-
123
-		return [
124
-			// AuthMechanism::SCHEME_NULL mechanism
125
-			$container->get(NullMechanism::class),
126
-
127
-			// AuthMechanism::SCHEME_BUILTIN mechanism
128
-			$container->get(Builtin::class),
129
-
130
-			// AuthMechanism::SCHEME_PASSWORD mechanisms
131
-			$container->get(Password::class),
132
-			$container->get(SessionCredentials::class),
133
-			$container->get(LoginCredentials::class),
134
-			$container->get(UserProvided::class),
135
-			$container->get(GlobalAuth::class),
136
-			$container->get(UserGlobalAuth::class),
137
-
138
-			// AuthMechanism::SCHEME_PUBLICKEY mechanisms
139
-			$container->get(RSA::class),
140
-			$container->get(RSAPrivateKey::class),
141
-
142
-			// AuthMechanism::SCHEME_OPENSTACK mechanisms
143
-			$container->get(OpenStackV2::class),
144
-			$container->get(OpenStackV3::class),
145
-			$container->get(Rackspace::class),
146
-
147
-			// Specialized mechanisms
148
-			$container->get(AccessKey::class),
149
-			$container->get(KerberosAuth::class),
150
-			$container->get(KerberosApacheAuth::class),
151
-		];
152
-	}
62
+    public const APP_ID = 'files_external';
63
+
64
+    /**
65
+     * Application constructor.
66
+     *
67
+     * @throws QueryException
68
+     */
69
+    public function __construct(array $urlParams = []) {
70
+        parent::__construct(self::APP_ID, $urlParams);
71
+    }
72
+
73
+    public function register(IRegistrationContext $context): void {
74
+        $context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class);
75
+        $context->registerEventListener(GroupDeletedEvent::class, GroupDeletedListener::class);
76
+        $context->registerEventListener(LoadAdditionalScriptsEvent::class, LoadAdditionalListener::class);
77
+        $context->registerEventListener(UserLoggedInEvent::class, StorePasswordListener::class);
78
+        $context->registerEventListener(PasswordUpdatedEvent::class, StorePasswordListener::class);
79
+        $context->registerConfigLexicon(ConfigLexicon::class);
80
+    }
81
+
82
+    public function boot(IBootContext $context): void {
83
+        $context->injectFn(function (IMountProviderCollection $mountProviderCollection, ConfigAdapter $configAdapter): void {
84
+            $mountProviderCollection->registerProvider($configAdapter);
85
+        });
86
+        $context->injectFn(function (BackendService $backendService, UserPlaceholderHandler $userConfigHandler): void {
87
+            $backendService->registerBackendProvider($this);
88
+            $backendService->registerAuthMechanismProvider($this);
89
+            $backendService->registerConfigHandler('user', function () use ($userConfigHandler) {
90
+                return $userConfigHandler;
91
+            });
92
+        });
93
+    }
94
+
95
+    /**
96
+     * @{inheritdoc}
97
+     */
98
+    public function getBackends() {
99
+        $container = $this->getContainer();
100
+
101
+        $backends = [
102
+            $container->get(Local::class),
103
+            $container->get(FTP::class),
104
+            $container->get(DAV::class),
105
+            $container->get(OwnCloud::class),
106
+            $container->get(SFTP::class),
107
+            $container->get(AmazonS3::class),
108
+            $container->get(Swift::class),
109
+            $container->get(SFTP_Key::class),
110
+            $container->get(SMB::class),
111
+            $container->get(SMB_OC::class),
112
+        ];
113
+
114
+        return $backends;
115
+    }
116
+
117
+    /**
118
+     * @{inheritdoc}
119
+     */
120
+    public function getAuthMechanisms() {
121
+        $container = $this->getContainer();
122
+
123
+        return [
124
+            // AuthMechanism::SCHEME_NULL mechanism
125
+            $container->get(NullMechanism::class),
126
+
127
+            // AuthMechanism::SCHEME_BUILTIN mechanism
128
+            $container->get(Builtin::class),
129
+
130
+            // AuthMechanism::SCHEME_PASSWORD mechanisms
131
+            $container->get(Password::class),
132
+            $container->get(SessionCredentials::class),
133
+            $container->get(LoginCredentials::class),
134
+            $container->get(UserProvided::class),
135
+            $container->get(GlobalAuth::class),
136
+            $container->get(UserGlobalAuth::class),
137
+
138
+            // AuthMechanism::SCHEME_PUBLICKEY mechanisms
139
+            $container->get(RSA::class),
140
+            $container->get(RSAPrivateKey::class),
141
+
142
+            // AuthMechanism::SCHEME_OPENSTACK mechanisms
143
+            $container->get(OpenStackV2::class),
144
+            $container->get(OpenStackV3::class),
145
+            $container->get(Rackspace::class),
146
+
147
+            // Specialized mechanisms
148
+            $container->get(AccessKey::class),
149
+            $container->get(KerberosAuth::class),
150
+            $container->get(KerberosApacheAuth::class),
151
+        ];
152
+    }
153 153
 }
Please login to merge, or discard this patch.
apps/files_external/lib/MountConfig.php 2 patches
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -27,176 +27,176 @@
 block discarded – undo
27 27
  * Class to configure mount.json globally and for users
28 28
  */
29 29
 class MountConfig {
30
-	// TODO: make this class non-static and give it a proper namespace
30
+    // TODO: make this class non-static and give it a proper namespace
31 31
 
32
-	public const MOUNT_TYPE_GLOBAL = 'global';
33
-	public const MOUNT_TYPE_GROUP = 'group';
34
-	public const MOUNT_TYPE_USER = 'user';
35
-	public const MOUNT_TYPE_PERSONAL = 'personal';
32
+    public const MOUNT_TYPE_GLOBAL = 'global';
33
+    public const MOUNT_TYPE_GROUP = 'group';
34
+    public const MOUNT_TYPE_USER = 'user';
35
+    public const MOUNT_TYPE_PERSONAL = 'personal';
36 36
 
37
-	// whether to skip backend test (for unit tests, as this static class is not mockable)
38
-	public static $skipTest = false;
37
+    // whether to skip backend test (for unit tests, as this static class is not mockable)
38
+    public static $skipTest = false;
39 39
 
40
-	public function __construct(
41
-		private UserGlobalStoragesService $userGlobalStorageService,
42
-		private UserStoragesService $userStorageService,
43
-		private GlobalStoragesService $globalStorageService,
44
-	) {
45
-	}
40
+    public function __construct(
41
+        private UserGlobalStoragesService $userGlobalStorageService,
42
+        private UserStoragesService $userStorageService,
43
+        private GlobalStoragesService $globalStorageService,
44
+    ) {
45
+    }
46 46
 
47
-	/**
48
-	 * @param mixed $input
49
-	 * @param string|null $userId
50
-	 * @return mixed
51
-	 * @throws QueryException
52
-	 * @since 16.0.0
53
-	 */
54
-	public static function substitutePlaceholdersInConfig($input, ?string $userId = null) {
55
-		/** @var BackendService $backendService */
56
-		$backendService = Server::get(BackendService::class);
57
-		/** @var IConfigHandler[] $handlers */
58
-		$handlers = $backendService->getConfigHandlers();
59
-		foreach ($handlers as $handler) {
60
-			if ($handler instanceof UserContext && $userId !== null) {
61
-				$handler->setUserId($userId);
62
-			}
63
-			$input = $handler->handle($input);
64
-		}
65
-		return $input;
66
-	}
47
+    /**
48
+     * @param mixed $input
49
+     * @param string|null $userId
50
+     * @return mixed
51
+     * @throws QueryException
52
+     * @since 16.0.0
53
+     */
54
+    public static function substitutePlaceholdersInConfig($input, ?string $userId = null) {
55
+        /** @var BackendService $backendService */
56
+        $backendService = Server::get(BackendService::class);
57
+        /** @var IConfigHandler[] $handlers */
58
+        $handlers = $backendService->getConfigHandlers();
59
+        foreach ($handlers as $handler) {
60
+            if ($handler instanceof UserContext && $userId !== null) {
61
+                $handler->setUserId($userId);
62
+            }
63
+            $input = $handler->handle($input);
64
+        }
65
+        return $input;
66
+    }
67 67
 
68
-	/**
69
-	 * Test connecting using the given backend configuration
70
-	 *
71
-	 * @param string $class backend class name
72
-	 * @param array $options backend configuration options
73
-	 * @param boolean $isPersonal
74
-	 * @return int see self::STATUS_*
75
-	 * @throws \Exception
76
-	 */
77
-	public static function getBackendStatus($class, $options) {
78
-		if (self::$skipTest) {
79
-			return StorageNotAvailableException::STATUS_SUCCESS;
80
-		}
81
-		foreach ($options as $key => &$option) {
82
-			if ($key === 'password') {
83
-				// no replacements in passwords
84
-				continue;
85
-			}
86
-			$option = self::substitutePlaceholdersInConfig($option);
87
-		}
88
-		if (class_exists($class)) {
89
-			try {
90
-				/** @var Common $storage */
91
-				$storage = new $class($options);
68
+    /**
69
+     * Test connecting using the given backend configuration
70
+     *
71
+     * @param string $class backend class name
72
+     * @param array $options backend configuration options
73
+     * @param boolean $isPersonal
74
+     * @return int see self::STATUS_*
75
+     * @throws \Exception
76
+     */
77
+    public static function getBackendStatus($class, $options) {
78
+        if (self::$skipTest) {
79
+            return StorageNotAvailableException::STATUS_SUCCESS;
80
+        }
81
+        foreach ($options as $key => &$option) {
82
+            if ($key === 'password') {
83
+                // no replacements in passwords
84
+                continue;
85
+            }
86
+            $option = self::substitutePlaceholdersInConfig($option);
87
+        }
88
+        if (class_exists($class)) {
89
+            try {
90
+                /** @var Common $storage */
91
+                $storage = new $class($options);
92 92
 
93
-				try {
94
-					$result = $storage->test();
95
-					$storage->setAvailability($result);
96
-					if ($result) {
97
-						return StorageNotAvailableException::STATUS_SUCCESS;
98
-					}
99
-				} catch (\Exception $e) {
100
-					$storage->setAvailability(false);
101
-					throw $e;
102
-				}
103
-			} catch (\Exception $exception) {
104
-				Server::get(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception, 'app' => 'files_external']);
105
-				throw $exception;
106
-			}
107
-		}
108
-		return StorageNotAvailableException::STATUS_ERROR;
109
-	}
93
+                try {
94
+                    $result = $storage->test();
95
+                    $storage->setAvailability($result);
96
+                    if ($result) {
97
+                        return StorageNotAvailableException::STATUS_SUCCESS;
98
+                    }
99
+                } catch (\Exception $e) {
100
+                    $storage->setAvailability(false);
101
+                    throw $e;
102
+                }
103
+            } catch (\Exception $exception) {
104
+                Server::get(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception, 'app' => 'files_external']);
105
+                throw $exception;
106
+            }
107
+        }
108
+        return StorageNotAvailableException::STATUS_ERROR;
109
+    }
110 110
 
111
-	/**
112
-	 * Encrypt passwords in the given config options
113
-	 *
114
-	 * @param array $options mount options
115
-	 * @return array updated options
116
-	 */
117
-	public static function encryptPasswords($options) {
118
-		if (isset($options['password'])) {
119
-			$options['password_encrypted'] = self::encryptPassword($options['password']);
120
-			// do not unset the password, we want to keep the keys order
121
-			// on load... because that's how the UI currently works
122
-			$options['password'] = '';
123
-		}
124
-		return $options;
125
-	}
111
+    /**
112
+     * Encrypt passwords in the given config options
113
+     *
114
+     * @param array $options mount options
115
+     * @return array updated options
116
+     */
117
+    public static function encryptPasswords($options) {
118
+        if (isset($options['password'])) {
119
+            $options['password_encrypted'] = self::encryptPassword($options['password']);
120
+            // do not unset the password, we want to keep the keys order
121
+            // on load... because that's how the UI currently works
122
+            $options['password'] = '';
123
+        }
124
+        return $options;
125
+    }
126 126
 
127
-	/**
128
-	 * Decrypt passwords in the given config options
129
-	 *
130
-	 * @param array $options mount options
131
-	 * @return array updated options
132
-	 */
133
-	public static function decryptPasswords($options) {
134
-		// note: legacy options might still have the unencrypted password in the "password" field
135
-		if (isset($options['password_encrypted'])) {
136
-			$options['password'] = self::decryptPassword($options['password_encrypted']);
137
-			unset($options['password_encrypted']);
138
-		}
139
-		return $options;
140
-	}
127
+    /**
128
+     * Decrypt passwords in the given config options
129
+     *
130
+     * @param array $options mount options
131
+     * @return array updated options
132
+     */
133
+    public static function decryptPasswords($options) {
134
+        // note: legacy options might still have the unencrypted password in the "password" field
135
+        if (isset($options['password_encrypted'])) {
136
+            $options['password'] = self::decryptPassword($options['password_encrypted']);
137
+            unset($options['password_encrypted']);
138
+        }
139
+        return $options;
140
+    }
141 141
 
142
-	/**
143
-	 * Encrypt a single password
144
-	 *
145
-	 * @param string $password plain text password
146
-	 * @return string encrypted password
147
-	 */
148
-	private static function encryptPassword($password) {
149
-		$cipher = self::getCipher();
150
-		$iv = Server::get(ISecureRandom::class)->generate(16);
151
-		$cipher->setIV($iv);
152
-		return base64_encode($iv . $cipher->encrypt($password));
153
-	}
142
+    /**
143
+     * Encrypt a single password
144
+     *
145
+     * @param string $password plain text password
146
+     * @return string encrypted password
147
+     */
148
+    private static function encryptPassword($password) {
149
+        $cipher = self::getCipher();
150
+        $iv = Server::get(ISecureRandom::class)->generate(16);
151
+        $cipher->setIV($iv);
152
+        return base64_encode($iv . $cipher->encrypt($password));
153
+    }
154 154
 
155
-	/**
156
-	 * Decrypts a single password
157
-	 *
158
-	 * @param string $encryptedPassword encrypted password
159
-	 * @return string plain text password
160
-	 */
161
-	private static function decryptPassword($encryptedPassword) {
162
-		$cipher = self::getCipher();
163
-		$binaryPassword = base64_decode($encryptedPassword);
164
-		$iv = substr($binaryPassword, 0, 16);
165
-		$cipher->setIV($iv);
166
-		$binaryPassword = substr($binaryPassword, 16);
167
-		return $cipher->decrypt($binaryPassword);
168
-	}
155
+    /**
156
+     * Decrypts a single password
157
+     *
158
+     * @param string $encryptedPassword encrypted password
159
+     * @return string plain text password
160
+     */
161
+    private static function decryptPassword($encryptedPassword) {
162
+        $cipher = self::getCipher();
163
+        $binaryPassword = base64_decode($encryptedPassword);
164
+        $iv = substr($binaryPassword, 0, 16);
165
+        $cipher->setIV($iv);
166
+        $binaryPassword = substr($binaryPassword, 16);
167
+        return $cipher->decrypt($binaryPassword);
168
+    }
169 169
 
170
-	/**
171
-	 * Returns the encryption cipher
172
-	 *
173
-	 * @return AES
174
-	 */
175
-	private static function getCipher() {
176
-		$cipher = new AES(AES::MODE_CBC);
177
-		$cipher->setKey(Server::get(IConfig::class)->getSystemValue('passwordsalt', null));
178
-		return $cipher;
179
-	}
170
+    /**
171
+     * Returns the encryption cipher
172
+     *
173
+     * @return AES
174
+     */
175
+    private static function getCipher() {
176
+        $cipher = new AES(AES::MODE_CBC);
177
+        $cipher->setKey(Server::get(IConfig::class)->getSystemValue('passwordsalt', null));
178
+        return $cipher;
179
+    }
180 180
 
181
-	/**
182
-	 * Computes a hash based on the given configuration.
183
-	 * This is mostly used to find out whether configurations
184
-	 * are the same.
185
-	 *
186
-	 * @param array $config
187
-	 * @return string
188
-	 */
189
-	public static function makeConfigHash($config) {
190
-		$data = json_encode(
191
-			[
192
-				'c' => $config['backend'],
193
-				'a' => $config['authMechanism'],
194
-				'm' => $config['mountpoint'],
195
-				'o' => $config['options'],
196
-				'p' => $config['priority'] ?? -1,
197
-				'mo' => $config['mountOptions'] ?? [],
198
-			]
199
-		);
200
-		return hash('md5', $data);
201
-	}
181
+    /**
182
+     * Computes a hash based on the given configuration.
183
+     * This is mostly used to find out whether configurations
184
+     * are the same.
185
+     *
186
+     * @param array $config
187
+     * @return string
188
+     */
189
+    public static function makeConfigHash($config) {
190
+        $data = json_encode(
191
+            [
192
+                'c' => $config['backend'],
193
+                'a' => $config['authMechanism'],
194
+                'm' => $config['mountpoint'],
195
+                'o' => $config['options'],
196
+                'p' => $config['priority'] ?? -1,
197
+                'mo' => $config['mountOptions'] ?? [],
198
+            ]
199
+        );
200
+        return hash('md5', $data);
201
+    }
202 202
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -149,7 +149,7 @@
 block discarded – undo
149 149
 		$cipher = self::getCipher();
150 150
 		$iv = Server::get(ISecureRandom::class)->generate(16);
151 151
 		$cipher->setIV($iv);
152
-		return base64_encode($iv . $cipher->encrypt($password));
152
+		return base64_encode($iv.$cipher->encrypt($password));
153 153
 	}
154 154
 
155 155
 	/**
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/GlobalStoragesController.php 1 patch
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -23,167 +23,167 @@
 block discarded – undo
23 23
  * Global storages controller
24 24
  */
25 25
 class GlobalStoragesController extends StoragesController {
26
-	/**
27
-	 * Creates a new global storages controller.
28
-	 *
29
-	 * @param string $AppName application name
30
-	 * @param IRequest $request request object
31
-	 * @param IL10N $l10n l10n service
32
-	 * @param GlobalStoragesService $globalStoragesService storage service
33
-	 * @param LoggerInterface $logger
34
-	 * @param IUserSession $userSession
35
-	 * @param IGroupManager $groupManager
36
-	 * @param IConfig $config
37
-	 */
38
-	public function __construct(
39
-		$appName,
40
-		IRequest $request,
41
-		IL10N $l10n,
42
-		GlobalStoragesService $globalStoragesService,
43
-		LoggerInterface $logger,
44
-		IUserSession $userSession,
45
-		IGroupManager $groupManager,
46
-		IConfig $config,
47
-	) {
48
-		parent::__construct(
49
-			$appName,
50
-			$request,
51
-			$l10n,
52
-			$globalStoragesService,
53
-			$logger,
54
-			$userSession,
55
-			$groupManager,
56
-			$config
57
-		);
58
-	}
26
+    /**
27
+     * Creates a new global storages controller.
28
+     *
29
+     * @param string $AppName application name
30
+     * @param IRequest $request request object
31
+     * @param IL10N $l10n l10n service
32
+     * @param GlobalStoragesService $globalStoragesService storage service
33
+     * @param LoggerInterface $logger
34
+     * @param IUserSession $userSession
35
+     * @param IGroupManager $groupManager
36
+     * @param IConfig $config
37
+     */
38
+    public function __construct(
39
+        $appName,
40
+        IRequest $request,
41
+        IL10N $l10n,
42
+        GlobalStoragesService $globalStoragesService,
43
+        LoggerInterface $logger,
44
+        IUserSession $userSession,
45
+        IGroupManager $groupManager,
46
+        IConfig $config,
47
+    ) {
48
+        parent::__construct(
49
+            $appName,
50
+            $request,
51
+            $l10n,
52
+            $globalStoragesService,
53
+            $logger,
54
+            $userSession,
55
+            $groupManager,
56
+            $config
57
+        );
58
+    }
59 59
 
60
-	/**
61
-	 * Create an external storage entry.
62
-	 *
63
-	 * @param string $mountPoint storage mount point
64
-	 * @param string $backend backend identifier
65
-	 * @param string $authMechanism authentication mechanism identifier
66
-	 * @param array $backendOptions backend-specific options
67
-	 * @param array $mountOptions mount-specific options
68
-	 * @param array $applicableUsers users for which to mount the storage
69
-	 * @param array $applicableGroups groups for which to mount the storage
70
-	 * @param int $priority priority
71
-	 *
72
-	 * @return DataResponse
73
-	 */
74
-	#[PasswordConfirmationRequired(strict: true)]
75
-	public function create(
76
-		string $mountPoint,
77
-		string $backend,
78
-		string $authMechanism,
79
-		$backendOptions,
80
-		$mountOptions,
81
-		$applicableUsers,
82
-		$applicableGroups,
83
-		$priority,
84
-	) {
85
-		$canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
86
-		if (!$canCreateNewLocalStorage && $backend === 'local') {
87
-			return new DataResponse(
88
-				[
89
-					'message' => $this->l10n->t('Forbidden to manage local mounts')
90
-				],
91
-				Http::STATUS_FORBIDDEN
92
-			);
93
-		}
60
+    /**
61
+     * Create an external storage entry.
62
+     *
63
+     * @param string $mountPoint storage mount point
64
+     * @param string $backend backend identifier
65
+     * @param string $authMechanism authentication mechanism identifier
66
+     * @param array $backendOptions backend-specific options
67
+     * @param array $mountOptions mount-specific options
68
+     * @param array $applicableUsers users for which to mount the storage
69
+     * @param array $applicableGroups groups for which to mount the storage
70
+     * @param int $priority priority
71
+     *
72
+     * @return DataResponse
73
+     */
74
+    #[PasswordConfirmationRequired(strict: true)]
75
+    public function create(
76
+        string $mountPoint,
77
+        string $backend,
78
+        string $authMechanism,
79
+        $backendOptions,
80
+        $mountOptions,
81
+        $applicableUsers,
82
+        $applicableGroups,
83
+        $priority,
84
+    ) {
85
+        $canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
86
+        if (!$canCreateNewLocalStorage && $backend === 'local') {
87
+            return new DataResponse(
88
+                [
89
+                    'message' => $this->l10n->t('Forbidden to manage local mounts')
90
+                ],
91
+                Http::STATUS_FORBIDDEN
92
+            );
93
+        }
94 94
 
95
-		$newStorage = $this->createStorage(
96
-			$mountPoint,
97
-			$backend,
98
-			$authMechanism,
99
-			$backendOptions,
100
-			$mountOptions,
101
-			$applicableUsers,
102
-			$applicableGroups,
103
-			$priority
104
-		);
105
-		if ($newStorage instanceof DataResponse) {
106
-			return $newStorage;
107
-		}
95
+        $newStorage = $this->createStorage(
96
+            $mountPoint,
97
+            $backend,
98
+            $authMechanism,
99
+            $backendOptions,
100
+            $mountOptions,
101
+            $applicableUsers,
102
+            $applicableGroups,
103
+            $priority
104
+        );
105
+        if ($newStorage instanceof DataResponse) {
106
+            return $newStorage;
107
+        }
108 108
 
109
-		$response = $this->validate($newStorage);
110
-		if (!empty($response)) {
111
-			return $response;
112
-		}
109
+        $response = $this->validate($newStorage);
110
+        if (!empty($response)) {
111
+            return $response;
112
+        }
113 113
 
114
-		$newStorage = $this->service->addStorage($newStorage);
114
+        $newStorage = $this->service->addStorage($newStorage);
115 115
 
116
-		$this->updateStorageStatus($newStorage);
116
+        $this->updateStorageStatus($newStorage);
117 117
 
118
-		return new DataResponse(
119
-			$newStorage->jsonSerialize(true),
120
-			Http::STATUS_CREATED
121
-		);
122
-	}
118
+        return new DataResponse(
119
+            $newStorage->jsonSerialize(true),
120
+            Http::STATUS_CREATED
121
+        );
122
+    }
123 123
 
124
-	/**
125
-	 * Update an external storage entry.
126
-	 *
127
-	 * @param int $id storage id
128
-	 * @param string $mountPoint storage mount point
129
-	 * @param string $backend backend identifier
130
-	 * @param string $authMechanism authentication mechanism identifier
131
-	 * @param array $backendOptions backend-specific options
132
-	 * @param array $mountOptions mount-specific options
133
-	 * @param array $applicableUsers users for which to mount the storage
134
-	 * @param array $applicableGroups groups for which to mount the storage
135
-	 * @param int $priority priority
136
-	 *
137
-	 * @return DataResponse
138
-	 */
139
-	#[PasswordConfirmationRequired(strict: true)]
140
-	public function update(
141
-		int $id,
142
-		string $mountPoint,
143
-		string $backend,
144
-		string $authMechanism,
145
-		$backendOptions,
146
-		$mountOptions,
147
-		$applicableUsers,
148
-		$applicableGroups,
149
-		$priority,
150
-	) {
151
-		$storage = $this->createStorage(
152
-			$mountPoint,
153
-			$backend,
154
-			$authMechanism,
155
-			$backendOptions,
156
-			$mountOptions,
157
-			$applicableUsers,
158
-			$applicableGroups,
159
-			$priority
160
-		);
161
-		if ($storage instanceof DataResponse) {
162
-			return $storage;
163
-		}
164
-		$storage->setId($id);
124
+    /**
125
+     * Update an external storage entry.
126
+     *
127
+     * @param int $id storage id
128
+     * @param string $mountPoint storage mount point
129
+     * @param string $backend backend identifier
130
+     * @param string $authMechanism authentication mechanism identifier
131
+     * @param array $backendOptions backend-specific options
132
+     * @param array $mountOptions mount-specific options
133
+     * @param array $applicableUsers users for which to mount the storage
134
+     * @param array $applicableGroups groups for which to mount the storage
135
+     * @param int $priority priority
136
+     *
137
+     * @return DataResponse
138
+     */
139
+    #[PasswordConfirmationRequired(strict: true)]
140
+    public function update(
141
+        int $id,
142
+        string $mountPoint,
143
+        string $backend,
144
+        string $authMechanism,
145
+        $backendOptions,
146
+        $mountOptions,
147
+        $applicableUsers,
148
+        $applicableGroups,
149
+        $priority,
150
+    ) {
151
+        $storage = $this->createStorage(
152
+            $mountPoint,
153
+            $backend,
154
+            $authMechanism,
155
+            $backendOptions,
156
+            $mountOptions,
157
+            $applicableUsers,
158
+            $applicableGroups,
159
+            $priority
160
+        );
161
+        if ($storage instanceof DataResponse) {
162
+            return $storage;
163
+        }
164
+        $storage->setId($id);
165 165
 
166
-		$response = $this->validate($storage);
167
-		if (!empty($response)) {
168
-			return $response;
169
-		}
166
+        $response = $this->validate($storage);
167
+        if (!empty($response)) {
168
+            return $response;
169
+        }
170 170
 
171
-		try {
172
-			$storage = $this->service->updateStorage($storage);
173
-		} catch (NotFoundException $e) {
174
-			return new DataResponse(
175
-				[
176
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
177
-				],
178
-				Http::STATUS_NOT_FOUND
179
-			);
180
-		}
171
+        try {
172
+            $storage = $this->service->updateStorage($storage);
173
+        } catch (NotFoundException $e) {
174
+            return new DataResponse(
175
+                [
176
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
177
+                ],
178
+                Http::STATUS_NOT_FOUND
179
+            );
180
+        }
181 181
 
182
-		$this->updateStorageStatus($storage);
182
+        $this->updateStorageStatus($storage);
183 183
 
184
-		return new DataResponse(
185
-			$storage->jsonSerialize(true),
186
-			Http::STATUS_OK
187
-		);
188
-	}
184
+        return new DataResponse(
185
+            $storage->jsonSerialize(true),
186
+            Http::STATUS_OK
187
+        );
188
+    }
189 189
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/UserGlobalStoragesController.php 1 patch
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -30,164 +30,164 @@
 block discarded – undo
30 30
  * User global storages controller
31 31
  */
32 32
 class UserGlobalStoragesController extends StoragesController {
33
-	/**
34
-	 * Creates a new user global storages controller.
35
-	 *
36
-	 * @param string $AppName application name
37
-	 * @param IRequest $request request object
38
-	 * @param IL10N $l10n l10n service
39
-	 * @param UserGlobalStoragesService $userGlobalStoragesService storage service
40
-	 * @param LoggerInterface $logger
41
-	 * @param IUserSession $userSession
42
-	 * @param IGroupManager $groupManager
43
-	 */
44
-	public function __construct(
45
-		$appName,
46
-		IRequest $request,
47
-		IL10N $l10n,
48
-		UserGlobalStoragesService $userGlobalStoragesService,
49
-		LoggerInterface $logger,
50
-		IUserSession $userSession,
51
-		IGroupManager $groupManager,
52
-		IConfig $config,
53
-	) {
54
-		parent::__construct(
55
-			$appName,
56
-			$request,
57
-			$l10n,
58
-			$userGlobalStoragesService,
59
-			$logger,
60
-			$userSession,
61
-			$groupManager,
62
-			$config
63
-		);
64
-	}
65
-
66
-	/**
67
-	 * Get all storage entries
68
-	 *
69
-	 * @return DataResponse
70
-	 */
71
-	#[NoAdminRequired]
72
-	public function index() {
73
-		/** @var UserGlobalStoragesService */
74
-		$service = $this->service;
75
-		$storages = array_map(function ($storage) {
76
-			// remove configuration data, this must be kept private
77
-			$this->sanitizeStorage($storage);
78
-			return $storage->jsonSerialize(true);
79
-		}, $service->getUniqueStorages());
80
-
81
-		return new DataResponse(
82
-			$storages,
83
-			Http::STATUS_OK
84
-		);
85
-	}
86
-
87
-	protected function manipulateStorageConfig(StorageConfig $storage) {
88
-		/** @var AuthMechanism */
89
-		$authMechanism = $storage->getAuthMechanism();
90
-		$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
91
-		/** @var Backend */
92
-		$backend = $storage->getBackend();
93
-		$backend->manipulateStorageConfig($storage, $this->userSession->getUser());
94
-	}
95
-
96
-	/**
97
-	 * Get an external storage entry.
98
-	 *
99
-	 * @param int $id storage id
100
-	 * @return DataResponse
101
-	 */
102
-	#[NoAdminRequired]
103
-	public function show($id) {
104
-		try {
105
-			$storage = $this->service->getStorage($id);
106
-
107
-			$this->updateStorageStatus($storage);
108
-		} catch (NotFoundException $e) {
109
-			return new DataResponse(
110
-				[
111
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
112
-				],
113
-				Http::STATUS_NOT_FOUND
114
-			);
115
-		}
116
-
117
-		$this->sanitizeStorage($storage);
118
-
119
-		$data = $storage->jsonSerialize(true);
120
-		$isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
121
-		$data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAL || $isAdmin;
122
-
123
-		return new DataResponse(
124
-			$data,
125
-			Http::STATUS_OK
126
-		);
127
-	}
128
-
129
-	/**
130
-	 * Update an external storage entry.
131
-	 * Only allows setting user provided backend fields
132
-	 *
133
-	 * @param int $id storage id
134
-	 * @param array $backendOptions backend-specific options
135
-	 *
136
-	 * @return DataResponse
137
-	 */
138
-	#[NoAdminRequired]
139
-	#[PasswordConfirmationRequired(strict: true)]
140
-	public function update(
141
-		int $id,
142
-		$backendOptions,
143
-	) {
144
-		try {
145
-			$storage = $this->service->getStorage($id);
146
-			$authMechanism = $storage->getAuthMechanism();
147
-			if ($authMechanism instanceof IUserProvided || $authMechanism instanceof  UserGlobalAuth) {
148
-				$authMechanism->saveBackendOptions($this->userSession->getUser(), $id, $backendOptions);
149
-				$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
150
-			} else {
151
-				return new DataResponse(
152
-					[
153
-						'message' => $this->l10n->t('Storage with ID "%d" is not editable by non-admins', [$id])
154
-					],
155
-					Http::STATUS_FORBIDDEN
156
-				);
157
-			}
158
-		} catch (NotFoundException $e) {
159
-			return new DataResponse(
160
-				[
161
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
162
-				],
163
-				Http::STATUS_NOT_FOUND
164
-			);
165
-		}
166
-
167
-		$this->updateStorageStatus($storage);
168
-		$this->sanitizeStorage($storage);
169
-
170
-		return new DataResponse(
171
-			$storage->jsonSerialize(true),
172
-			Http::STATUS_OK
173
-		);
174
-	}
175
-
176
-	/**
177
-	 * Remove sensitive data from a StorageConfig before returning it to the user
178
-	 *
179
-	 * @param StorageConfig $storage
180
-	 */
181
-	protected function sanitizeStorage(StorageConfig $storage) {
182
-		$storage->setBackendOptions([]);
183
-		$storage->setMountOptions([]);
184
-
185
-		if ($storage->getAuthMechanism() instanceof IUserProvided) {
186
-			try {
187
-				$storage->getAuthMechanism()->manipulateStorageConfig($storage, $this->userSession->getUser());
188
-			} catch (InsufficientDataForMeaningfulAnswerException $e) {
189
-				// not configured yet
190
-			}
191
-		}
192
-	}
33
+    /**
34
+     * Creates a new user global storages controller.
35
+     *
36
+     * @param string $AppName application name
37
+     * @param IRequest $request request object
38
+     * @param IL10N $l10n l10n service
39
+     * @param UserGlobalStoragesService $userGlobalStoragesService storage service
40
+     * @param LoggerInterface $logger
41
+     * @param IUserSession $userSession
42
+     * @param IGroupManager $groupManager
43
+     */
44
+    public function __construct(
45
+        $appName,
46
+        IRequest $request,
47
+        IL10N $l10n,
48
+        UserGlobalStoragesService $userGlobalStoragesService,
49
+        LoggerInterface $logger,
50
+        IUserSession $userSession,
51
+        IGroupManager $groupManager,
52
+        IConfig $config,
53
+    ) {
54
+        parent::__construct(
55
+            $appName,
56
+            $request,
57
+            $l10n,
58
+            $userGlobalStoragesService,
59
+            $logger,
60
+            $userSession,
61
+            $groupManager,
62
+            $config
63
+        );
64
+    }
65
+
66
+    /**
67
+     * Get all storage entries
68
+     *
69
+     * @return DataResponse
70
+     */
71
+    #[NoAdminRequired]
72
+    public function index() {
73
+        /** @var UserGlobalStoragesService */
74
+        $service = $this->service;
75
+        $storages = array_map(function ($storage) {
76
+            // remove configuration data, this must be kept private
77
+            $this->sanitizeStorage($storage);
78
+            return $storage->jsonSerialize(true);
79
+        }, $service->getUniqueStorages());
80
+
81
+        return new DataResponse(
82
+            $storages,
83
+            Http::STATUS_OK
84
+        );
85
+    }
86
+
87
+    protected function manipulateStorageConfig(StorageConfig $storage) {
88
+        /** @var AuthMechanism */
89
+        $authMechanism = $storage->getAuthMechanism();
90
+        $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
91
+        /** @var Backend */
92
+        $backend = $storage->getBackend();
93
+        $backend->manipulateStorageConfig($storage, $this->userSession->getUser());
94
+    }
95
+
96
+    /**
97
+     * Get an external storage entry.
98
+     *
99
+     * @param int $id storage id
100
+     * @return DataResponse
101
+     */
102
+    #[NoAdminRequired]
103
+    public function show($id) {
104
+        try {
105
+            $storage = $this->service->getStorage($id);
106
+
107
+            $this->updateStorageStatus($storage);
108
+        } catch (NotFoundException $e) {
109
+            return new DataResponse(
110
+                [
111
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
112
+                ],
113
+                Http::STATUS_NOT_FOUND
114
+            );
115
+        }
116
+
117
+        $this->sanitizeStorage($storage);
118
+
119
+        $data = $storage->jsonSerialize(true);
120
+        $isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
121
+        $data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAL || $isAdmin;
122
+
123
+        return new DataResponse(
124
+            $data,
125
+            Http::STATUS_OK
126
+        );
127
+    }
128
+
129
+    /**
130
+     * Update an external storage entry.
131
+     * Only allows setting user provided backend fields
132
+     *
133
+     * @param int $id storage id
134
+     * @param array $backendOptions backend-specific options
135
+     *
136
+     * @return DataResponse
137
+     */
138
+    #[NoAdminRequired]
139
+    #[PasswordConfirmationRequired(strict: true)]
140
+    public function update(
141
+        int $id,
142
+        $backendOptions,
143
+    ) {
144
+        try {
145
+            $storage = $this->service->getStorage($id);
146
+            $authMechanism = $storage->getAuthMechanism();
147
+            if ($authMechanism instanceof IUserProvided || $authMechanism instanceof  UserGlobalAuth) {
148
+                $authMechanism->saveBackendOptions($this->userSession->getUser(), $id, $backendOptions);
149
+                $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
150
+            } else {
151
+                return new DataResponse(
152
+                    [
153
+                        'message' => $this->l10n->t('Storage with ID "%d" is not editable by non-admins', [$id])
154
+                    ],
155
+                    Http::STATUS_FORBIDDEN
156
+                );
157
+            }
158
+        } catch (NotFoundException $e) {
159
+            return new DataResponse(
160
+                [
161
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
162
+                ],
163
+                Http::STATUS_NOT_FOUND
164
+            );
165
+        }
166
+
167
+        $this->updateStorageStatus($storage);
168
+        $this->sanitizeStorage($storage);
169
+
170
+        return new DataResponse(
171
+            $storage->jsonSerialize(true),
172
+            Http::STATUS_OK
173
+        );
174
+    }
175
+
176
+    /**
177
+     * Remove sensitive data from a StorageConfig before returning it to the user
178
+     *
179
+     * @param StorageConfig $storage
180
+     */
181
+    protected function sanitizeStorage(StorageConfig $storage) {
182
+        $storage->setBackendOptions([]);
183
+        $storage->setMountOptions([]);
184
+
185
+        if ($storage->getAuthMechanism() instanceof IUserProvided) {
186
+            try {
187
+                $storage->getAuthMechanism()->manipulateStorageConfig($storage, $this->userSession->getUser());
188
+            } catch (InsufficientDataForMeaningfulAnswerException $e) {
189
+                // not configured yet
190
+            }
191
+        }
192
+    }
193 193
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/StoragesController.php 2 patches
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -30,288 +30,288 @@
 block discarded – undo
30 30
  * Base class for storages controllers
31 31
  */
32 32
 abstract class StoragesController extends Controller {
33
-	/**
34
-	 * Creates a new storages controller.
35
-	 *
36
-	 * @param string $AppName application name
37
-	 * @param IRequest $request request object
38
-	 * @param IL10N $l10n l10n service
39
-	 * @param StoragesService $storagesService storage service
40
-	 * @param LoggerInterface $logger
41
-	 */
42
-	public function __construct(
43
-		$appName,
44
-		IRequest $request,
45
-		protected IL10N $l10n,
46
-		protected StoragesService $service,
47
-		protected LoggerInterface $logger,
48
-		protected IUserSession $userSession,
49
-		protected IGroupManager $groupManager,
50
-		protected IConfig $config,
51
-	) {
52
-		parent::__construct($appName, $request);
53
-	}
33
+    /**
34
+     * Creates a new storages controller.
35
+     *
36
+     * @param string $AppName application name
37
+     * @param IRequest $request request object
38
+     * @param IL10N $l10n l10n service
39
+     * @param StoragesService $storagesService storage service
40
+     * @param LoggerInterface $logger
41
+     */
42
+    public function __construct(
43
+        $appName,
44
+        IRequest $request,
45
+        protected IL10N $l10n,
46
+        protected StoragesService $service,
47
+        protected LoggerInterface $logger,
48
+        protected IUserSession $userSession,
49
+        protected IGroupManager $groupManager,
50
+        protected IConfig $config,
51
+    ) {
52
+        parent::__construct($appName, $request);
53
+    }
54 54
 
55
-	/**
56
-	 * Create a storage from its parameters
57
-	 *
58
-	 * @param string $mountPoint storage mount point
59
-	 * @param string $backend backend identifier
60
-	 * @param string $authMechanism authentication mechanism identifier
61
-	 * @param array $backendOptions backend-specific options
62
-	 * @param array|null $mountOptions mount-specific options
63
-	 * @param array|null $applicableUsers users for which to mount the storage
64
-	 * @param array|null $applicableGroups groups for which to mount the storage
65
-	 * @param int|null $priority priority
66
-	 *
67
-	 * @return StorageConfig|DataResponse
68
-	 */
69
-	protected function createStorage(
70
-		string $mountPoint,
71
-		string $backend,
72
-		string $authMechanism,
73
-		$backendOptions,
74
-		$mountOptions = null,
75
-		$applicableUsers = null,
76
-		$applicableGroups = null,
77
-		$priority = null,
78
-	) {
79
-		$canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
80
-		if (!$canCreateNewLocalStorage && $backend === 'local') {
81
-			return new DataResponse(
82
-				[
83
-					'message' => $this->l10n->t('Forbidden to manage local mounts')
84
-				],
85
-				Http::STATUS_FORBIDDEN
86
-			);
87
-		}
55
+    /**
56
+     * Create a storage from its parameters
57
+     *
58
+     * @param string $mountPoint storage mount point
59
+     * @param string $backend backend identifier
60
+     * @param string $authMechanism authentication mechanism identifier
61
+     * @param array $backendOptions backend-specific options
62
+     * @param array|null $mountOptions mount-specific options
63
+     * @param array|null $applicableUsers users for which to mount the storage
64
+     * @param array|null $applicableGroups groups for which to mount the storage
65
+     * @param int|null $priority priority
66
+     *
67
+     * @return StorageConfig|DataResponse
68
+     */
69
+    protected function createStorage(
70
+        string $mountPoint,
71
+        string $backend,
72
+        string $authMechanism,
73
+        $backendOptions,
74
+        $mountOptions = null,
75
+        $applicableUsers = null,
76
+        $applicableGroups = null,
77
+        $priority = null,
78
+    ) {
79
+        $canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
80
+        if (!$canCreateNewLocalStorage && $backend === 'local') {
81
+            return new DataResponse(
82
+                [
83
+                    'message' => $this->l10n->t('Forbidden to manage local mounts')
84
+                ],
85
+                Http::STATUS_FORBIDDEN
86
+            );
87
+        }
88 88
 
89
-		try {
90
-			return $this->service->createStorage(
91
-				$mountPoint,
92
-				$backend,
93
-				$authMechanism,
94
-				$backendOptions,
95
-				$mountOptions,
96
-				$applicableUsers,
97
-				$applicableGroups,
98
-				$priority
99
-			);
100
-		} catch (\InvalidArgumentException $e) {
101
-			$this->logger->error($e->getMessage(), ['exception' => $e]);
102
-			return new DataResponse(
103
-				[
104
-					'message' => $this->l10n->t('Invalid backend or authentication mechanism class')
105
-				],
106
-				Http::STATUS_UNPROCESSABLE_ENTITY
107
-			);
108
-		}
109
-	}
89
+        try {
90
+            return $this->service->createStorage(
91
+                $mountPoint,
92
+                $backend,
93
+                $authMechanism,
94
+                $backendOptions,
95
+                $mountOptions,
96
+                $applicableUsers,
97
+                $applicableGroups,
98
+                $priority
99
+            );
100
+        } catch (\InvalidArgumentException $e) {
101
+            $this->logger->error($e->getMessage(), ['exception' => $e]);
102
+            return new DataResponse(
103
+                [
104
+                    'message' => $this->l10n->t('Invalid backend or authentication mechanism class')
105
+                ],
106
+                Http::STATUS_UNPROCESSABLE_ENTITY
107
+            );
108
+        }
109
+    }
110 110
 
111
-	/**
112
-	 * Validate storage config
113
-	 *
114
-	 * @param StorageConfig $storage storage config
115
-	 *1
116
-	 * @return DataResponse|null returns response in case of validation error
117
-	 */
118
-	protected function validate(StorageConfig $storage) {
119
-		$mountPoint = $storage->getMountPoint();
120
-		if ($mountPoint === '') {
121
-			return new DataResponse(
122
-				[
123
-					'message' => $this->l10n->t('Invalid mount point'),
124
-				],
125
-				Http::STATUS_UNPROCESSABLE_ENTITY
126
-			);
127
-		}
111
+    /**
112
+     * Validate storage config
113
+     *
114
+     * @param StorageConfig $storage storage config
115
+     *1
116
+     * @return DataResponse|null returns response in case of validation error
117
+     */
118
+    protected function validate(StorageConfig $storage) {
119
+        $mountPoint = $storage->getMountPoint();
120
+        if ($mountPoint === '') {
121
+            return new DataResponse(
122
+                [
123
+                    'message' => $this->l10n->t('Invalid mount point'),
124
+                ],
125
+                Http::STATUS_UNPROCESSABLE_ENTITY
126
+            );
127
+        }
128 128
 
129
-		if ($storage->getBackendOption('objectstore')) {
130
-			// objectstore must not be sent from client side
131
-			return new DataResponse(
132
-				[
133
-					'message' => $this->l10n->t('Objectstore forbidden'),
134
-				],
135
-				Http::STATUS_UNPROCESSABLE_ENTITY
136
-			);
137
-		}
129
+        if ($storage->getBackendOption('objectstore')) {
130
+            // objectstore must not be sent from client side
131
+            return new DataResponse(
132
+                [
133
+                    'message' => $this->l10n->t('Objectstore forbidden'),
134
+                ],
135
+                Http::STATUS_UNPROCESSABLE_ENTITY
136
+            );
137
+        }
138 138
 
139
-		/** @var Backend */
140
-		$backend = $storage->getBackend();
141
-		/** @var AuthMechanism */
142
-		$authMechanism = $storage->getAuthMechanism();
143
-		if ($backend->checkDependencies()) {
144
-			// invalid backend
145
-			return new DataResponse(
146
-				[
147
-					'message' => $this->l10n->t('Invalid storage backend "%s"', [
148
-						$backend->getIdentifier(),
149
-					]),
150
-				],
151
-				Http::STATUS_UNPROCESSABLE_ENTITY
152
-			);
153
-		}
139
+        /** @var Backend */
140
+        $backend = $storage->getBackend();
141
+        /** @var AuthMechanism */
142
+        $authMechanism = $storage->getAuthMechanism();
143
+        if ($backend->checkDependencies()) {
144
+            // invalid backend
145
+            return new DataResponse(
146
+                [
147
+                    'message' => $this->l10n->t('Invalid storage backend "%s"', [
148
+                        $backend->getIdentifier(),
149
+                    ]),
150
+                ],
151
+                Http::STATUS_UNPROCESSABLE_ENTITY
152
+            );
153
+        }
154 154
 
155
-		if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
156
-			// not permitted to use backend
157
-			return new DataResponse(
158
-				[
159
-					'message' => $this->l10n->t('Not permitted to use backend "%s"', [
160
-						$backend->getIdentifier(),
161
-					]),
162
-				],
163
-				Http::STATUS_UNPROCESSABLE_ENTITY
164
-			);
165
-		}
166
-		if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
167
-			// not permitted to use auth mechanism
168
-			return new DataResponse(
169
-				[
170
-					'message' => $this->l10n->t('Not permitted to use authentication mechanism "%s"', [
171
-						$authMechanism->getIdentifier(),
172
-					]),
173
-				],
174
-				Http::STATUS_UNPROCESSABLE_ENTITY
175
-			);
176
-		}
155
+        if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
156
+            // not permitted to use backend
157
+            return new DataResponse(
158
+                [
159
+                    'message' => $this->l10n->t('Not permitted to use backend "%s"', [
160
+                        $backend->getIdentifier(),
161
+                    ]),
162
+                ],
163
+                Http::STATUS_UNPROCESSABLE_ENTITY
164
+            );
165
+        }
166
+        if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
167
+            // not permitted to use auth mechanism
168
+            return new DataResponse(
169
+                [
170
+                    'message' => $this->l10n->t('Not permitted to use authentication mechanism "%s"', [
171
+                        $authMechanism->getIdentifier(),
172
+                    ]),
173
+                ],
174
+                Http::STATUS_UNPROCESSABLE_ENTITY
175
+            );
176
+        }
177 177
 
178
-		if (!$backend->validateStorage($storage)) {
179
-			// unsatisfied parameters
180
-			return new DataResponse(
181
-				[
182
-					'message' => $this->l10n->t('Unsatisfied backend parameters'),
183
-				],
184
-				Http::STATUS_UNPROCESSABLE_ENTITY
185
-			);
186
-		}
187
-		if (!$authMechanism->validateStorage($storage)) {
188
-			// unsatisfied parameters
189
-			return new DataResponse(
190
-				[
191
-					'message' => $this->l10n->t('Unsatisfied authentication mechanism parameters'),
192
-				],
193
-				Http::STATUS_UNPROCESSABLE_ENTITY
194
-			);
195
-		}
178
+        if (!$backend->validateStorage($storage)) {
179
+            // unsatisfied parameters
180
+            return new DataResponse(
181
+                [
182
+                    'message' => $this->l10n->t('Unsatisfied backend parameters'),
183
+                ],
184
+                Http::STATUS_UNPROCESSABLE_ENTITY
185
+            );
186
+        }
187
+        if (!$authMechanism->validateStorage($storage)) {
188
+            // unsatisfied parameters
189
+            return new DataResponse(
190
+                [
191
+                    'message' => $this->l10n->t('Unsatisfied authentication mechanism parameters'),
192
+                ],
193
+                Http::STATUS_UNPROCESSABLE_ENTITY
194
+            );
195
+        }
196 196
 
197
-		return null;
198
-	}
197
+        return null;
198
+    }
199 199
 
200
-	protected function manipulateStorageConfig(StorageConfig $storage) {
201
-		/** @var AuthMechanism */
202
-		$authMechanism = $storage->getAuthMechanism();
203
-		$authMechanism->manipulateStorageConfig($storage);
204
-		/** @var Backend */
205
-		$backend = $storage->getBackend();
206
-		$backend->manipulateStorageConfig($storage);
207
-	}
200
+    protected function manipulateStorageConfig(StorageConfig $storage) {
201
+        /** @var AuthMechanism */
202
+        $authMechanism = $storage->getAuthMechanism();
203
+        $authMechanism->manipulateStorageConfig($storage);
204
+        /** @var Backend */
205
+        $backend = $storage->getBackend();
206
+        $backend->manipulateStorageConfig($storage);
207
+    }
208 208
 
209
-	/**
210
-	 * Check whether the given storage is available / valid.
211
-	 *
212
-	 * Note that this operation can be time consuming depending
213
-	 * on whether the remote storage is available or not.
214
-	 *
215
-	 * @param StorageConfig $storage storage configuration
216
-	 */
217
-	protected function updateStorageStatus(StorageConfig &$storage) {
218
-		try {
219
-			$this->manipulateStorageConfig($storage);
209
+    /**
210
+     * Check whether the given storage is available / valid.
211
+     *
212
+     * Note that this operation can be time consuming depending
213
+     * on whether the remote storage is available or not.
214
+     *
215
+     * @param StorageConfig $storage storage configuration
216
+     */
217
+    protected function updateStorageStatus(StorageConfig &$storage) {
218
+        try {
219
+            $this->manipulateStorageConfig($storage);
220 220
 
221
-			/** @var Backend */
222
-			$backend = $storage->getBackend();
223
-			// update status (can be time-consuming)
224
-			$storage->setStatus(
225
-				MountConfig::getBackendStatus(
226
-					$backend->getStorageClass(),
227
-					$storage->getBackendOptions(),
228
-				)
229
-			);
230
-		} catch (InsufficientDataForMeaningfulAnswerException $e) {
231
-			$status = $e->getCode() ?: StorageNotAvailableException::STATUS_INDETERMINATE;
232
-			$storage->setStatus(
233
-				(int)$status,
234
-				$this->l10n->t('Insufficient data: %s', [$e->getMessage()])
235
-			);
236
-		} catch (StorageNotAvailableException $e) {
237
-			$storage->setStatus(
238
-				(int)$e->getCode(),
239
-				$e->getMessage(),
240
-			);
241
-		} catch (\Exception $e) {
242
-			// FIXME: convert storage exceptions to StorageNotAvailableException
243
-			$storage->setStatus(
244
-				StorageNotAvailableException::STATUS_ERROR,
245
-				get_class($e) . ': ' . $e->getMessage()
246
-			);
247
-		}
248
-	}
221
+            /** @var Backend */
222
+            $backend = $storage->getBackend();
223
+            // update status (can be time-consuming)
224
+            $storage->setStatus(
225
+                MountConfig::getBackendStatus(
226
+                    $backend->getStorageClass(),
227
+                    $storage->getBackendOptions(),
228
+                )
229
+            );
230
+        } catch (InsufficientDataForMeaningfulAnswerException $e) {
231
+            $status = $e->getCode() ?: StorageNotAvailableException::STATUS_INDETERMINATE;
232
+            $storage->setStatus(
233
+                (int)$status,
234
+                $this->l10n->t('Insufficient data: %s', [$e->getMessage()])
235
+            );
236
+        } catch (StorageNotAvailableException $e) {
237
+            $storage->setStatus(
238
+                (int)$e->getCode(),
239
+                $e->getMessage(),
240
+            );
241
+        } catch (\Exception $e) {
242
+            // FIXME: convert storage exceptions to StorageNotAvailableException
243
+            $storage->setStatus(
244
+                StorageNotAvailableException::STATUS_ERROR,
245
+                get_class($e) . ': ' . $e->getMessage()
246
+            );
247
+        }
248
+    }
249 249
 
250
-	/**
251
-	 * Get all storage entries
252
-	 *
253
-	 * @return DataResponse
254
-	 */
255
-	public function index() {
256
-		$storages = array_map(static fn ($storage) => $storage->jsonSerialize(true), $this->service->getStorages());
250
+    /**
251
+     * Get all storage entries
252
+     *
253
+     * @return DataResponse
254
+     */
255
+    public function index() {
256
+        $storages = array_map(static fn ($storage) => $storage->jsonSerialize(true), $this->service->getStorages());
257 257
 
258
-		return new DataResponse(
259
-			$storages,
260
-			Http::STATUS_OK
261
-		);
262
-	}
258
+        return new DataResponse(
259
+            $storages,
260
+            Http::STATUS_OK
261
+        );
262
+    }
263 263
 
264
-	/**
265
-	 * Get an external storage entry.
266
-	 *
267
-	 * @param int $id storage id
268
-	 *
269
-	 * @return DataResponse
270
-	 */
271
-	public function show(int $id) {
272
-		try {
273
-			$storage = $this->service->getStorage($id);
264
+    /**
265
+     * Get an external storage entry.
266
+     *
267
+     * @param int $id storage id
268
+     *
269
+     * @return DataResponse
270
+     */
271
+    public function show(int $id) {
272
+        try {
273
+            $storage = $this->service->getStorage($id);
274 274
 
275
-			$this->updateStorageStatus($storage);
276
-		} catch (NotFoundException $e) {
277
-			return new DataResponse(
278
-				[
279
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
280
-				],
281
-				Http::STATUS_NOT_FOUND
282
-			);
283
-		}
275
+            $this->updateStorageStatus($storage);
276
+        } catch (NotFoundException $e) {
277
+            return new DataResponse(
278
+                [
279
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
280
+                ],
281
+                Http::STATUS_NOT_FOUND
282
+            );
283
+        }
284 284
 
285
-		$data = $storage->jsonSerialize(true);
286
-		$isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
287
-		$data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAL || $isAdmin;
285
+        $data = $storage->jsonSerialize(true);
286
+        $isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
287
+        $data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAL || $isAdmin;
288 288
 
289
-		return new DataResponse(
290
-			$data,
291
-			Http::STATUS_OK
292
-		);
293
-	}
289
+        return new DataResponse(
290
+            $data,
291
+            Http::STATUS_OK
292
+        );
293
+    }
294 294
 
295
-	/**
296
-	 * Deletes the storage with the given id.
297
-	 *
298
-	 * @param int $id storage id
299
-	 *
300
-	 * @return DataResponse
301
-	 */
302
-	#[PasswordConfirmationRequired(strict: true)]
303
-	public function destroy(int $id) {
304
-		try {
305
-			$this->service->removeStorage($id);
306
-		} catch (NotFoundException $e) {
307
-			return new DataResponse(
308
-				[
309
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
310
-				],
311
-				Http::STATUS_NOT_FOUND
312
-			);
313
-		}
295
+    /**
296
+     * Deletes the storage with the given id.
297
+     *
298
+     * @param int $id storage id
299
+     *
300
+     * @return DataResponse
301
+     */
302
+    #[PasswordConfirmationRequired(strict: true)]
303
+    public function destroy(int $id) {
304
+        try {
305
+            $this->service->removeStorage($id);
306
+        } catch (NotFoundException $e) {
307
+            return new DataResponse(
308
+                [
309
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
310
+                ],
311
+                Http::STATUS_NOT_FOUND
312
+            );
313
+        }
314 314
 
315
-		return new DataResponse([], Http::STATUS_NO_CONTENT);
316
-	}
315
+        return new DataResponse([], Http::STATUS_NO_CONTENT);
316
+    }
317 317
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 	 *
215 215
 	 * @param StorageConfig $storage storage configuration
216 216
 	 */
217
-	protected function updateStorageStatus(StorageConfig &$storage) {
217
+	protected function updateStorageStatus(StorageConfig & $storage) {
218 218
 		try {
219 219
 			$this->manipulateStorageConfig($storage);
220 220
 
@@ -230,19 +230,19 @@  discard block
 block discarded – undo
230 230
 		} catch (InsufficientDataForMeaningfulAnswerException $e) {
231 231
 			$status = $e->getCode() ?: StorageNotAvailableException::STATUS_INDETERMINATE;
232 232
 			$storage->setStatus(
233
-				(int)$status,
233
+				(int) $status,
234 234
 				$this->l10n->t('Insufficient data: %s', [$e->getMessage()])
235 235
 			);
236 236
 		} catch (StorageNotAvailableException $e) {
237 237
 			$storage->setStatus(
238
-				(int)$e->getCode(),
238
+				(int) $e->getCode(),
239 239
 				$e->getMessage(),
240 240
 			);
241 241
 		} catch (\Exception $e) {
242 242
 			// FIXME: convert storage exceptions to StorageNotAvailableException
243 243
 			$storage->setStatus(
244 244
 				StorageNotAvailableException::STATUS_ERROR,
245
-				get_class($e) . ': ' . $e->getMessage()
245
+				get_class($e).': '.$e->getMessage()
246 246
 			);
247 247
 		}
248 248
 	}
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/UserStoragesController.php 1 patch
Indentation   +185 added lines, -185 removed lines patch added patch discarded remove patch
@@ -27,189 +27,189 @@
 block discarded – undo
27 27
  * User storages controller
28 28
  */
29 29
 class UserStoragesController extends StoragesController {
30
-	/**
31
-	 * Creates a new user storages controller.
32
-	 *
33
-	 * @param string $AppName application name
34
-	 * @param IRequest $request request object
35
-	 * @param IL10N $l10n l10n service
36
-	 * @param UserStoragesService $userStoragesService storage service
37
-	 * @param LoggerInterface $logger
38
-	 * @param IUserSession $userSession
39
-	 * @param IGroupManager $groupManager
40
-	 */
41
-	public function __construct(
42
-		$appName,
43
-		IRequest $request,
44
-		IL10N $l10n,
45
-		UserStoragesService $userStoragesService,
46
-		LoggerInterface $logger,
47
-		IUserSession $userSession,
48
-		IGroupManager $groupManager,
49
-		IConfig $config,
50
-	) {
51
-		parent::__construct(
52
-			$appName,
53
-			$request,
54
-			$l10n,
55
-			$userStoragesService,
56
-			$logger,
57
-			$userSession,
58
-			$groupManager,
59
-			$config
60
-		);
61
-	}
62
-
63
-	protected function manipulateStorageConfig(StorageConfig $storage) {
64
-		/** @var AuthMechanism */
65
-		$authMechanism = $storage->getAuthMechanism();
66
-		$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
67
-		/** @var Backend */
68
-		$backend = $storage->getBackend();
69
-		$backend->manipulateStorageConfig($storage, $this->userSession->getUser());
70
-	}
71
-
72
-	/**
73
-	 * Get all storage entries
74
-	 *
75
-	 * @return DataResponse
76
-	 */
77
-	#[NoAdminRequired]
78
-	public function index() {
79
-		return parent::index();
80
-	}
81
-
82
-	/**
83
-	 * Return storage
84
-	 *
85
-	 * {@inheritdoc}
86
-	 */
87
-	#[NoAdminRequired]
88
-	public function show(int $id) {
89
-		return parent::show($id);
90
-	}
91
-
92
-	/**
93
-	 * Create an external storage entry.
94
-	 *
95
-	 * @param string $mountPoint storage mount point
96
-	 * @param string $backend backend identifier
97
-	 * @param string $authMechanism authentication mechanism identifier
98
-	 * @param array $backendOptions backend-specific options
99
-	 * @param array $mountOptions backend-specific mount options
100
-	 *
101
-	 * @return DataResponse
102
-	 */
103
-	#[NoAdminRequired]
104
-	#[PasswordConfirmationRequired(strict: true)]
105
-	public function create(
106
-		string $mountPoint,
107
-		string $backend,
108
-		string $authMechanism,
109
-		$backendOptions,
110
-		$mountOptions,
111
-	) {
112
-		$canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
113
-		if (!$canCreateNewLocalStorage && $backend === 'local') {
114
-			return new DataResponse(
115
-				[
116
-					'message' => $this->l10n->t('Forbidden to manage local mounts')
117
-				],
118
-				Http::STATUS_FORBIDDEN
119
-			);
120
-		}
121
-		$newStorage = $this->createStorage(
122
-			$mountPoint,
123
-			$backend,
124
-			$authMechanism,
125
-			$backendOptions,
126
-			$mountOptions
127
-		);
128
-		if ($newStorage instanceof DataResponse) {
129
-			return $newStorage;
130
-		}
131
-
132
-		$response = $this->validate($newStorage);
133
-		if (!empty($response)) {
134
-			return $response;
135
-		}
136
-
137
-		$newStorage = $this->service->addStorage($newStorage);
138
-		$this->updateStorageStatus($newStorage);
139
-
140
-		$newStorage->setType(StorageConfig::MOUNT_TYPE_PERSONAL);
141
-		return new DataResponse(
142
-			$newStorage->jsonSerialize(true),
143
-			Http::STATUS_CREATED
144
-		);
145
-	}
146
-
147
-	/**
148
-	 * Update an external storage entry.
149
-	 *
150
-	 * @param int $id storage id
151
-	 * @param string $mountPoint storage mount point
152
-	 * @param string $backend backend identifier
153
-	 * @param string $authMechanism authentication mechanism identifier
154
-	 * @param array $backendOptions backend-specific options
155
-	 * @param array $mountOptions backend-specific mount options
156
-	 *
157
-	 * @return DataResponse
158
-	 */
159
-	#[NoAdminRequired]
160
-	#[PasswordConfirmationRequired(strict: true)]
161
-	public function update(
162
-		int $id,
163
-		string $mountPoint,
164
-		string $backend,
165
-		string $authMechanism,
166
-		$backendOptions,
167
-		$mountOptions,
168
-	) {
169
-		$storage = $this->createStorage(
170
-			$mountPoint,
171
-			$backend,
172
-			$authMechanism,
173
-			$backendOptions,
174
-			$mountOptions
175
-		);
176
-		if ($storage instanceof DataResponse) {
177
-			return $storage;
178
-		}
179
-		$storage->setId($id);
180
-
181
-		$response = $this->validate($storage);
182
-		if (!empty($response)) {
183
-			return $response;
184
-		}
185
-
186
-		try {
187
-			$storage = $this->service->updateStorage($storage);
188
-		} catch (NotFoundException $e) {
189
-			return new DataResponse(
190
-				[
191
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
192
-				],
193
-				Http::STATUS_NOT_FOUND
194
-			);
195
-		}
196
-
197
-		$this->updateStorageStatus($storage);
198
-
199
-		return new DataResponse(
200
-			$storage->jsonSerialize(true),
201
-			Http::STATUS_OK
202
-		);
203
-	}
204
-
205
-	/**
206
-	 * Delete storage
207
-	 *
208
-	 * {@inheritdoc}
209
-	 */
210
-	#[NoAdminRequired]
211
-	#[PasswordConfirmationRequired(strict: true)]
212
-	public function destroy(int $id) {
213
-		return parent::destroy($id);
214
-	}
30
+    /**
31
+     * Creates a new user storages controller.
32
+     *
33
+     * @param string $AppName application name
34
+     * @param IRequest $request request object
35
+     * @param IL10N $l10n l10n service
36
+     * @param UserStoragesService $userStoragesService storage service
37
+     * @param LoggerInterface $logger
38
+     * @param IUserSession $userSession
39
+     * @param IGroupManager $groupManager
40
+     */
41
+    public function __construct(
42
+        $appName,
43
+        IRequest $request,
44
+        IL10N $l10n,
45
+        UserStoragesService $userStoragesService,
46
+        LoggerInterface $logger,
47
+        IUserSession $userSession,
48
+        IGroupManager $groupManager,
49
+        IConfig $config,
50
+    ) {
51
+        parent::__construct(
52
+            $appName,
53
+            $request,
54
+            $l10n,
55
+            $userStoragesService,
56
+            $logger,
57
+            $userSession,
58
+            $groupManager,
59
+            $config
60
+        );
61
+    }
62
+
63
+    protected function manipulateStorageConfig(StorageConfig $storage) {
64
+        /** @var AuthMechanism */
65
+        $authMechanism = $storage->getAuthMechanism();
66
+        $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
67
+        /** @var Backend */
68
+        $backend = $storage->getBackend();
69
+        $backend->manipulateStorageConfig($storage, $this->userSession->getUser());
70
+    }
71
+
72
+    /**
73
+     * Get all storage entries
74
+     *
75
+     * @return DataResponse
76
+     */
77
+    #[NoAdminRequired]
78
+    public function index() {
79
+        return parent::index();
80
+    }
81
+
82
+    /**
83
+     * Return storage
84
+     *
85
+     * {@inheritdoc}
86
+     */
87
+    #[NoAdminRequired]
88
+    public function show(int $id) {
89
+        return parent::show($id);
90
+    }
91
+
92
+    /**
93
+     * Create an external storage entry.
94
+     *
95
+     * @param string $mountPoint storage mount point
96
+     * @param string $backend backend identifier
97
+     * @param string $authMechanism authentication mechanism identifier
98
+     * @param array $backendOptions backend-specific options
99
+     * @param array $mountOptions backend-specific mount options
100
+     *
101
+     * @return DataResponse
102
+     */
103
+    #[NoAdminRequired]
104
+    #[PasswordConfirmationRequired(strict: true)]
105
+    public function create(
106
+        string $mountPoint,
107
+        string $backend,
108
+        string $authMechanism,
109
+        $backendOptions,
110
+        $mountOptions,
111
+    ) {
112
+        $canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
113
+        if (!$canCreateNewLocalStorage && $backend === 'local') {
114
+            return new DataResponse(
115
+                [
116
+                    'message' => $this->l10n->t('Forbidden to manage local mounts')
117
+                ],
118
+                Http::STATUS_FORBIDDEN
119
+            );
120
+        }
121
+        $newStorage = $this->createStorage(
122
+            $mountPoint,
123
+            $backend,
124
+            $authMechanism,
125
+            $backendOptions,
126
+            $mountOptions
127
+        );
128
+        if ($newStorage instanceof DataResponse) {
129
+            return $newStorage;
130
+        }
131
+
132
+        $response = $this->validate($newStorage);
133
+        if (!empty($response)) {
134
+            return $response;
135
+        }
136
+
137
+        $newStorage = $this->service->addStorage($newStorage);
138
+        $this->updateStorageStatus($newStorage);
139
+
140
+        $newStorage->setType(StorageConfig::MOUNT_TYPE_PERSONAL);
141
+        return new DataResponse(
142
+            $newStorage->jsonSerialize(true),
143
+            Http::STATUS_CREATED
144
+        );
145
+    }
146
+
147
+    /**
148
+     * Update an external storage entry.
149
+     *
150
+     * @param int $id storage id
151
+     * @param string $mountPoint storage mount point
152
+     * @param string $backend backend identifier
153
+     * @param string $authMechanism authentication mechanism identifier
154
+     * @param array $backendOptions backend-specific options
155
+     * @param array $mountOptions backend-specific mount options
156
+     *
157
+     * @return DataResponse
158
+     */
159
+    #[NoAdminRequired]
160
+    #[PasswordConfirmationRequired(strict: true)]
161
+    public function update(
162
+        int $id,
163
+        string $mountPoint,
164
+        string $backend,
165
+        string $authMechanism,
166
+        $backendOptions,
167
+        $mountOptions,
168
+    ) {
169
+        $storage = $this->createStorage(
170
+            $mountPoint,
171
+            $backend,
172
+            $authMechanism,
173
+            $backendOptions,
174
+            $mountOptions
175
+        );
176
+        if ($storage instanceof DataResponse) {
177
+            return $storage;
178
+        }
179
+        $storage->setId($id);
180
+
181
+        $response = $this->validate($storage);
182
+        if (!empty($response)) {
183
+            return $response;
184
+        }
185
+
186
+        try {
187
+            $storage = $this->service->updateStorage($storage);
188
+        } catch (NotFoundException $e) {
189
+            return new DataResponse(
190
+                [
191
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
192
+                ],
193
+                Http::STATUS_NOT_FOUND
194
+            );
195
+        }
196
+
197
+        $this->updateStorageStatus($storage);
198
+
199
+        return new DataResponse(
200
+            $storage->jsonSerialize(true),
201
+            Http::STATUS_OK
202
+        );
203
+    }
204
+
205
+    /**
206
+     * Delete storage
207
+     *
208
+     * {@inheritdoc}
209
+     */
210
+    #[NoAdminRequired]
211
+    #[PasswordConfirmationRequired(strict: true)]
212
+    public function destroy(int $id) {
213
+        return parent::destroy($id);
214
+    }
215 215
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/AjaxController.php 1 patch
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -21,113 +21,113 @@
 block discarded – undo
21 21
 use OCP\IUserSession;
22 22
 
23 23
 class AjaxController extends Controller {
24
-	/**
25
-	 * @param string $appName
26
-	 * @param IRequest $request
27
-	 * @param RSA $rsaMechanism
28
-	 * @param GlobalAuth $globalAuth
29
-	 * @param IUserSession $userSession
30
-	 * @param IGroupManager $groupManager
31
-	 */
32
-	public function __construct(
33
-		$appName,
34
-		IRequest $request,
35
-		private RSA $rsaMechanism,
36
-		private GlobalAuth $globalAuth,
37
-		private IUserSession $userSession,
38
-		private IGroupManager $groupManager,
39
-		private IUserManager $userManager,
40
-		private IL10N $l10n,
41
-	) {
42
-		parent::__construct($appName, $request);
43
-	}
24
+    /**
25
+     * @param string $appName
26
+     * @param IRequest $request
27
+     * @param RSA $rsaMechanism
28
+     * @param GlobalAuth $globalAuth
29
+     * @param IUserSession $userSession
30
+     * @param IGroupManager $groupManager
31
+     */
32
+    public function __construct(
33
+        $appName,
34
+        IRequest $request,
35
+        private RSA $rsaMechanism,
36
+        private GlobalAuth $globalAuth,
37
+        private IUserSession $userSession,
38
+        private IGroupManager $groupManager,
39
+        private IUserManager $userManager,
40
+        private IL10N $l10n,
41
+    ) {
42
+        parent::__construct($appName, $request);
43
+    }
44 44
 
45
-	/**
46
-	 * Returns a list of users and groups that match the given pattern.
47
-	 * Used for user and group picker in the admin settings.
48
-	 *
49
-	 * @param string $pattern The search pattern
50
-	 * @param int|null $limit The maximum number of results to return
51
-	 * @param int|null $offset The offset from which to start returning results
52
-	 * @return JSONResponse
53
-	 */
54
-	public function getApplicableEntities(string $pattern = '', ?int $limit = null, ?int $offset = null): JSONResponse {
55
-		$groups = [];
56
-		foreach ($this->groupManager->search($pattern, $limit, $offset) as $group) {
57
-			$groups[$group->getGID()] = $group->getDisplayName();
58
-		}
45
+    /**
46
+     * Returns a list of users and groups that match the given pattern.
47
+     * Used for user and group picker in the admin settings.
48
+     *
49
+     * @param string $pattern The search pattern
50
+     * @param int|null $limit The maximum number of results to return
51
+     * @param int|null $offset The offset from which to start returning results
52
+     * @return JSONResponse
53
+     */
54
+    public function getApplicableEntities(string $pattern = '', ?int $limit = null, ?int $offset = null): JSONResponse {
55
+        $groups = [];
56
+        foreach ($this->groupManager->search($pattern, $limit, $offset) as $group) {
57
+            $groups[$group->getGID()] = $group->getDisplayName();
58
+        }
59 59
 
60
-		$users = [];
61
-		foreach ($this->userManager->searchDisplayName($pattern, $limit, $offset) as $user) {
62
-			$users[$user->getUID()] = $user->getDisplayName();
63
-		}
60
+        $users = [];
61
+        foreach ($this->userManager->searchDisplayName($pattern, $limit, $offset) as $user) {
62
+            $users[$user->getUID()] = $user->getDisplayName();
63
+        }
64 64
 
65
-		$results = ['groups' => $groups, 'users' => $users];
66
-		return new JSONResponse($results);
67
-	}
65
+        $results = ['groups' => $groups, 'users' => $users];
66
+        return new JSONResponse($results);
67
+    }
68 68
 
69
-	/**
70
-	 * @param int $keyLength
71
-	 * @return array
72
-	 */
73
-	private function generateSshKeys($keyLength) {
74
-		$key = $this->rsaMechanism->createKey($keyLength);
75
-		// Replace the placeholder label with a more meaningful one
76
-		$key['publickey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
69
+    /**
70
+     * @param int $keyLength
71
+     * @return array
72
+     */
73
+    private function generateSshKeys($keyLength) {
74
+        $key = $this->rsaMechanism->createKey($keyLength);
75
+        // Replace the placeholder label with a more meaningful one
76
+        $key['publickey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
77 77
 
78
-		return $key;
79
-	}
78
+        return $key;
79
+    }
80 80
 
81
-	/**
82
-	 * Generates an SSH public/private key pair.
83
-	 *
84
-	 * @param int $keyLength
85
-	 */
86
-	#[NoAdminRequired]
87
-	public function getSshKeys($keyLength = 1024) {
88
-		$key = $this->generateSshKeys($keyLength);
89
-		return new JSONResponse([
90
-			'data' => [
91
-				'private_key' => $key['privatekey'],
92
-				'public_key' => $key['publickey']
93
-			],
94
-			'status' => 'success',
95
-		]);
96
-	}
81
+    /**
82
+     * Generates an SSH public/private key pair.
83
+     *
84
+     * @param int $keyLength
85
+     */
86
+    #[NoAdminRequired]
87
+    public function getSshKeys($keyLength = 1024) {
88
+        $key = $this->generateSshKeys($keyLength);
89
+        return new JSONResponse([
90
+            'data' => [
91
+                'private_key' => $key['privatekey'],
92
+                'public_key' => $key['publickey']
93
+            ],
94
+            'status' => 'success',
95
+        ]);
96
+    }
97 97
 
98
-	/**
99
-	 * @param string $uid
100
-	 * @param string $user
101
-	 * @param string $password
102
-	 * @return JSONResponse
103
-	 */
104
-	#[NoAdminRequired]
105
-	#[PasswordConfirmationRequired(strict: true)]
106
-	public function saveGlobalCredentials($uid, $user, $password): JSONResponse {
107
-		$currentUser = $this->userSession->getUser();
108
-		if ($currentUser === null) {
109
-			return new JSONResponse([
110
-				'status' => 'error',
111
-				'message' => $this->l10n->t('You are not logged in'),
112
-			], Http::STATUS_UNAUTHORIZED);
113
-		}
98
+    /**
99
+     * @param string $uid
100
+     * @param string $user
101
+     * @param string $password
102
+     * @return JSONResponse
103
+     */
104
+    #[NoAdminRequired]
105
+    #[PasswordConfirmationRequired(strict: true)]
106
+    public function saveGlobalCredentials($uid, $user, $password): JSONResponse {
107
+        $currentUser = $this->userSession->getUser();
108
+        if ($currentUser === null) {
109
+            return new JSONResponse([
110
+                'status' => 'error',
111
+                'message' => $this->l10n->t('You are not logged in'),
112
+            ], Http::STATUS_UNAUTHORIZED);
113
+        }
114 114
 
115
-		// Non-admins can only edit their own credentials
116
-		// Admin can edit global credentials
117
-		$allowedToEdit = $uid === ''
118
-			? $this->groupManager->isAdmin($currentUser->getUID())
119
-			: $currentUser->getUID() === $uid;
115
+        // Non-admins can only edit their own credentials
116
+        // Admin can edit global credentials
117
+        $allowedToEdit = $uid === ''
118
+            ? $this->groupManager->isAdmin($currentUser->getUID())
119
+            : $currentUser->getUID() === $uid;
120 120
 
121
-		if ($allowedToEdit) {
122
-			$this->globalAuth->saveAuth($uid, $user, $password);
123
-			return new JSONResponse([
124
-				'status' => 'success',
125
-			]);
126
-		}
121
+        if ($allowedToEdit) {
122
+            $this->globalAuth->saveAuth($uid, $user, $password);
123
+            return new JSONResponse([
124
+                'status' => 'success',
125
+            ]);
126
+        }
127 127
 
128
-		return new JSONResponse([
129
-			'status' => 'success',
130
-			'message' => $this->l10n->t('Permission denied'),
131
-		], Http::STATUS_FORBIDDEN);
132
-	}
128
+        return new JSONResponse([
129
+            'status' => 'success',
130
+            'message' => $this->l10n->t('Permission denied'),
131
+        ], Http::STATUS_FORBIDDEN);
132
+    }
133 133
 }
Please login to merge, or discard this patch.