Completed
Push — master ( 8e687f...b5ae1a )
by Morris
13s
created

PushController   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 205
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 13
Bugs 0 Features 0
Metric Value
wmc 23
c 13
b 0
f 0
lcom 1
cbo 0
dl 0
loc 205
ccs 47
cts 47
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A savePushToken() 0 16 2
A insertPushToken() 0 16 1
A updatePushToken() 0 14 1
C registerDevice() 0 46 13
A removeDevice() 0 19 4
A deletePushToken() 0 8 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\DataResponse;
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 22
	public function __construct($appName, IRequest $request, IDBConnection $db, ISession $session, IUserSession $userSession, IProvider $tokenProvider, Manager $identityProof) {
65 22
		parent::__construct($appName, $request);
66
67 22
		$this->db = $db;
68 22
		$this->session = $session;
69 22
		$this->userSession = $userSession;
70 22
		$this->tokenProvider = $tokenProvider;
71 22
		$this->identityProof = $identityProof;
72 22
	}
73
74
	/**
75
	 * @NoAdminRequired
76
	 *
77
	 * @param string $pushTokenHash
78
	 * @param string $devicePublicKey
79
	 * @param string $proxyServer
80
	 * @return DataResponse
81
	 */
82 15
	public function registerDevice($pushTokenHash, $devicePublicKey, $proxyServer) {
83 15
		$user = $this->userSession->getUser();
84 15
		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 1
			return new DataResponse([], Http::STATUS_UNAUTHORIZED);
86
		}
87
88 14
		if (!preg_match('/^([a-f0-9]{128})$/', $pushTokenHash)) {
89 3
			return new DataResponse(['message' => 'INVALID_PUSHTOKEN_HASH'], Http::STATUS_BAD_REQUEST);
90
		}
91
92
		if (
93 11
			((strlen($devicePublicKey) !== 450 || strpos($devicePublicKey, "\n" . '-----END PUBLIC KEY-----') !== 425) &&
94 4
				(strlen($devicePublicKey) !== 451 || strpos($devicePublicKey, "\n" . '-----END PUBLIC KEY-----' . "\n") !== 425)) ||
95 11
			strpos($devicePublicKey, '-----BEGIN PUBLIC KEY-----' . "\n") !== 0) {
96 3
			return new DataResponse(['message' => 'INVALID_DEVICE_KEY'], Http::STATUS_BAD_REQUEST);
97
		}
98
99
		if (
100 8
			!filter_var($proxyServer, FILTER_VALIDATE_URL) ||
101 5
			strlen($proxyServer) > 256 ||
102 8
			!preg_match('/^(https\:\/\/|http\:\/\/localhost(\:[0-9]{0,5})?\/)/', $proxyServer)
103
		) {
104 3
			return new DataResponse(['message' => 'INVALID_PROXY_SERVER'], Http::STATUS_BAD_REQUEST);
105
		}
106
107 5
		$tokenId = $this->session->get('token-id');
108
		try {
109 5
			$token = $this->tokenProvider->getTokenById($tokenId);
110 3
		} 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...
111 3
			return new DataResponse(['message' => 'INVALID_SESSION_TOKEN'], Http::STATUS_BAD_REQUEST);
112
		}
113
114 2
		$key = $this->identityProof->getKey($user);
115
116 2
		$deviceIdentifier = json_encode([$user->getCloudId(), $token->getId()]);
117 2
		openssl_sign($deviceIdentifier, $signature, $key->getPrivate(), OPENSSL_ALGO_SHA512);
118 2
		$deviceIdentifier = base64_encode(hash('sha512', $deviceIdentifier, true));
119
120 2
		$created = $this->savePushToken($user, $token, $deviceIdentifier, $devicePublicKey, $pushTokenHash, $proxyServer);
121
122 2
		return new DataResponse([
123 2
			'publicKey' => $key->getPublic(),
124 2
			'deviceIdentifier' => $deviceIdentifier,
125 2
			'signature' => base64_encode($signature),
126 2
		], $created ? Http::STATUS_CREATED : Http::STATUS_OK);
127
	}
128
129
	/**
130
	 * @NoAdminRequired
131
	 *
132
	 * @return DataResponse
133
	 */
