Completed
Pull Request — master (#59)
by Joas
31:48
created

PushController   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 217
Duplicated Lines 18.89 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 25
c 2
b 0
f 0
lcom 1
cbo 0
dl 41
loc 217
ccs 0
cts 119
cp 0
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A savePushToken() 0 18 3
C removeDevice() 5 27 7
A insertPushToken() 0 14 1
A updatePushToken() 16 16 2
A deletePushToken() 15 15 2
D registerDevice() 5 40 9

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2017 Joas Schilling <[email protected]>
4
 *
5
 * @license GNU AGPL version 3 or any later version
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as
9
 * published by the Free Software Foundation, either version 3 of the
10
 * License, or (at your option) any later version.
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
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 */
21
22
namespace OCA\Notifications\Controller;
23
24
use OC\Authentication\Exceptions\InvalidTokenException;
25
use OC\Authentication\Token\IProvider;
26
use OC\Authentication\Token\IToken;
27
use OC\Security\IdentityProof\Manager;
28
use OCP\AppFramework\Http;
29
use OCP\AppFramework\Http\JSONResponse;
30
use OCP\AppFramework\OCSController;
31
use OCP\DB\QueryBuilder\IQueryBuilder;
32
use OCP\IDBConnection;
33
use OCP\IRequest;
34
use OCP\ISession;
35
use OCP\IUser;
36
use OCP\IUserSession;
37
38
class PushController extends OCSController {
39
40
	/** @var IDBConnection */
41
	private $db;
42
43
	/** @var ISession */
44
	private $session;
45
46
	/** @var IUserSession */
47
	private $userSession;
48
49
	/** @var IProvider */
50
	private $tokenProvider;
51
52
	/** @var Manager */
53
	private $identityProof;
54
55
	/**
56
	 * @param string $appName
57
	 * @param IRequest $request
58
	 * @param IDBConnection $db
59
	 * @param ISession $session
60
	 * @param IUserSession $userSession
61
	 * @param IProvider $tokenProvider
62
	 * @param Manager $identityProof
63
	 */
64
	public function __construct($appName, IRequest $request, IDBConnection $db, ISession $session, IUserSession $userSession, IProvider $tokenProvider, Manager $identityProof) {
65
		parent::__construct($appName, $request);
66
67
		$this->db = $db;
68
		$this->session = $session;
69
		$this->userSession = $userSession;
70
		$this->tokenProvider = $tokenProvider;
71
		$this->identityProof = $identityProof;
72
	}
73
74
	/**
75
	 * @NoAdminRequired
76
	 * @NoCSRFRequired
77
	 *
78
	 * @param string $pushTokenHash
79
	 * @param string $devicePublicKey
80
	 * @return JSONResponse
81
	 */
82
	public function registerDevice($pushTokenHash, $devicePublicKey) {
83
		$user = $this->userSession->getUser();
84
		if (!$user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
85
			return new JSONResponse([], Http::STATUS_UNAUTHORIZED);
86
		}
87
88
		if (!preg_match('/^([a-f0-9]{128})$/', $pushTokenHash)) {
89
			return new JSONResponse(['message' => 'INVALID_PUSHTOKEN_HASH'], Http::STATUS_BAD_REQUEST);
90
		}
91
92 View Code Duplication
		if (strlen($devicePublicKey) !== 450 ||
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...
93
			strpos($devicePublicKey, '-----BEGIN PUBLIC KEY-----') !== 0 ||
94
			strpos($devicePublicKey, '-----END PUBLIC KEY-----') !== 426) {
95
			return new JSONResponse(['message' => 'INVALID_DEVICE_KEY'], Http::STATUS_BAD_REQUEST);
96
		}
97
98
		$tokenId = $this->session->get('token-id');
99
		try {
100
			$token = $this->tokenProvider->getTokenById($tokenId);
101
		} catch (InvalidTokenException $e) {
0 ignored issues
show
Bug introduced by
The class OC\Authentication\Exceptions\InvalidTokenException 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...
102
			return new JSONResponse(['message' => 'INVALID_SESSION_TOKEN'], Http::STATUS_BAD_REQUEST);
103
		}
104
105
		$key = $this->identityProof->getKey($user);
106
107
		try {
108
			$created = $this->savePushToken($user, $token, $devicePublicKey, $pushTokenHash);
109
		} catch (\BadMethodCallException $e) {
110
			return new JSONResponse(['message' => 'INVALID_DEVICE_KEY'], Http::STATUS_BAD_REQUEST);
111
		}
112
113
		$deviceIdentifier = json_encode([$user->getCloudId(), $token->getId()]);
114
		openssl_sign($deviceIdentifier, $signature, $key->getPrivate(), OPENSSL_ALGO_SHA512);
115
116
		return new JSONResponse([
117
			'publicKey' => $key->getPublic(),
118
			'deviceIdentifier' => base64_encode(hash('sha512', $deviceIdentifier, true)),
119
			'signature' => base64_encode($signature),
120
		], $created ? Http::STATUS_CREATED : Http::STATUS_OK);
121
	}
122
123
	/**
124
	 * @NoAdminRequired
125
	 * @NoCSRFRequired
126
	 *
127
	 * @param string $devicePublicKey
128
	 * @return JSONResponse
129
	 */
130
	public function removeDevice($devicePublicKey) {
131
		$user = $this->userSession->getUser();
132
		if (!$user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
133
			return new JSONResponse([], Http::STATUS_UNAUTHORIZED);
134
		}
135
136 View Code Duplication
		if (strlen($devicePublicKey) !== 450 ||
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...
137
			strpos($devicePublicKey, '-----BEGIN PUBLIC KEY-----') !== 0 ||
138
			strpos($devicePublicKey, '-----END PUBLIC KEY-----') !== 426) {
139
			return new JSONResponse(['message' => 'INVALID_DEVICE_KEY'], Http::STATUS_BAD_REQUEST);
140
		}
141
142
		$sessionId = $this->session->getId();
143
		try {
144
			$token = $this->tokenProvider->getToken($sessionId);
145
		} catch (InvalidTokenException $e) {
0 ignored issues
show
Bug introduced by
The class OC\Authentication\Exceptions\InvalidTokenException 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...
146
			return new JSONResponse(['message' => 'INVALID_SESSION_TOKEN'], Http::STATUS_BAD_REQUEST);
147
		}
148
149
		try {
150
			$this->deletePushToken($user, $token, $devicePublicKey);
151
		} catch (\BadMethodCallException $e) {
152
			return new JSONResponse(['message' => 'INVALID_DEVICE_KEY'], Http::STATUS_BAD_REQUEST);
153
		}
154
155
		return new JSONResponse([], Http::STATUS_ACCEPTED);
156
	}
157
158
	/**
159
	 * @param IUser $user
160
	 * @param IToken $token
161
	 * @param string $devicePublicKey
162
	 * @param string $pushTokenHash
163
	 * @return bool If the hash was new to the database
164
	 * @throws \BadMethodCallException
165
	 */
166
	protected function savePushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash) {
167
		$query = $this->db->getQueryBuilder();
168
		$query->select('pushtokenhash')
169
			->from('notifications_pushtokens')
170
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
171
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId())))
172
			->andWhere($query->expr()->eq('devicepublickey', $query->createNamedParameter($devicePublicKey)));
