Passed
Push — master ( a92321...b8b2e7 )
by Blizzz
27:11 queued 15:31
created
apps/settings/lib/BackgroundJobs/VerifyUserData.php 2 patches
Indentation   +245 added lines, -245 removed lines patch added patch discarded remove patch
@@ -43,249 +43,249 @@
 block discarded – undo
43 43
 
44 44
 class VerifyUserData extends Job {
45 45
 
46
-	/** @var  bool */
47
-	private $retainJob = true;
48
-
49
-	/** @var int max number of attempts to send the request */
50
-	private $maxTry = 24;
51
-
52
-	/** @var int how much time should be between two tries (1 hour) */
53
-	private $interval = 3600;
54
-
55
-	/** @var IAccountManager */
56
-	private $accountManager;
57
-
58
-	/** @var IUserManager */
59
-	private $userManager;
60
-
61
-	/** @var IClientService */
62
-	private $httpClientService;
63
-
64
-	/** @var ILogger */
65
-	private $logger;
66
-
67
-	/** @var string */
68
-	private $lookupServerUrl;
69
-
70
-	/** @var IConfig */
71
-	private $config;
72
-
73
-	public function __construct(IAccountManager $accountManager,
74
-								IUserManager $userManager,
75
-								IClientService $clientService,
76
-								ILogger $logger,
77
-								ITimeFactory $timeFactory,
78
-								IConfig $config
79
-	) {
80
-		parent::__construct($timeFactory);
81
-		$this->accountManager = $accountManager;
82
-		$this->userManager = $userManager;
83
-		$this->httpClientService = $clientService;
84
-		$this->logger = $logger;
85
-
86
-		$lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
87
-		$this->lookupServerUrl = rtrim($lookupServerUrl, '/');
88
-		$this->config = $config;
89
-	}
90
-
91
-	/**
92
-	 * run the job, then remove it from the jobList
93
-	 *
94
-	 * @param IJobList $jobList
95
-	 * @param ILogger|null $logger
96
-	 */
97
-	public function execute(IJobList $jobList, ILogger $logger = null) {
98
-		if ($this->shouldRun($this->argument)) {
99
-			parent::execute($jobList, $logger);
100
-			$jobList->remove($this, $this->argument);
101
-			if ($this->retainJob) {
102
-				$this->reAddJob($jobList, $this->argument);
103
-			} else {
104
-				$this->resetVerificationState();
105
-			}
106
-		}
107
-	}
108
-
109
-	protected function run($argument) {
110
-		$try = (int)$argument['try'] + 1;
111
-
112
-		switch ($argument['type']) {
113
-			case IAccountManager::PROPERTY_WEBSITE:
114
-				$result = $this->verifyWebsite($argument);
115
-				break;
116
-			case IAccountManager::PROPERTY_TWITTER:
117
-			case IAccountManager::PROPERTY_EMAIL:
118
-				$result = $this->verifyViaLookupServer($argument, $argument['type']);
119
-				break;
120
-			default:
121
-				// no valid type given, no need to retry
122
-				$this->logger->error($argument['type'] . ' is no valid type for user account data.');
123
-				$result = true;
124
-		}
125
-
126
-		if ($result === true || $try > $this->maxTry) {
127
-			$this->retainJob = false;
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * verify web page
133
-	 *
134
-	 * @param array $argument
135
-	 * @return bool true if we could check the verification code, otherwise false
136
-	 */
137
-	protected function verifyWebsite(array $argument) {
138
-		$result = false;
139
-
140
-		$url = rtrim($argument['data'], '/') . '/.well-known/' . 'CloudIdVerificationCode.txt';
141
-
142
-		$client = $this->httpClientService->newClient();
143
-		try {
144
-			$response = $client->get($url);
145
-		} catch (\Exception $e) {
146
-			return false;
147
-		}
148
-
149
-		if ($response->getStatusCode() === Http::STATUS_OK) {
150
-			$result = true;
151
-			$publishedCode = $response->getBody();
152
-			// remove new lines and spaces
153
-			$publishedCodeSanitized = trim(preg_replace('/\s\s+/', ' ', $publishedCode));
154
-			$user = $this->userManager->get($argument['uid']);
155
-			// we don't check a valid user -> give up
156
-			if ($user === null) {
157
-				$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
158
-				return $result;
159
-			}
160
-			$userAccount = $this->accountManager->getAccount($user);
161
-			$websiteProp = $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE);
162
-			$websiteProp->setVerified($publishedCodeSanitized === $argument['verificationCode']
163
-				? IAccountManager::VERIFIED
164
-				: IAccountManager::NOT_VERIFIED
165
-			);
166
-			$this->accountManager->updateAccount($userAccount);
167
-		}
168
-
169
-		return $result;
170
-	}
171
-
172
-	protected function verifyViaLookupServer(array $argument, string $dataType): bool {
173
-		if (empty($this->lookupServerUrl) ||
174
-			$this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes') !== 'yes' ||
175
-			$this->config->getSystemValue('has_internet_connection', true) === false) {
176
-			return false;
177
-		}
178
-
179
-		$user = $this->userManager->get($argument['uid']);
180
-
181
-		// we don't check a valid user -> give up
182
-		if ($user === null) {
183
-			$this->logger->info($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
184
-			return true;
185
-		}
186
-
187
-		$cloudId = $user->getCloudId();
188
-		$lookupServerData = $this->queryLookupServer($cloudId);
189
-
190
-		// for some reasons we couldn't read any data from the lookup server, try again later
191
-		if (empty($lookupServerData) || empty($lookupServerData[$dataType])) {
192
-			return false;
193
-		}
194
-
195
-		// lookup server has verification data for wrong user data (e.g. email address), try again later
196
-		if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
197
-			return false;
198
-		}
199
-
200
-		// lookup server hasn't verified the email address so far, try again later
201
-		if ($lookupServerData[$dataType]['verified'] === IAccountManager::NOT_VERIFIED) {
202
-			return false;
203
-		}
204
-
205
-		try {
206
-			$userAccount = $this->accountManager->getAccount($user);
207
-			$property = $userAccount->getProperty($dataType);
208
-			$property->setVerified(IAccountManager::VERIFIED);
209
-			$this->accountManager->updateAccount($userAccount);
210
-		} catch (PropertyDoesNotExistException $e) {
211
-			return false;
212
-		}
213
-
214
-		return true;
215
-	}
216
-
217
-	/**
218
-	 * @param string $cloudId
219
-	 * @return array
220
-	 */
221
-	protected function queryLookupServer($cloudId) {
222
-		try {
223
-			$client = $this->httpClientService->newClient();
224
-			$response = $client->get(
225
-				$this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
226
-				[
227
-					'timeout' => 10,
228
-					'connect_timeout' => 3,
229
-				]
230
-			);
231
-
232
-			$body = json_decode($response->getBody(), true);
233
-
234
-			if (is_array($body) && isset($body['federationId']) && $body['federationId'] === $cloudId) {
235
-				return $body;
236
-			}
237
-		} catch (\Exception $e) {
238
-			// do nothing, we will just re-try later
239
-		}
240
-
241
-		return [];
242
-	}
243
-
244
-	/**
245
-	 * re-add background job with new arguments
246
-	 *
247
-	 * @param IJobList $jobList
248
-	 * @param array $argument
249
-	 */
250
-	protected function reAddJob(IJobList $jobList, array $argument) {
251
-		$jobList->add(VerifyUserData::class,
252
-			[
253
-				'verificationCode' => $argument['verificationCode'],
254
-				'data' => $argument['data'],
255
-				'type' => $argument['type'],
256
-				'uid' => $argument['uid'],
257
-				'try' => (int)$argument['try'] + 1,
258
-				'lastRun' => time()
259
-			]
260
-		);
261
-	}
262
-
263
-	/**
264
-	 * test if it is time for the next run
265
-	 *
266
-	 * @param array $argument
267
-	 * @return bool
268
-	 */
269
-	protected function shouldRun(array $argument) {
270
-		$lastRun = (int)$argument['lastRun'];
271
-		return ((time() - $lastRun) > $this->interval);
272
-	}
273
-
274
-
275
-	/**
276
-	 * reset verification state after max tries are reached
277
-	 */
278
-	protected function resetVerificationState(): void {
279
-		$user = $this->userManager->get($this->argument['uid']);
280
-		if ($user !== null) {
281
-			$userAccount = $this->accountManager->getAccount($user);
282
-			try {
283
-				$property = $userAccount->getProperty($this->argument['type']);
284
-				$property->setVerified(IAccountManager::NOT_VERIFIED);
285
-				$this->accountManager->updateAccount($userAccount);
286
-			} catch (PropertyDoesNotExistException $e) {
287
-				return;
288
-			}
289
-		}
290
-	}
46
+    /** @var  bool */
47
+    private $retainJob = true;
48
+
49
+    /** @var int max number of attempts to send the request */
50
+    private $maxTry = 24;
51
+
52
+    /** @var int how much time should be between two tries (1 hour) */
53
+    private $interval = 3600;
54
+
55
+    /** @var IAccountManager */
56
+    private $accountManager;
57
+
58
+    /** @var IUserManager */
59
+    private $userManager;
60
+
61
+    /** @var IClientService */
62
+    private $httpClientService;
63
+
64
+    /** @var ILogger */
65
+    private $logger;
66
+
67
+    /** @var string */
68
+    private $lookupServerUrl;
69
+
70
+    /** @var IConfig */
71
+    private $config;
72
+
73
+    public function __construct(IAccountManager $accountManager,
74
+                                IUserManager $userManager,
75
+                                IClientService $clientService,
76
+                                ILogger $logger,
77
+                                ITimeFactory $timeFactory,
78
+                                IConfig $config
79
+    ) {
80
+        parent::__construct($timeFactory);
81
+        $this->accountManager = $accountManager;
82
+        $this->userManager = $userManager;
83
+        $this->httpClientService = $clientService;
84
+        $this->logger = $logger;
85
+
86
+        $lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
87
+        $this->lookupServerUrl = rtrim($lookupServerUrl, '/');
88
+        $this->config = $config;
89
+    }
90
+
91
+    /**
92
+     * run the job, then remove it from the jobList
93
+     *
94
+     * @param IJobList $jobList
95
+     * @param ILogger|null $logger
96
+     */
97
+    public function execute(IJobList $jobList, ILogger $logger = null) {
98
+        if ($this->shouldRun($this->argument)) {
99
+            parent::execute($jobList, $logger);
100
+            $jobList->remove($this, $this->argument);
101
+            if ($this->retainJob) {
102
+                $this->reAddJob($jobList, $this->argument);
103
+            } else {
104
+                $this->resetVerificationState();
105
+            }
106
+        }
107
+    }
108
+
109
+    protected function run($argument) {
110
+        $try = (int)$argument['try'] + 1;
111
+
112
+        switch ($argument['type']) {
113
+            case IAccountManager::PROPERTY_WEBSITE:
114
+                $result = $this->verifyWebsite($argument);
115
+                break;
116
+            case IAccountManager::PROPERTY_TWITTER:
117
+            case IAccountManager::PROPERTY_EMAIL:
118
+                $result = $this->verifyViaLookupServer($argument, $argument['type']);
119
+                break;
120
+            default:
121
+                // no valid type given, no need to retry
122
+                $this->logger->error($argument['type'] . ' is no valid type for user account data.');
123
+                $result = true;
124
+        }
125
+
126
+        if ($result === true || $try > $this->maxTry) {
127
+            $this->retainJob = false;
128
+        }
129
+    }
130
+
131
+    /**
132
+     * verify web page
133
+     *
134
+     * @param array $argument
135
+     * @return bool true if we could check the verification code, otherwise false
136
+     */
137
+    protected function verifyWebsite(array $argument) {
138
+        $result = false;
139
+
140
+        $url = rtrim($argument['data'], '/') . '/.well-known/' . 'CloudIdVerificationCode.txt';
141
+
142
+        $client = $this->httpClientService->newClient();
143
+        try {
144
+            $response = $client->get($url);
145
+        } catch (\Exception $e) {
146
+            return false;
147
+        }
148
+
149
+        if ($response->getStatusCode() === Http::STATUS_OK) {
150
+            $result = true;
151
+            $publishedCode = $response->getBody();
152
+            // remove new lines and spaces
153
+            $publishedCodeSanitized = trim(preg_replace('/\s\s+/', ' ', $publishedCode));
154
+            $user = $this->userManager->get($argument['uid']);
155
+            // we don't check a valid user -> give up
156
+            if ($user === null) {
157
+                $this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
158
+                return $result;
159
+            }
160
+            $userAccount = $this->accountManager->getAccount($user);
161
+            $websiteProp = $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE);
162
+            $websiteProp->setVerified($publishedCodeSanitized === $argument['verificationCode']
163
+                ? IAccountManager::VERIFIED
164
+                : IAccountManager::NOT_VERIFIED
165
+            );
166
+            $this->accountManager->updateAccount($userAccount);
167
+        }
168
+
169
+        return $result;
170
+    }
171
+
172
+    protected function verifyViaLookupServer(array $argument, string $dataType): bool {
173
+        if (empty($this->lookupServerUrl) ||
174
+            $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes') !== 'yes' ||
175
+            $this->config->getSystemValue('has_internet_connection', true) === false) {
176
+            return false;
177
+        }
178
+
179
+        $user = $this->userManager->get($argument['uid']);
180
+
181
+        // we don't check a valid user -> give up
182
+        if ($user === null) {
183
+            $this->logger->info($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
184
+            return true;
185
+        }
186
+
187
+        $cloudId = $user->getCloudId();
188
+        $lookupServerData = $this->queryLookupServer($cloudId);
189
+
190
+        // for some reasons we couldn't read any data from the lookup server, try again later
191
+        if (empty($lookupServerData) || empty($lookupServerData[$dataType])) {
192
+            return false;
193
+        }
194
+
195
+        // lookup server has verification data for wrong user data (e.g. email address), try again later
196
+        if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
197
+            return false;
198
+        }
199
+
200
+        // lookup server hasn't verified the email address so far, try again later
201
+        if ($lookupServerData[$dataType]['verified'] === IAccountManager::NOT_VERIFIED) {
202
+            return false;
203
+        }
204
+
205
+        try {
206
+            $userAccount = $this->accountManager->getAccount($user);
207
+            $property = $userAccount->getProperty($dataType);
208
+            $property->setVerified(IAccountManager::VERIFIED);
209
+            $this->accountManager->updateAccount($userAccount);
210
+        } catch (PropertyDoesNotExistException $e) {
211
+            return false;
212
+        }
213
+
214
+        return true;
215
+    }
216
+
217
+    /**
218
+     * @param string $cloudId
219
+     * @return array
220
+     */
221
+    protected function queryLookupServer($cloudId) {
222
+        try {
223
+            $client = $this->httpClientService->newClient();
224
+            $response = $client->get(
225
+                $this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
226
+                [
227
+                    'timeout' => 10,
228
+                    'connect_timeout' => 3,
229
+                ]
230
+            );
231
+
232
+            $body = json_decode($response->getBody(), true);
233
+
234
+            if (is_array($body) && isset($body['federationId']) && $body['federationId'] === $cloudId) {
235
+                return $body;
236
+            }
237
+        } catch (\Exception $e) {
238
+            // do nothing, we will just re-try later
239
+        }
240
+
241
+        return [];
242
+    }
243
+
244
+    /**
245
+     * re-add background job with new arguments
246
+     *
247
+     * @param IJobList $jobList
248
+     * @param array $argument
249
+     */
250
+    protected function reAddJob(IJobList $jobList, array $argument) {
251
+        $jobList->add(VerifyUserData::class,
252
+            [
253
+                'verificationCode' => $argument['verificationCode'],
254
+                'data' => $argument['data'],
255
+                'type' => $argument['type'],
256
+                'uid' => $argument['uid'],
257
+                'try' => (int)$argument['try'] + 1,
258
+                'lastRun' => time()
259
+            ]
260
+        );
261
+    }
262
+
263
+    /**
264
+     * test if it is time for the next run
265
+     *
266
+     * @param array $argument
267
+     * @return bool
268
+     */
269
+    protected function shouldRun(array $argument) {
270
+        $lastRun = (int)$argument['lastRun'];
271
+        return ((time() - $lastRun) > $this->interval);
272
+    }
273
+
274
+
275
+    /**
276
+     * reset verification state after max tries are reached
277
+     */
278
+    protected function resetVerificationState(): void {
279
+        $user = $this->userManager->get($this->argument['uid']);
280
+        if ($user !== null) {
281
+            $userAccount = $this->accountManager->getAccount($user);
282
+            try {
283
+                $property = $userAccount->getProperty($this->argument['type']);
284
+                $property->setVerified(IAccountManager::NOT_VERIFIED);
285
+                $this->accountManager->updateAccount($userAccount);
286
+            } catch (PropertyDoesNotExistException $e) {
287
+                return;
288
+            }
289
+        }
290
+    }
291 291
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 	}
108 108
 
