Completed
Push — master ( c17b1b...8f13d8 )
by Olivier
13:31 queued 09:59
created

EnvCheckMiddleware::authenticate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.3149

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 12
ccs 4
cts 7
cp 0.5714
rs 9.4285
cc 2
eloc 8
nc 2
nop 2
crap 2.3149
1
<?php
2
/**
3
 * ownCloud - galleryplus
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Olivier Paroz <[email protected]>
9
 * @author Bernhard Posselt <[email protected]>
10
 * @author Authors of \OCA\Files_Sharing\Helper
11
 *
12
 * @copyright Olivier Paroz 2014-2016
13
 * @copyright Bernhard Posselt 2012-2015
14
 * @copyright Authors of \OCA\Files_Sharing\Helper 2014-2016
15
 */
16
17
namespace OCA\GalleryPlus\Middleware;
18
19
use OCP\IRequest;
20
use OCP\IURLGenerator;
21
use OCP\ISession;
22
use OCP\ILogger;
23
use OCP\Share;
24
use OCP\Share\IShare;
25
use OCP\Share\Exceptions\ShareNotFound;
26
use OCP\Security\IHasher;
27
28
use OCP\AppFramework\Http;
29
use OCP\AppFramework\Utility\IControllerMethodReflector;
30
31
use OCA\GalleryPlus\Environment\Environment;
32
use OCP\Share\IManager;
33
34
/**
35
 * Checks that we have a valid token linked to a valid resource and that the
36
 * user is authorised to access it
37
 *
38
 * Once all checks have been passed, the environment is ready to use
39
 *
40
 * @package OCA\GalleryPlus\Middleware
41
 */