134 5
	public function removeDevice() {
135 5
		$user = $this->userSession->getUser();
136 5
		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 1
			return new DataResponse([], Http::STATUS_UNAUTHORIZED);
138
		}
139
140 4
		$tokenId = $this->session->get('token-id');
141
		try {
142 4
			$token = $this->tokenProvider->getTokenById($tokenId);
143 2
		} 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...
144 2
			return new DataResponse(['message' => 'INVALID_SESSION_TOKEN'], Http::STATUS_BAD_REQUEST);
145
		}
146
147 2
		if ($this->deletePushToken($user, $token)) {
148 1
			return new DataResponse([], Http::STATUS_ACCEPTED);
149
		}
150
151 1
		return new DataResponse([], Http::STATUS_OK);
152
	}
153
154
	/**
155
	 * @param IUser $user
156
	 * @param IToken $token
157
	 * @param string $deviceIdentifier
158
	 * @param string $devicePublicKey
159
	 * @param string $pushTokenHash
160
	 * @param string $proxyServer
161
	 * @return bool If the hash was new to the database
162
	 */
163
	protected function savePushToken(IUser $user, IToken $token, $deviceIdentifier, $devicePublicKey, $pushTokenHash, $proxyServer) {
164
		$query = $this->db->getQueryBuilder();
165
		$query->select('*')
166
			->from('notifications_pushtokens')
167
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
168
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId())));
169
		$result = $query->execute();
170
		$row = $result->fetch();
171
		$result->closeCursor();
172
173
		if (!$row) {
174
			return $this->insertPushToken($user, $token, $deviceIdentifier, $devicePublicKey, $pushTokenHash, $proxyServer);
175
		}
176
177
		return $this->updatePushToken($user, $token, $devicePublicKey, $pushTokenHash, $proxyServer);
178
	}
179
180
	/**
181
	 * @param IUser $user
182
	 * @param IToken $token
183
	 * @param string $deviceIdentifier
184
	 * @param string $devicePublicKey
185
	 * @param string $pushTokenHash
186
	 * @param string $proxyServer
187
	 * @return bool If the entry was created
188
	 */
189
	protected function insertPushToken(IUser $user, IToken $token, $deviceIdentifier, $devicePublicKey, $pushTokenHash, $proxyServer) {
190
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
191
192
		$query = $this->db->getQueryBuilder();
193
		$query->insert('notifications_pushtokens')
194
			->values([
195
				'uid' => $query->createNamedParameter($user->getUID()),
196
				'token' => $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT),
197
				'deviceidentifier' => $query->createNamedParameter($deviceIdentifier),
198
				'devicepublickey' => $query->createNamedParameter($devicePublicKey),
199
				'devicepublickeyhash' => $query->createNamedParameter($devicePublicKeyHash),
200
				'pushtokenhash' => $query->createNamedParameter($pushTokenHash),
201
				'proxyserver' => $query->createNamedParameter($proxyServer),
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
	 * @param string $proxyServer
212
	 * @return bool If the entry was updated
213
	 */
214
	protected function updatePushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash, $proxyServer) {
215
		$devicePublicKeyHash = hash('sha512', $devicePublicKey);
216
217
		$query = $this->db->getQueryBuilder();
218
		$query->update('notifications_pushtokens')
219
			->set('devicepublickey', $query->createNamedParameter($devicePublicKey))
220
			->set('devicepublickeyhash', $query->createNamedParameter($devicePublicKeyHash))
221
			->set('pushtokenhash', $query->createNamedParameter($pushTokenHash))
222
			->set('proxyserver', $query->createNamedParameter($proxyServer))
223
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
224
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)));
225
226
		return $query->execute() !== 0;
227
	}
228
229
	/**
230
	 * @param IUser $user
231
	 * @param IToken $token
232
	 * @return bool If the entry was deleted
233
	 */
234
	protected function deletePushToken(IUser $user, IToken $token) {
235
		$query = $this->db->getQueryBuilder();
236
		$query->delete('notifications_pushtokens')
237
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
238
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)));
239
240
		return $query->execute() !== 0;
241
	}
242
}
243