Completed
Pull Request — master (#59)
by Joas
02:09
created

PushController::removeDevice()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 27
Code Lines 18

Duplication

Lines 5
Ratio 18.52 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 5
loc 27
rs 6.7272
cc 7
eloc 18
nc 5
nop 1
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
		$deviceIdentifier = json_encode([$user->getCloudId(), $token->getId()]);
108
		openssl_sign($deviceIdentifier, $signature, $key->getPrivate(), OPENSSL_ALGO_SHA512);
109
		$deviceIdentifier = base64_encode(hash('sha512', $deviceIdentifier, true));
110
111
		try {
112
			$created = $this->savePushToken($user, $token, $deviceIdentifier, $devicePublicKey, $pushTokenHash);
113
		} catch (\BadMethodCallException $e) {
114
			return new JSONResponse(['message' => 'INVALID_DEVICE_KEY'], Http::STATUS_BAD_REQUEST);
115
		}
116
117
		return new JSONResponse([
118
			'publicKey' => $key->getPublic(),
119
			'deviceIdentifier' => $deviceIdentifier,
120
			'signature' => base64_encode($signature),
121
		], $created ? Http::STATUS_CREATED : Http::STATUS_OK);
122
	}
123
124
	/**
125
	 * @NoAdminRequired
126
	 * @NoCSRFRequired
127
	 *
128
	 * @param string $devicePublicKey
129
	 * @return JSONResponse
130
	 */
131
	public function removeDevice($devicePublicKey) {
132
		$user = $this->userSession->getUser();
133
		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...
134
			return new JSONResponse([], Http::STATUS_UNAUTHORIZED);
135
		}
136
137 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...
138
			strpos($devicePublicKey, '-----BEGIN PUBLIC KEY-----') !== 0 ||
139
			strpos($devicePublicKey, '-----END PUBLIC KEY-----') !== 426) {
140
			return new JSONResponse(['message' => 'INVALID_DEVICE_KEY'], Http::STATUS_BAD_REQUEST);
141
		}
142
143
		$sessionId = $this->session->getId();
144
		try {
145
			$token = $this->tokenProvider->getToken($sessionId);
146
		} 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...
147
			return new JSONResponse(['message' => 'INVALID_SESSION_TOKEN'], Http::STATUS_BAD_REQUEST);
148
		}
149
150
		try {
151
			$this->deletePushToken($user, $token, $devicePublicKey);
152
		} catch (\BadMethodCallException $e) {
153
			return new JSONResponse(['message' => 'INVALID_DEVICE_KEY'], Http::STATUS_BAD_REQUEST);
154
		}
155
156
		return new JSONResponse([], Http::STATUS_ACCEPTED);
157
	}
158
159
	/**
160
	 * @param IUser $user
161
	 * @param IToken $token
162
	 * @param string $deviceIdentifier
163
	 * @param string $devicePublicKey
164
	 * @param string $pushTokenHash
165
	 * @return bool If the hash was new to the database
166
	 * @throws \BadMethodCallException
167
	 */
168
	protected function savePushToken(IUser $user, IToken $token, $deviceIdentifier, $devicePublicKey, $pushTokenHash) {
169
		$query = $this->db->getQueryBuilder();
170
		$query->select('pushtokenhash')
171
			->from('notifications_pushtokens')
172
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
173
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId())))
174
			->andWhere($query->expr()->eq('devicepublickey', $query->createNamedParameter($devicePublicKey)));
175
		$result = $query->execute();
176
		$row = $result->fetch();
177
		$result->closeCursor();
178
179
		if (!$row) {
180
			return $this->insertPushToken($user, $token, $deviceIdentifier, $devicePublicKey, $pushTokenHash);
181
		} else if ($row['pushtokenhash'] !== $pushTokenHash) {
182
			return $this->updatePushToken($user, $token, $devicePublicKey, $pushTokenHash);
183
		}
184
		return false;
185
	}
186
187
	/**
188
	 * @param IUser $user
189
	 * @param IToken $token
190
	 * @param string $deviceIdentifier
191
	 * @param string $devicePublicKey
192
	 * @param string $pushTokenHash
193
	 * @return bool If the entry was created
194
	 */
195
	protected function insertPushToken(IUser $user, IToken $token, $deviceIdentifier, $devicePublicKey, $pushTokenHash) {
196
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
197
198
		$query = $this->db->getQueryBuilder();
199
		$query->insert('notifications_pushtokens')
200
			->values([
201
				'uid' => $query->createNamedParameter($user->getUID()),
202
				'token' => $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT),
203
				'deviceidentifier' => $query->createNamedParameter($deviceIdentifier),
204
				'devicepublickey' => $query->createNamedParameter($devicePublicKey),
205
				'devicepublickeyhash' => $query->createNamedParameter($devicePublicKeyHash),
206
				'pushtokenhash' => $query->createNamedParameter($pushTokenHash),
207
			]);
208
		return $query->execute() > 0;
209
	}
210
211
	/**
212
	 * @param IUser $user
213
	 * @param IToken $token
214
	 * @param string $devicePublicKey
215
	 * @param string $pushTokenHash
216
	 * @return bool If the entry was updated
217
	 * @throws \BadMethodCallException
218
	 */
219 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...
220
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
221
222
		$query = $this->db->getQueryBuilder();
223
		$query->update('notifications_pushtokens')
224
			->set('pushtokenhash', $query->createNamedParameter($pushTokenHash))
225
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
226
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)))
227
			->andWhere($query->expr()->eq('devicepublickeyhash', $query->createNamedParameter($devicePublicKeyHash)));
228
229
		if ($query->execute() !== 0) {
230
			throw new \BadMethodCallException();
231
		}
232
233
		return true;
234
	}
235
236
	/**
237
	 * @param IUser $user
238
	 * @param IToken $token
239
	 * @param string $devicePublicKey
240
	 * @return bool If the entry was deleted
241
	 * @throws \BadMethodCallException
242
	 */
243 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...
244
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
245
246
		$query = $this->db->getQueryBuilder();
247
		$query->delete('notifications_pushtokens')
248
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
249
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)))
250
			->andWhere($query->expr()->eq('devicepublickeyhash', $query->createNamedParameter($devicePublicKeyHash)));
251
252
		if ($query->execute() !== 0) {
253
			throw new \BadMethodCallException();
254
		}
255
256
		return true;
257
	}
258
}
259