Completed
Pull Request — master (#32303)
by Victor
11:31
created

OcmController::createShare()   D

Complexity

Conditions 15
Paths 67

Size

Total Lines 115

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
nc 67
nop 11
dl 0
loc 115
rs 4.7333
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * @author Viktar Dubiniuk <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2018, ownCloud GmbH
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\FederatedFileSharing\Controller;
23
24
use OCA\FederatedFileSharing\Address;
25
use OCA\FederatedFileSharing\AddressHandler;
26
use OCA\FederatedFileSharing\FederatedShareProvider;
27
use OCA\FederatedFileSharing\Ocm\Notification\FileNotification;
28
use OCP\AppFramework\Http\JSONResponse;
29
use OCA\FederatedFileSharing\Exception\InvalidShareException;
30
use OCA\FederatedFileSharing\Exception\NotSupportedException;
31
use OCA\FederatedFileSharing\FedShareManager;
32
use OCP\AppFramework\Controller;
33
use OCP\AppFramework\Http;
34
use OCP\ILogger;
35
use OCP\IRequest;
36
use OCP\IURLGenerator;
37
use OCP\IUserManager;
38
use OCP\Share;
39
use OCP\Share\IShare;
40
41
/**
42
 * Class OcmController
43
 *
44
 * @package OCA\FederatedFileSharing\Controller
45
 */
46
class OcmController extends Controller {
47
	const API_VERSION = '1.0-proposal1';
48
49
	/**
50
	 * @var FederatedShareProvider
51
	 */
52
	private $federatedShareProvider;
53
54
	/**
55
	 * @var IURLGenerator
56
	 */
57
	protected $urlGenerator;
58
59
	/**
60
	 * @var IUserManager
61
	 */
62
	protected $userManager;
63
64
	/**
65
	 * @var AddressHandler
66
	 */
67
	protected $addressHandler;
68
69
	/**
70
	 * @var FedShareManager
71
	 */
72
	protected $fedShareManager;
73
74
	/**
75
	 * @var ILogger
76
	 */
77
	protected $logger;
78
79
	/**
80
	 * OcmController constructor.
81
	 *
82
	 * @param string $appName
83
	 * @param IRequest $request
84
	 * @param FederatedShareProvider $federatedShareProvider
85
	 * @param IURLGenerator $urlGenerator
86
	 * @param IUserManager $userManager
87
	 * @param AddressHandler $addressHandler
88
	 * @param FedShareManager $fedShareManager
89
	 * @param ILogger $logger
90
	 */
91 View Code Duplication
	public function __construct($appName,
92
									IRequest $request,
93
									FederatedShareProvider $federatedShareProvider,
94
									IURLGenerator $urlGenerator,
95
									IUserManager $userManager,
96
									AddressHandler $addressHandler,
97
									FedShareManager $fedShareManager,
98
									ILogger $logger
99
	) {
100
		parent::__construct($appName, $request);
101
102
		$this->federatedShareProvider = $federatedShareProvider;
103
		$this->urlGenerator = $urlGenerator;
104
		$this->userManager = $userManager;
105
		$this->addressHandler = $addressHandler;
106
		$this->fedShareManager = $fedShareManager;
107
		$this->logger = $logger;
108
	}
109
110
	/**
111
	 * @NoCSRFRequired
112
	 * @PublicPage
113
	 *
114
	 * EndPoint discovery
115
	 * Responds to /ocm-provider/ requests
116
	 *
117
	 * @return array
118
	 */
119
	public function discovery() {
120
		return [
121
			'enabled' => true,
122
			'apiVersion' => self::API_VERSION,
123
			'endPoint' => $this->urlGenerator->linkToRouteAbsolute(
124
				"{$this->appName}.ocm.index"
125
			),
126
			'shareTypes' => [
127
				'name' => FileNotification::RESOURCE_TYPE_FILE,
128
				'protocols' => $this->getProtocols()
129
			]
130
		];
131
	}
132
133
	/**
134
	 * @NoCSRFRequired
135
	 * @PublicPage
136
	 *
137
	 *
138
	 *
139
	 * @param string $shareWith identifier of the user or group
140
	 * 							to share the resource with
141
	 * @param string $name name of the shared resource
142
	 * @param string $description share description (optional)
143
	 * @param string $providerId Identifier of the resource at the provider side
144
	 * @param string $owner identifier of the user that owns the resource
145
	 * @param string $ownerDisplayName display name of the owner
146
	 * @param string $sender Provider specific identifier of the user that wants
147
	 *							to share the resource
148
	 * @param string $senderDisplayName Display name of the user that wants
149
	 * 									to share the resource
150
	 * @param string $shareType Share type ('user' is supported atm)
151
	 * @param string $resourceType only 'file' is supported atm
152
	 * @param array $protocol
153
	 * 		[
154
	 * 			'name' => (string) protocol name. Only 'webdav' is supported atm,
155
	 * 			'options' => [
156
	 * 				protocol specific options
157
	 * 				only `webdav` options are supported atm
158
	 * 				e.g. `uri`,	`access_token`, `password`, `permissions` etc.
159
	 *
160
	 * 				For backward compatibility the webdav protocol will use
161
	 * 				the 'sharedSecret" as username and password
162
	 * 			]
163
	 *
164
	 * @return JSONResponse
165
	 */
166
	public function createShare($shareWith,
167
								$name,
168
								$description,
0 ignored issues
show
Unused Code introduced by
The parameter $description is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
169
								$providerId,
170
								$owner,
171
								$ownerDisplayName,
172
								$sender,
173
								$senderDisplayName,
174
								$shareType,
175
								$resourceType,
176
								$protocol
177
178
	) {
179
		try {
180
			$hasMissingParams = $this->hasNull(
181
				[$shareWith, $name, $providerId, $owner, $shareType, $resourceType]
182
			);
183
			if ($hasMissingParams
184
				|| !\is_array($protocol)
185
				|| !isset($protocol['name'])
186
				|| !isset($protocol['options'])
187
				|| !\is_array($protocol['options'])
188
				|| !isset($protocol['options']['sharedSecret'])
189
			) {
190
				throw new InvalidShareException(
191
					'server can not add remote share, missing parameter'
192
				);
193
			}
194
			if (!\OCP\Util::isValidFileName($name)) {
195
				throw new InvalidShareException(
196
					'The mountpoint name contains invalid characters.'
197
				);
198
			}
199
200
			$shareWithAddress = new Address($shareWith);
201
			$localShareWith = $shareWithAddress->getUserId();
202
203
			// FIXME this should be a method in the user management instead
204
			$this->logger->debug(
205
				"shareWith before, $localShareWith",
206
				['app' => $this->appName]
207
			);
208
			\OCP\Util::emitHook(
209
				'\OCA\Files_Sharing\API\Server2Server',
210
				'preLoginNameUsedAsUserName',
211
				['uid' => &$localShareWith]
212
			);
213
			$this->logger->debug(
214
				"shareWith after, $localShareWith",
215
				['app' => $this->appName]
216
			);
217
218
			if ($this->isSupportedProtocol($protocol['name']) === false) {
219
				return new JSONResponse(
220
					['message' => "Protocol {$protocol['name']} is not supported"],
221
					Http::STATUS_NOT_IMPLEMENTED
222
				);
223
			}
224
225
			if ($this->isSupportedShareType($shareType) === false) {
226
				return new JSONResponse(
227
					['message' => "ShareType {$shareType} is not supported"],
228
					Http::STATUS_NOT_IMPLEMENTED
229
				);
230
			}
231
232
			if ($this->isSupportedResourceType($resourceType) === false) {
233
				return new JSONResponse(
234
					['message' => "ResourceType {$resourceType} is not supported"],
235
					Http::STATUS_NOT_IMPLEMENTED
236
				);
237
			}
238
239
			if (!$this->userManager->userExists($localShareWith)) {
240
				throw new InvalidShareException("User $localShareWith does not exist");
241
			}
242
243
			$ownerAddress = new Address($owner, $ownerDisplayName);
244
			$sharedByAddress = new Address($sender, $senderDisplayName);
245
246
			$this->fedShareManager->createShare(
247
				$ownerAddress,
248
				$sharedByAddress,
249
				$localShareWith,
250
				$providerId,
251
				$name,
252
				$protocol['options']['sharedSecret']
253
			);
254
		} catch (InvalidShareException $e) {
255
			return new JSONResponse(
256
				['message' => $e->getMessage()],
257
				Http::STATUS_BAD_REQUEST
258
			);
259
		} catch (NotSupportedException $e) {
260
			return new JSONResponse(
261
				['message' => 'Server does not support federated cloud sharing'],
262
				Http::STATUS_SERVICE_UNAVAILABLE
263
			);
264
		} catch (\Exception $e) {
265
			$this->logger->error(
266
				"server can not add remote share, {$e->getMessage()}",
267
				['app' => 'federatefilesharing']
268
			);
269
			return new JSONResponse(
270
				[
271
					'message' => "internal server error, was not able to add share from {$ownerAddress->getHostName()}"
0 ignored issues
show
Bug introduced by
The variable $ownerAddress does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
272
				],
273
				Http::STATUS_INTERNAL_SERVER_ERROR
274
			);
275
		}
276
		return new JSONResponse(
277
			[],
278
			Http::STATUS_CREATED
279
		);
280
	}
281
282
	/**
283
	 * @param string $notificationType notification type (SHARE_REMOVED, etc)
284
	 * @param string $resourceType only 'file' is supported atm
285
	 * @param string $providerId Identifier of the resource at the provider side
286
	 * @param array $notification
287
	 * 		[
288
	 * 			optional additional parameters, depending on the notification
289
	 * 				and the resource type
290
	 * 		]
291
	 *
292
	 * @return JSONResponse
293
	 */
294
	public function processNotification($notificationType,
295
										$resourceType,
296
										$providerId,
297
										$notification
298
	) {
299
		try {
300
			$hasMissingParams = $this->hasNull(
301
				[$notificationType, $resourceType, $providerId]
302
			);
303
			if ($hasMissingParams || !\is_array($notification)) {
304
				throw new InvalidShareException(
305
					'server can not add remote share, missing parameter'
306
				);
307
			}
308
			// TODO: check permissions/preconditions in all cases
309
			switch ($notificationType) {
310 View Code Duplication
				case FileNotification::NOTIFICATION_TYPE_SHARE_ACCEPTED:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
311
					$share = $this->getValidShare(
312
						$providerId, $notification['sharedSecret']
313
					);
314
					$this->fedShareManager->acceptShare($share);
315
					break;
316 View Code Duplication
				case FileNotification::NOTIFICATION_TYPE_SHARE_DECLINED:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
317
					$share = $this->getValidShare(
318
						$providerId, $notification['sharedSecret']
319
					);
320
					$this->fedShareManager->declineShare($share);
321
					break;
322
				case FileNotification::NOTIFICATION_TYPE_REQUEST_RESHARE:
323
					$shareWithAddress = new Address($notification['shareWith']);
324
					$localShareWith = $shareWithAddress->getUserId();
325
					$share = $this->getValidShare(
326
						$providerId, $notification['sharedSecret']
327
					);
328
					// TODO: permissions not needed ???
329
					$this->fedShareManager->reShare(
330
						$share, $providerId, $localShareWith, 0
331
					);
332
					break;
333
				case FileNotification::NOTIFICATION_TYPE_RESHARE_CHANGE_PERMISSION:
334
					$permissions = $notification['permission'];
335
					// TODO: Map OCM permissions to numeric
336
					$share = $this->getValidShare(
337
						$providerId, $notification['sharedSecret']
338
					);
339
					$this->fedShareManager->updatePermissions($share, $permissions);
340
					break;
341
				case FileNotification::NOTIFICATION_TYPE_SHARE_UNSHARED:
342
					$this->fedShareManager->unshare(
343
						$providerId, $notification['sharedSecret']
344
					);
345
					break;
346
				case FileNotification::NOTIFICATION_TYPE_RESHARE_UNDO:
347
					$share = $this->getValidShare(
348
						$providerId, $notification['sharedSecret']
349
					);
350
					$this->fedShareManager->revoke($share);
351
			}
352
		} catch (Share\Exceptions\ShareNotFound $e) {
353
			return new JSONResponse(
354
				['message' => $e->getMessage()],
355
				Http::STATUS_BAD_REQUEST
356
			);
357
		} catch (InvalidShareException $e) {
358
			return new JSONResponse(
359
				['message' => 'Missing arguments'],
360
				Http::STATUS_BAD_REQUEST
361
			);
362
		}
363
		return new JSONResponse(
364
			[],
365
			Http::STATUS_CREATED
366
		);
367
	}
368
369
	/**
370
	 * Get list of supported protocols
371
	 *
372
	 * @return array
373
	 */
374
	protected function getProtocols() {
375
		return [
376
			'webdav' => '/public.php/webdav/'
377
		];
378
	}
379
380
	/**
381
	 * Check if value is null or an array has any null item
382
	 *
383
	 * @param mixed $param
384
	 *
385
	 * @return bool
386
	 */
387 View Code Duplication
	protected function hasNull($param) {
388
		if (\is_array($param)) {
389
			return \in_array(null, $param, true);
390
		} else {
391
			return $param === null;
392
		}
393
	}
394
395
	/**
396
	 * Get share by id, validate it's type and token
397
	 *
398
	 * @param int $id
399
	 * @param string $sharedSecret
400
	 *
401
	 * @return IShare
402
	 *
403
	 * @throws InvalidShareException
404
	 * @throws Share\Exceptions\ShareNotFound
405
	 */
406 View Code Duplication
	protected function getValidShare($id, $sharedSecret) {
407
		$share = $this->federatedShareProvider->getShareById($id);
408
		if ($share->getShareType() !== FederatedShareProvider::SHARE_TYPE_REMOTE
409
			|| $share->getToken() !== $sharedSecret
410
		) {
411
			throw new InvalidShareException();
412
		}
413
		return $share;
414
	}
415
416
	/**
417
	 * @param string $resourceType
418
	 *
419
	 * @return bool
420
	 */
421
	protected function isSupportedResourceType($resourceType) {
422
		return $resourceType === FileNotification::RESOURCE_TYPE_FILE;
423
	}
424
425
	/**
426
	 * @param string $shareType
427
	 * @return bool
428
	 */
429
	protected function isSupportedShareType($shareType) {
430
		return $shareType === 'user';
431
	}
432
433
	/**
434
	 * @param string $protocolName
435
	 * @return bool
436
	 */
437
	protected function isSupportedProtocol($protocolName) {
438
		$supportedProtocols = $this->getProtocols();
439
		$supportedProtocolNames = \array_keys($supportedProtocols);
440
		return \in_array($protocolName, $supportedProtocolNames);
441
	}
442
}
443