42
class EnvCheckMiddleware extends CheckMiddleware {
43
44
	/** @var IHasher */
45
	private $hasher;
46
	/** @var ISession */
47
	private $session;
48
	/** @var Environment */
49
	private $environment;
50
	/** @var IControllerMethodReflector */
51
	protected $reflector;
52
	/** @var IManager */
53
	protected $shareManager;
54
55
	/***
56
	 * Constructor
57
	 *
58
	 * @param string $appName
59
	 * @param IRequest $request
60
	 * @param IHasher $hasher
61
	 * @param ISession $session
62
	 * @param Environment $environment
63
	 * @param IControllerMethodReflector $reflector
64
	 * @param IURLGenerator $urlGenerator
65
	 * @param ILogger $logger
66
	 * @param IManager $shareManager
67
	 */
68 55
	public function __construct(
69
		$appName,
70
		IRequest $request,
71
		IHasher $hasher,
72
		ISession $session,
73
		Environment $environment,
74
		IControllerMethodReflector $reflector,
75
		IURLGenerator $urlGenerator,
76
		IManager $shareManager,
77
		ILogger $logger
78
	) {
79 55
		parent::__construct(
80
			$appName,
81
			$request,
82
			$urlGenerator,
83
			$logger
84
		);
85
86 55
		$this->hasher = $hasher;
87 55
		$this->session = $session;
88 55
		$this->environment = $environment;
89 55
		$this->reflector = $reflector;
90 55
		$this->shareManager = $shareManager;
91 55
	}
92
93
	/**
94
	 * Checks that we have a valid token linked to a valid resource and that the
95
	 * user is authorised to access it
96
	 *
97
	 * Inspects the controller method annotations and if PublicPage is found
98
	 * it checks that we have a token and an optional password giving access to a valid resource.
99
	 * Once that's done, the environment is setup so that our services can find the resources they
100
	 * need.
101
	 *
102
	 * The checks are not performed on "guest" pages and the environment is not setup. Typical
103
	 * guest pages are anonymous error ages
104
	 *
105
	 * @inheritDoc
106
	 */
107 34
	public function beforeController($controller, $methodName) {
108 34
		if ($this->reflector->hasAnnotation('Guest')) {
109 3
			return;
110
		}
111 33
		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
112 33
		if ($isPublicPage) {
113 14
			$this->validateAndSetTokenBasedEnv();
114
		} else {
115 21
			$this->environment->setStandardEnv();
116
		}
117 29
	}
118
119
	/**
120
	 * Checks that we have a token and an optional password giving access to a
121
	 * valid resource. Sets the token based environment after that
122
	 *
123
	 * @throws CheckException
124
	 */
125 14
	private function validateAndSetTokenBasedEnv() {
126 14
		$token = $this->request->getParam('token');
127 14
		if (!$token) {
128 2
			throw new CheckException(
129 2
				"Can't access a public resource without a token", Http::STATUS_NOT_FOUND
130
			);
131
		} else {
132 12
			$share = $this->getShare($token);
133 10
			$password = $this->request->getParam('password');
134
			// Let's see if the user needs to provide a password
135 10
			$this->checkAuthorisation($share, $password);
136
137 9
			$this->environment->setTokenBasedEnv($share);
138
		}
139 9
	}
140
141
	/**
142
	 * Validates a token to make sure its linked to a valid resource
143
	 *
144
	 * Uses Share 2.0
145
	 *
146
	 * @fixme setIncognitoMode in 8.1 https://github.com/owncloud/core/pull/12912
147
	 *
148
	 * @param string $token
149
	 *
150
	 * @throws CheckException
151
	 * @return IShare
152
	 */
153 12
	private function getShare($token) {
154
		// Allows a logged in user to access public links
155 12
		\OC_User::setIncognitoMode(true);
156
157
		try {
158 12
			$share = $this->shareManager->getShareByToken($token);
159 2
		} catch (ShareNotFound $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Share\Exceptions\ShareNotFound does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
160 2
			throw new CheckException($e->getMessage(), Http::STATUS_NOT_FOUND);
161
		}
162
163 10
		$this->checkShareIsValid($share, $token);
164 10
		$this->checkItemType($share);
165
166 10
		return $share;
167
	}
168
169
	/**
170
	 * Makes sure that the token contains all the information that we need
171
	 *
172
	 * @param IShare $share
173
	 * @param string $token
174
	 *
175
	 * @throws CheckException
176
	 */
177 13
	private function checkShareIsValid($share, $token) {
178 13
		if ($share->getShareOwner() === null
179 13
			|| $share->getTarget() === null
180
		) {
181
			$message =
182
				'Passed token seems to be valid, but it does not contain all necessary information . ("'
183 2
				. $token . '")';
184 2
			throw new CheckException($message, Http::STATUS_NOT_FOUND);
185
		}
186 11
	}
187
188
	/**
189
	 * Makes sure an item type was set for that token
190
	 *
191
	 * @param IShare $share
192
	 *
193
	 * @throws CheckException
194
	 */
195 12
	private function checkItemType($share) {
196 12
		if ($share->getNodeType() === null) {
197 1
			$message = 'No item type set for share id: ' . $share->getId();
198 1
			throw new CheckException($message, Http::STATUS_NOT_FOUND);
199
		}
200 11
	}
201
202
203
	/**
204
	 * Checks if a password is required or if the one supplied is working
205
	 *
206
	 * @param IShare $share
207
	 * @param string|null $password optional password
208
	 *
209
	 * @throws CheckException
210
	 */
211 13
	private function checkAuthorisation($share, $password) {
212 13
		$passwordRequired = $share->getPassword();
213
214 13
		if (isset($passwordRequired)) {
215 9
			if ($password !== null) {
216 8
				$this->authenticate($share, $password);
217
			} else {
218 1
				$this->checkSession($share);
219
			}
220
		}
221 11
	}
222
223
	/**
224
	 * Authenticate link item with the given password
225
	 * or with the session if no password was given.
226
	 *
227
	 * @param IShare $share
228
	 * @param string $password
229
	 *
230
	 * @return bool true if authorized, an exception is raised otherwise
231
	 *
232
	 * @throws CheckException
233
	 */
234 11
	private function authenticate($share, $password) {
235 11
		if ((int)$share->getShareType() === Share::SHARE_TYPE_LINK) {
236 11
			$this->checkPassword($share, $password);
237
		} else {
238
			throw new CheckException(
239
				'Unknown share type ' . $share->getShareType() . ' for share id '
240
				. $share->getId(), Http::STATUS_NOT_FOUND
241
			);
242
		}
243
244 7
		return true;
245
	}
246
247
	/**
248
	 * Validates the given password
249
	 *
250
	 * @fixme @LukasReschke says: Migrate old hashes to new hash format
251
	 * Due to the fact that there is no reasonable functionality to update the password
252
	 * of an existing share no migration is yet performed there.
253
	 * The only possibility is to update the existing share which will result in a new
254
	 * share ID and is a major hack.
255
	 *
256
	 * In the future the migration should be performed once there is a proper method
257
	 * to update the share's password. (for example `$share->updatePassword($password)`
258
	 *
259
	 * @link https://github.com/owncloud/core/issues/10671
260
	 *
261
	 * @param IShare $share
262
	 * @param string $password
263
	 *
264
	 * @throws CheckException
265
	 */
266 13
	private function checkPassword($share, $password) {
267 13
		$newHash = '';
268 13
		if ($this->shareManager->checkPassword($share, $password)) {
269
			// Save item id in session for future requests
270 8
			$this->session->set('public_link_authenticated', $share->getId());
271
			// @codeCoverageIgnoreStart
272
			if (!empty($newHash)) {
273
				// For future use
274
			}
275
			// @codeCoverageIgnoreEnd
276
		} else {
277 5
			throw new CheckException("Wrong password", Http::STATUS_UNAUTHORIZED);
278
		}
279 8
	}
280
281
	/**
282
	 * Makes sure the user is already properly authenticated when a password is required and none
283
	 * was provided
284
	 *
285
	 * @param IShare $share
286
	 *
287
	 * @throws CheckException
288
	 */
289 4
	private function checkSession($share) {
290
		// Not authenticated ?
291 4
		if (!$this->session->exists('public_link_authenticated')
292 4
			|| $this->session->get('public_link_authenticated') !== $share->getId()
293
		) {
294 2
			throw new CheckException("Missing password", Http::STATUS_UNAUTHORIZED);
295
		}
296 2
	}
297
298
}
299