Completed
Pull Request — master (#59)
by Joas
05:35
created

PushController::savePushToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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