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