173
		$result = $query->execute();
174
		$row = $result->fetch();
175
		$result->closeCursor();
176
177
		if (!$row) {
178
			return $this->insertPushToken($user, $token, $devicePublicKey, $pushTokenHash);
179
		} else if ($row['pushtokenhash'] !== $pushTokenHash) {
180
			return $this->updatePushToken($user, $token, $devicePublicKey, $pushTokenHash);
181
		}
182
		return false;
183
	}
184
185
	/**
186
	 * @param IUser $user
187
	 * @param IToken $token
188
	 * @param string $devicePublicKey
189
	 * @param string $pushTokenHash
190
	 * @return bool If the entry was created
191
	 */
192
	protected function insertPushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash) {
193
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
194
195
		$query = $this->db->getQueryBuilder();
196
		$query->insert('notifications_pushtokens')
197
			->values([
198
				'uid' => $query->createNamedParameter($user->getUID()),
199
				'token' => $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT),
200
				'devicepublickey' => $query->createNamedParameter($devicePublicKey),
201
				'devicepublickeyhash' => $query->createNamedParameter($devicePublicKeyHash),
202
				'pushtokenhash' => $query->createNamedParameter($pushTokenHash),
203
			]);
204
		return $query->execute() > 0;
205
	}
206
207
	/**
208
	 * @param IUser $user
209
	 * @param IToken $token
210
	 * @param string $devicePublicKey
211
	 * @param string $pushTokenHash
212
	 * @return bool If the entry was updated
213
	 * @throws \BadMethodCallException
214
	 */
215 View Code Duplication
	protected function updatePushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
216
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
217
218
		$query = $this->db->getQueryBuilder();
219
		$query->update('notifications_pushtokens')
220
			->set('pushtokenhash', $query->createNamedParameter($pushTokenHash))
221
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
222
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)))
223
			->andWhere($query->expr()->eq('devicepublickeyhash', $query->createNamedParameter($devicePublicKeyHash)));
224
225
		if ($query->execute() !== 0) {
226
			throw new \BadMethodCallException();
227
		}
228
229
		return true;
230
	}
231
232
	/**
233
	 * @param IUser $user
234
	 * @param IToken $token
235
	 * @param string $devicePublicKey
236
	 * @return bool If the entry was deleted
237
	 * @throws \BadMethodCallException
238
	 */
239 View Code Duplication
	protected function deletePushToken(IUser $user, IToken $token, $devicePublicKey) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
240
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
241
242
		$query = $this->db->getQueryBuilder();
243
		$query->delete('notifications_pushtokens')
244
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
245
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)))
246
			->andWhere($query->expr()->eq('devicepublickeyhash', $query->createNamedParameter($devicePublicKeyHash)));
247
248
		if ($query->execute() !== 0) {
249
			throw new \BadMethodCallException();
250
		}
251
252
		return true;
253
	}
254
}
255