Completed
Pull Request — master (#59)
by Joas
01:58
created

PushController::deletePushToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 3
crap 2
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\Crypto;
28
use OC\Security\IdentityProof\Manager;
29
use OCP\AppFramework\Http;
30
use OCP\AppFramework\Http\JSONResponse;
31
use OCP\AppFramework\OCSController;
32
use OCP\DB\QueryBuilder\IQueryBuilder;
33
use OCP\IDBConnection;
34
use OCP\IRequest;
35
use OCP\ISession;
36
use OCP\IUser;
37
use OCP\IUserSession;
38
39
class PushController extends OCSController {
40
41
	/** @var IDBConnection */
42
	private $db;
43
44
	/** @var ISession */
45
	private $session;
46
47
	/** @var IUserSession */
48
	private $userSession;
49
50
	/** @var IProvider */
51
	private $tokenProvider;
52
53
	/** @var Manager */
54
	private $identityProof;
55
56
	/** @var Crypto */
57
	private $crypto;
58
59
	/**
60
	 * @param string $appName
61
	 * @param IRequest $request
62
	 * @param IDBConnection $db
63
	 * @param ISession $session
64
	 * @param IUserSession $userSession
65
	 * @param IProvider $tokenProvider
66
	 * @param Manager $identityProof
67
	 * @param Crypto $crypto
68
	 */
69
	public function __construct($appName, IRequest $request, IDBConnection $db, ISession $session, IUserSession $userSession, IProvider $tokenProvider, Manager $identityProof, Crypto $crypto) {
70
		parent::__construct($appName, $request);
71
72
		$this->db = $db;
73
		$this->session = $session;
74
		$this->userSession = $userSession;
75
		$this->tokenProvider = $tokenProvider;
76
		$this->identityProof = $identityProof;
77
		$this->crypto = $crypto;
78
	}
79
80
	/**
81
	 * @NoAdminRequired
82
	 * @NoCSRFRequired
83
	 *
84
	 * @param string $pushTokenHash
85
	 * @param string $devicePublicKey
86
	 * @return JSONResponse
87
	 */
88
	public function registerDevice($pushTokenHash, $devicePublicKey) {
89
		$user = $this->userSession->getUser();
90
		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...
91
			return new JSONResponse([], Http::STATUS_UNAUTHORIZED);
92
		}
93
94
		if (!preg_match('/^([a-f0-9]{128})$/', $pushTokenHash)) {
95
			return new JSONResponse(['message' => 'Invalid hashed push token'], Http::STATUS_BAD_REQUEST);
96
		}
97
98 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...
99
			strpos($devicePublicKey, '-----BEGIN PUBLIC KEY-----') !== 0 ||
100
			strpos($devicePublicKey, '-----END PUBLIC KEY-----') !== 426) {
101
			return new JSONResponse(['message' => 'Invalid device public key'], Http::STATUS_BAD_REQUEST);
102
		}
103
104
		$tokenId = $this->session->get('token-id');
105
		try {
106
			$token = $this->tokenProvider->getTokenById($tokenId);
107
		} 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...
108
			return new JSONResponse(['message' => 'Could not identify session token'], Http::STATUS_BAD_REQUEST);
109
		}
110
111
		$key = $this->identityProof->getKey($user);
112
113
		try {
114
			$created = $this->savePushToken($user, $token, $devicePublicKey, $pushTokenHash);
115
		} catch (\BadMethodCallException $e) {
116
			return new JSONResponse(['message' => 'Invalid device public key'], Http::STATUS_BAD_REQUEST);
117
		}
118
119
		$encryptedData = $this->crypto->encrypt(json_encode([$user->getCloudId(), $token->getId()]), $user);
120
		return new JSONResponse([
121
			'publicKey' => $key->getPublic(),
122
			'deviceIdentifier' => $encryptedData['message'],
123
			'signature' => $encryptedData['signature'],
124
		], $created ? Http::STATUS_CREATED : Http::STATUS_OK);
125
	}
126
127
	/**
128
	 * @NoAdminRequired
129
	 * @NoCSRFRequired
130
	 *
131
	 * @param string $devicePublicKey
132
	 * @return JSONResponse
133
	 */
