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

PushController::insertPushToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

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 11
ccs 0
cts 11
cp 0
rs 9.4285
cc 1
eloc 9
nc 1
nop 4
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
		$sessionId = $this->session->getId();
105
		try {
106
			$token = $this->tokenProvider->getToken($sessionId);
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
		$created = $this->savePushToken($user, $token, $devicePublicKey, $pushTokenHash);
114
115
		$encryptedData = $this->crypto->encrypt(json_encode([$user->getCloudId(), $token->getId()]), $user);
116
		return new JSONResponse([
117
			'publicKey' => $key->getPublic(),
118
			'deviceIdentifier' => $encryptedData['message'],
119
			'signature' => $encryptedData['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-----') !== 425) {
139
			return new JSONResponse(['message' => 'Invalid device public 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' => 'Could not identify session token'], Http::STATUS_BAD_REQUEST);
147
		}
148
149
		$this->deletePushToken($user, $token, $devicePublicKey);
150
		return new JSONResponse();
151
	}
152
153
	/**
154
	 * @param IUser $user
155
	 * @param IToken $token
156
	 * @param string $devicePublicKey
157
	 * @param string $pushTokenHash
158
	 * @return bool If the hash was new to the database
159
	 */
160
	protected function savePushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash) {
161
		$query = $this->db->getQueryBuilder();
162
		$query->select('pushtokenhash')
163
			->from('notifications_pushtokens')
164
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
165
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId())))
166
			->andWhere($query->expr()->eq('devicepublickey', $query->createNamedParameter($devicePublicKey)));
167
		$result = $query->execute();
168
		$row = $result->fetch();
169
		$result->closeCursor();
170
171
		if (!$row) {
172
			return $this->insertPushToken($user, $token, $devicePublicKey, $pushTokenHash);
173
		} else if ($row['pushtokenhash'] !== $pushTokenHash) {
174
			return $this->updatePushToken($user, $token, $devicePublicKey, $pushTokenHash);
175
		}
176
		return false;
177
	}
178
179
	/**
180
	 * @param IUser $user
181
	 * @param IToken $token
182
	 * @param string $devicePublicKey
183
	 * @param string $pushTokenHash
184
	 * @return bool If the entry was created
185
	 */
186
	protected function insertPushToken(IUser $user, IToken $token, $devicePublicKey, $pushTokenHash) {
187
		$query = $this->db->getQueryBuilder();
188
		$query->insert('notifications_pushtokens')
189
			->values([
190
				'uid' => $query->createNamedParameter($user->getUID()),
191
				'token' => $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT),
192
				'devicepublickey' => $query->createNamedParameter($devicePublicKey),
193
				'pushtokenhash' => $query->createNamedParameter($pushTokenHash),
194
			]);
195
		return $query->execute() > 0;
196
	}
197
198
	/**
199
	 * @param IUser $user
200
	 * @param IToken $token
201
	 * @param string $devicePublicKey
202
	 * @param string $pushTokenHash
203
	 * @return bool If the entry was updated
204
	 */
205 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...
206
		$query = $this->db->getQueryBuilder();
207
		$query->update('notifications_pushtokens')
208
			->set('pushtokenhash', $query->createNamedParameter($pushTokenHash))
209
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
210
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)))
211
			->andWhere($query->expr()->eq('devicepublickey', $query->createNamedParameter($devicePublicKey)));
212
		return $query->execute() > 0;
213
	}
214
215
	/**
216
	 * @param IUser $user
217
	 * @param IToken $token
218
	 * @param string $devicePublicKey
219
	 * @return bool If the entry was deleted
220
	 */
221 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...
222
		$query = $this->db->getQueryBuilder();
223
		$query->delete('notifications_pushtokens')
224
			->where($query->expr()->eq('uid', $query->createNamedParameter($user->getUID())))
225
			->andWhere($query->expr()->eq('token', $query->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT)))
226
			->andWhere($query->expr()->eq('devicepublickey', $query->createNamedParameter($devicePublicKey)));
227
		return $query->execute() > 0;
228
	}
229
}
230