109 109
 	protected function run($argument) {
110
-		$try = (int)$argument['try'] + 1;
110
+		$try = (int) $argument['try'] + 1;
111 111
 
112 112
 		switch ($argument['type']) {
113 113
 			case IAccountManager::PROPERTY_WEBSITE:
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 				break;
120 120
 			default:
121 121
 				// no valid type given, no need to retry
122
-				$this->logger->error($argument['type'] . ' is no valid type for user account data.');
122
+				$this->logger->error($argument['type'].' is no valid type for user account data.');
123 123
 				$result = true;
124 124
 		}
125 125
 
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	protected function verifyWebsite(array $argument) {
138 138
 		$result = false;
139 139
 
140
-		$url = rtrim($argument['data'], '/') . '/.well-known/' . 'CloudIdVerificationCode.txt';
140
+		$url = rtrim($argument['data'], '/').'/.well-known/'.'CloudIdVerificationCode.txt';
141 141
 
142 142
 		$client = $this->httpClientService->newClient();
143 143
 		try {
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 			$user = $this->userManager->get($argument['uid']);
155 155
 			// we don't check a valid user -> give up
156 156
 			if ($user === null) {
157
-				$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
157
+				$this->logger->error($argument['uid'].' doesn\'t exist, can\'t verify user data.');
158 158
 				return $result;
159 159
 			}
160 160
 			$userAccount = $this->accountManager->getAccount($user);
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 
181 181
 		// we don't check a valid user -> give up
182 182
 		if ($user === null) {
183
-			$this->logger->info($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
183
+			$this->logger->info($argument['uid'].' doesn\'t exist, can\'t verify user data.');
184 184
 			return true;
185 185
 		}
186 186
 
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 		try {
223 223
 			$client = $this->httpClientService->newClient();
224 224
 			$response = $client->get(
225
-				$this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
225
+				$this->lookupServerUrl.'/users?search='.urlencode($cloudId).'&exactCloudId=1',
226 226
 				[
227 227
 					'timeout' => 10,
228 228
 					'connect_timeout' => 3,
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 				'data' => $argument['data'],
255 255
 				'type' => $argument['type'],
256 256
 				'uid' => $argument['uid'],
257
-				'try' => (int)$argument['try'] + 1,
257
+				'try' => (int) $argument['try'] + 1,
258 258
 				'lastRun' => time()
259 259
 			]
260 260
 		);
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 	 * @return bool
268 268
 	 */
269 269
 	protected function shouldRun(array $argument) {
270
-		$lastRun = (int)$argument['lastRun'];
270
+		$lastRun = (int) $argument['lastRun'];
271 271
 		return ((time() - $lastRun) > $this->interval);
272 272
 	}
273 273
 
Please login to merge, or discard this patch.