134
	public function removeDevice($devicePublicKey) {
135
		$user = $this->userSession->getUser();
136
		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...
137
			return new JSONResponse([], Http::STATUS_UNAUTHORIZED);
138
		}
139
140 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...
141
			strpos($devicePublicKey, '-----BEGIN PUBLIC KEY-----') !== 0 ||
142
			strpos($devicePublicKey, '-----END PUBLIC KEY-----') !== 426) {
143
			return new JSONResponse(['message' => 'Invalid device public key'], Http::STATUS_BAD_REQUEST);
144
		}
145
146
		$sessionId = $this->session->getId();
147
		try {
148
			$token = $this->tokenProvider->getToken($sessionId);
149
		} 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...
150
			return new JSONResponse(['message' => 'Could not identify session token'], Http::STATUS_BAD_REQUEST);
151
		}
152
153
		$this->deletePushToken($user, $token, $devicePublicKey);
154
		return new JSONResponse();
155
	}
156
157
	/**
158
	 * @param IUser $user
159
	 * @param IToken $token
160
	 * @param string $devicePublicKey
161
	 * @param string $pushTokenHash
162
	 * @return bool If the hash was new to the database
163
	 * @throws \BadMethodCallException
164
	 */
165
	protected function savePushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash) {
166
		$query = $this->db->getQueryBuilder();
167
		$query->select('pushtokenhash')
168
			->from('notifications_pushtokens')
169
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
170
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId())))
171
			->andWhere($query->expr()->eq('devicepublickey', $query->createNamedParameter($devicePublicKey)));
172
		$result = $query->execute();
173
		$row = $result->fetch();
174
		$result->closeCursor();
175
176
		if (!$row) {
177
			return $this->insertPushToken($user, $token, $devicePublicKey, $pushTokenHash);
178
		} else if ($row['pushtokenhash'] !== $pushTokenHash) {
179
			return $this->updatePushToken($user, $token, $devicePublicKey, $pushTokenHash);
180
		}
181
		return false;
182
	}
183
184
	/**
185
	 * @param IUser $user
186
	 * @param IToken $token
187
	 * @param string $devicePublicKey
188
	 * @param string $pushTokenHash
189
	 * @return bool If the entry was created
190
	 */
191
	protected function insertPushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash) {
192
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
193
194
		$query = $this->db->getQueryBuilder();
195
		$query->insert('notifications_pushtokens')
196
			->values([
197
				'uid' => $query->createNamedParameter($user->getUID()),
198
				'token' => $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT),
199
				'devicepublickey' => $query->createNamedParameter($devicePublicKey),
200
				'devicepublickeyhash' => $query->createNamedParameter($devicePublicKeyHash),
201
				'pushtokenhash' => $query->createNamedParameter($pushTokenHash),
202
			]);
203
		return $query->execute() > 0;
204
	}
205
206
	/**
207
	 * @param IUser $user
208
	 * @param IToken $token
209
	 * @param string $devicePublicKey
210
	 * @param string $pushTokenHash
211
	 * @return bool If the entry was updated
212
	 * @throws \BadMethodCallException
213
	 */
214
	protected function updatePushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash) {
215
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
216
217
		$query = $this->db->getQueryBuilder();
218
		$query->update('notifications_pushtokens')
219
			->set('pushtokenhash', $query->createNamedParameter($pushTokenHash))
220
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
221
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)))
222
			->andWhere($query->expr()->eq('devicepublickeyhash', $query->createNamedParameter($devicePublicKeyHash)));
223
224
		if ($query->execute() !== 0) {
225
			throw new \BadMethodCallException();
226
		}
227
228
		return true;
229
	}
230
231
	/**
232
	 * @param IUser $user
233
	 * @param IToken $token
234
	 * @param string $devicePublicKey
235
	 * @return bool If the entry was deleted
236
	 */
237
	protected function deletePushToken(IUser $user, IToken $token, $devicePublicKey) {
238
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
239
240
		$query = $this->db->getQueryBuilder();
241
		$query->delete('notifications_pushtokens')
242
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
243
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)))
244
			->andWhere($query->expr()->eq('devicepublickeyhash', $query->createNamedParameter($devicePublicKeyHash)));
245
		return $query->execute() > 0;
246
	}
247
}
248