@@ -16,547 +16,547 @@ |
||
16 | 16 | require __DIR__ . '/../../vendor/autoload.php'; |
17 | 17 | |
18 | 18 | trait BasicStructure { |
19 | - use Auth; |
|
20 | - use Avatar; |
|
21 | - use Download; |
|
22 | - use Mail; |
|
23 | - use Theming; |
|
24 | - |
|
25 | - /** @var string */ |
|
26 | - private $currentUser = ''; |
|
27 | - |
|
28 | - /** @var string */ |
|
29 | - private $currentServer = ''; |
|
30 | - |
|
31 | - /** @var string */ |
|
32 | - private $baseUrl = ''; |
|
33 | - |
|
34 | - /** @var int */ |
|
35 | - private $apiVersion = 1; |
|
36 | - |
|
37 | - /** @var ResponseInterface */ |
|
38 | - private $response = null; |
|
39 | - |
|
40 | - /** @var CookieJar */ |
|
41 | - private $cookieJar; |
|
42 | - |
|
43 | - /** @var string */ |
|
44 | - private $requestToken; |
|
45 | - |
|
46 | - protected $adminUser; |
|
47 | - protected $regularUser; |
|
48 | - protected $localBaseUrl; |
|
49 | - protected $remoteBaseUrl; |
|
50 | - |
|
51 | - public function __construct($baseUrl, $admin, $regular_user_password) { |
|
52 | - // Initialize your context here |
|
53 | - $this->baseUrl = $baseUrl; |
|
54 | - $this->adminUser = $admin; |
|
55 | - $this->regularUser = $regular_user_password; |
|
56 | - $this->localBaseUrl = $this->baseUrl; |
|
57 | - $this->remoteBaseUrl = $this->baseUrl; |
|
58 | - $this->currentServer = 'LOCAL'; |
|
59 | - $this->cookieJar = new CookieJar(); |
|
60 | - |
|
61 | - // in case of ci deployment we take the server url from the environment |
|
62 | - $testServerUrl = getenv('TEST_SERVER_URL'); |
|
63 | - if ($testServerUrl !== false) { |
|
64 | - $this->baseUrl = $testServerUrl; |
|
65 | - $this->localBaseUrl = $testServerUrl; |
|
66 | - } |
|
67 | - |
|
68 | - // federated server url from the environment |
|
69 | - $testRemoteServerUrl = getenv('TEST_SERVER_FED_URL'); |
|
70 | - if ($testRemoteServerUrl !== false) { |
|
71 | - $this->remoteBaseUrl = $testRemoteServerUrl; |
|
72 | - } |
|
73 | - } |
|
74 | - |
|
75 | - /** |
|
76 | - * @Given /^using api version "(\d+)"$/ |
|
77 | - * @param string $version |
|
78 | - */ |
|
79 | - public function usingApiVersion($version) { |
|
80 | - $this->apiVersion = (int)$version; |
|
81 | - } |
|
82 | - |
|
83 | - /** |
|
84 | - * @Given /^As an "([^"]*)"$/ |
|
85 | - * @param string $user |
|
86 | - */ |
|
87 | - public function asAn($user) { |
|
88 | - $this->currentUser = $user; |
|
89 | - } |
|
90 | - |
|
91 | - /** |
|
92 | - * @Given /^Using server "(LOCAL|REMOTE)"$/ |
|
93 | - * @param string $server |
|
94 | - * @return string Previous used server |
|
95 | - */ |
|
96 | - public function usingServer($server) { |
|
97 | - $previousServer = $this->currentServer; |
|
98 | - if ($server === 'LOCAL') { |
|
99 | - $this->baseUrl = $this->localBaseUrl; |
|
100 | - $this->currentServer = 'LOCAL'; |
|
101 | - return $previousServer; |
|
102 | - } else { |
|
103 | - $this->baseUrl = $this->remoteBaseUrl; |
|
104 | - $this->currentServer = 'REMOTE'; |
|
105 | - return $previousServer; |
|
106 | - } |
|
107 | - } |
|
108 | - |
|
109 | - /** |
|
110 | - * @When /^sending "([^"]*)" to "([^"]*)"$/ |
|
111 | - * @param string $verb |
|
112 | - * @param string $url |
|
113 | - */ |
|
114 | - public function sendingTo($verb, $url) { |
|
115 | - $this->sendingToWith($verb, $url, null); |
|
116 | - } |
|
117 | - |
|
118 | - /** |
|
119 | - * Parses the xml answer to get ocs response which doesn't match with |
|
120 | - * http one in v1 of the api. |
|
121 | - * |
|
122 | - * @param ResponseInterface $response |
|
123 | - * @return string |
|
124 | - */ |
|
125 | - public function getOCSResponse($response) { |
|
126 | - $body = simplexml_load_string((string)$response->getBody()); |
|
127 | - if ($body === false) { |
|
128 | - throw new \RuntimeException('Could not parse OCS response, body is not valid XML'); |
|
129 | - } |
|
130 | - return $body->meta[0]->statuscode; |
|
131 | - } |
|
132 | - |
|
133 | - /** |
|
134 | - * This function is needed to use a vertical fashion in the gherkin tables. |
|
135 | - * |
|
136 | - * @param array $arrayOfArrays |
|
137 | - * @return array |
|
138 | - */ |
|
139 | - public function simplifyArray($arrayOfArrays) { |
|
140 | - $a = array_map(function ($subArray) { |
|
141 | - return $subArray[0]; |
|
142 | - }, $arrayOfArrays); |
|
143 | - return $a; |
|
144 | - } |
|
145 | - |
|
146 | - /** |
|
147 | - * @When /^sending "([^"]*)" to "([^"]*)" with$/ |
|
148 | - * @param string $verb |
|
149 | - * @param string $url |
|
150 | - * @param TableNode $body |
|
151 | - */ |
|
152 | - public function sendingToWith($verb, $url, $body) { |
|
153 | - $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php" . $url; |
|
154 | - $client = new Client(); |
|
155 | - $options = []; |
|
156 | - if ($this->currentUser === 'admin') { |
|
157 | - $options['auth'] = $this->adminUser; |
|
158 | - } elseif (strpos($this->currentUser, 'anonymous') !== 0) { |
|
159 | - $options['auth'] = [$this->currentUser, $this->regularUser]; |
|
160 | - } |
|
161 | - $options['headers'] = [ |
|
162 | - 'OCS-APIRequest' => 'true' |
|
163 | - ]; |
|
164 | - if ($body instanceof TableNode) { |
|
165 | - $fd = $body->getRowsHash(); |
|
166 | - $options['form_params'] = $fd; |
|
167 | - } |
|
168 | - |
|
169 | - // TODO: Fix this hack! |
|
170 | - if ($verb === 'PUT' && $body === null) { |
|
171 | - $options['form_params'] = [ |
|
172 | - 'foo' => 'bar', |
|
173 | - ]; |
|
174 | - } |
|
175 | - |
|
176 | - try { |
|
177 | - $this->response = $client->request($verb, $fullUrl, $options); |
|
178 | - } catch (ClientException $ex) { |
|
179 | - $this->response = $ex->getResponse(); |
|
180 | - } catch (ServerException $ex) { |
|
181 | - $this->response = $ex->getResponse(); |
|
182 | - } |
|
183 | - } |
|
184 | - |
|
185 | - /** |
|
186 | - * @param string $verb |
|
187 | - * @param string $url |
|
188 | - * @param TableNode|array|null $body |
|
189 | - * @param array $headers |
|
190 | - */ |
|
191 | - protected function sendRequestForJSON(string $verb, string $url, $body = null, array $headers = []): void { |
|
192 | - $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php" . $url; |
|
193 | - $client = new Client(); |
|
194 | - $options = []; |
|
195 | - if ($this->currentUser === 'admin') { |
|
196 | - $options['auth'] = ['admin', 'admin']; |
|
197 | - } elseif (strpos($this->currentUser, 'anonymous') !== 0) { |
|
198 | - $options['auth'] = [$this->currentUser, $this->regularUser]; |
|
199 | - } |
|
200 | - if ($body instanceof TableNode) { |
|
201 | - $fd = $body->getRowsHash(); |
|
202 | - $options['form_params'] = $fd; |
|
203 | - } elseif (is_array($body)) { |
|
204 | - $options['form_params'] = $body; |
|
205 | - } |
|
206 | - |
|
207 | - $options['headers'] = array_merge($headers, [ |
|
208 | - 'OCS-ApiRequest' => 'true', |
|
209 | - 'Accept' => 'application/json', |
|
210 | - ]); |
|
211 | - |
|
212 | - try { |
|
213 | - $this->response = $client->{$verb}($fullUrl, $options); |
|
214 | - } catch (ClientException $ex) { |
|
215 | - $this->response = $ex->getResponse(); |
|
216 | - } |
|
217 | - } |
|
218 | - |
|
219 | - /** |
|
220 | - * @When /^sending "([^"]*)" with exact url to "([^"]*)"$/ |
|
221 | - * @param string $verb |
|
222 | - * @param string $url |
|
223 | - */ |
|
224 | - public function sendingToDirectUrl($verb, $url) { |
|
225 | - $this->sendingToWithDirectUrl($verb, $url, null); |
|
226 | - } |
|
227 | - |
|
228 | - public function sendingToWithDirectUrl($verb, $url, $body) { |
|
229 | - $fullUrl = substr($this->baseUrl, 0, -5) . $url; |
|
230 | - $client = new Client(); |
|
231 | - $options = []; |
|
232 | - if ($this->currentUser === 'admin') { |
|
233 | - $options['auth'] = $this->adminUser; |
|
234 | - } elseif (strpos($this->currentUser, 'anonymous') !== 0) { |
|
235 | - $options['auth'] = [$this->currentUser, $this->regularUser]; |
|
236 | - } |
|
237 | - if ($body instanceof TableNode) { |
|
238 | - $fd = $body->getRowsHash(); |
|
239 | - $options['form_params'] = $fd; |
|
240 | - } |
|
241 | - |
|
242 | - try { |
|
243 | - $this->response = $client->request($verb, $fullUrl, $options); |
|
244 | - } catch (ClientException $ex) { |
|
245 | - $this->response = $ex->getResponse(); |
|
246 | - } |
|
247 | - } |
|
248 | - |
|
249 | - public function isExpectedUrl($possibleUrl, $finalPart) { |
|
250 | - $baseUrlChopped = substr($this->baseUrl, 0, -4); |
|
251 | - $endCharacter = strlen($baseUrlChopped) + strlen($finalPart); |
|
252 | - return (substr($possibleUrl, 0, $endCharacter) == "$baseUrlChopped" . "$finalPart"); |
|
253 | - } |
|
254 | - |
|
255 | - /** |
|
256 | - * @Then /^the OCS status code should be "([^"]*)"$/ |
|
257 | - * @param int $statusCode |
|
258 | - */ |
|
259 | - public function theOCSStatusCodeShouldBe($statusCode) { |
|
260 | - Assert::assertEquals($statusCode, $this->getOCSResponse($this->response)); |
|
261 | - } |
|
262 | - |
|
263 | - /** |
|
264 | - * @Then /^the HTTP status code should be "([^"]*)"$/ |
|
265 | - * @param int $statusCode |
|
266 | - */ |
|
267 | - public function theHTTPStatusCodeShouldBe($statusCode) { |
|
268 | - Assert::assertEquals($statusCode, $this->response->getStatusCode()); |
|
269 | - } |
|
270 | - |
|
271 | - /** |
|
272 | - * @Then /^the Content-Type should be "([^"]*)"$/ |
|
273 | - * @param string $contentType |
|
274 | - */ |
|
275 | - public function theContentTypeShouldbe($contentType) { |
|
276 | - Assert::assertEquals($contentType, $this->response->getHeader('Content-Type')[0]); |
|
277 | - } |
|
278 | - |
|
279 | - /** |
|
280 | - * @param ResponseInterface $response |
|
281 | - */ |
|
282 | - private function extracRequestTokenFromResponse(ResponseInterface $response) { |
|
283 | - $this->requestToken = substr(preg_replace('/(.*)data-requesttoken="(.*)">(.*)/sm', '\2', $response->getBody()->getContents()), 0, 89); |
|
284 | - } |
|
285 | - |
|
286 | - /** |
|
287 | - * @Given Logging in using web as :user |
|
288 | - * @param string $user |
|
289 | - */ |
|
290 | - public function loggingInUsingWebAs($user) { |
|
291 | - $baseUrl = substr($this->baseUrl, 0, -5); |
|
292 | - $loginUrl = $baseUrl . '/index.php/login'; |
|
293 | - // Request a new session and extract CSRF token |
|
294 | - $client = new Client(); |
|
295 | - $response = $client->get( |
|
296 | - $loginUrl, |
|
297 | - [ |
|
298 | - 'cookies' => $this->cookieJar, |
|
299 | - ] |
|
300 | - ); |
|
301 | - $this->extracRequestTokenFromResponse($response); |
|
302 | - |
|
303 | - // Login and extract new token |
|
304 | - $password = ($user === 'admin') ? 'admin' : '123456'; |
|
305 | - $client = new Client(); |
|
306 | - $response = $client->post( |
|
307 | - $loginUrl, |
|
308 | - [ |
|
309 | - 'form_params' => [ |
|
310 | - 'user' => $user, |
|
311 | - 'password' => $password, |
|
312 | - 'requesttoken' => $this->requestToken, |
|
313 | - ], |
|
314 | - 'cookies' => $this->cookieJar, |
|
315 | - 'headers' => [ |
|
316 | - 'Origin' => $baseUrl, |
|
317 | - ], |
|
318 | - ] |
|
319 | - ); |
|
320 | - $this->extracRequestTokenFromResponse($response); |
|
321 | - } |
|
322 | - |
|
323 | - /** |
|
324 | - * @When Sending a :method to :url with requesttoken |
|
325 | - * @param string $method |
|
326 | - * @param string $url |
|
327 | - * @param TableNode|array|null $body |
|
328 | - */ |
|
329 | - public function sendingAToWithRequesttoken($method, $url, $body = null) { |
|
330 | - $baseUrl = substr($this->baseUrl, 0, -5); |
|
331 | - |
|
332 | - $options = [ |
|
333 | - 'cookies' => $this->cookieJar, |
|
334 | - 'headers' => [ |
|
335 | - 'requesttoken' => $this->requestToken |
|
336 | - ], |
|
337 | - ]; |
|
338 | - |
|
339 | - if ($body instanceof TableNode) { |
|
340 | - $fd = $body->getRowsHash(); |
|
341 | - $options['form_params'] = $fd; |
|
342 | - } elseif ($body) { |
|
343 | - $options = array_merge_recursive($options, $body); |
|
344 | - } |
|
345 | - |
|
346 | - $client = new Client(); |
|
347 | - try { |
|
348 | - $this->response = $client->request( |
|
349 | - $method, |
|
350 | - $baseUrl . $url, |
|
351 | - $options |
|
352 | - ); |
|
353 | - } catch (ClientException $e) { |
|
354 | - $this->response = $e->getResponse(); |
|
355 | - } |
|
356 | - } |
|
357 | - |
|
358 | - /** |
|
359 | - * @When Sending a :method to :url without requesttoken |
|
360 | - * @param string $method |
|
361 | - * @param string $url |
|
362 | - */ |
|
363 | - public function sendingAToWithoutRequesttoken($method, $url) { |
|
364 | - $baseUrl = substr($this->baseUrl, 0, -5); |
|
365 | - |
|
366 | - $client = new Client(); |
|
367 | - try { |
|
368 | - $this->response = $client->request( |
|
369 | - $method, |
|
370 | - $baseUrl . $url, |
|
371 | - [ |
|
372 | - 'cookies' => $this->cookieJar |
|
373 | - ] |
|
374 | - ); |
|
375 | - } catch (ClientException $e) { |
|
376 | - $this->response = $e->getResponse(); |
|
377 | - } |
|
378 | - } |
|
379 | - |
|
380 | - public static function removeFile($path, $filename) { |
|
381 | - if (file_exists("$path" . "$filename")) { |
|
382 | - unlink("$path" . "$filename"); |
|
383 | - } |
|
384 | - } |
|
385 | - |
|
386 | - /** |
|
387 | - * @Given User :user modifies text of :filename with text :text |
|
388 | - * @param string $user |
|
389 | - * @param string $filename |
|
390 | - * @param string $text |
|
391 | - */ |
|
392 | - public function modifyTextOfFile($user, $filename, $text) { |
|
393 | - self::removeFile($this->getDataDirectory() . "/$user/files", "$filename"); |
|
394 | - file_put_contents($this->getDataDirectory() . "/$user/files" . "$filename", "$text"); |
|
395 | - } |
|
396 | - |
|
397 | - private function getDataDirectory() { |
|
398 | - // Based on "runOcc" from CommandLine trait |
|
399 | - $args = ['config:system:get', 'datadirectory']; |
|
400 | - $args = array_map(function ($arg) { |
|
401 | - return escapeshellarg($arg); |
|
402 | - }, $args); |
|
403 | - $args[] = '--no-ansi --no-warnings'; |
|
404 | - $args = implode(' ', $args); |
|
405 | - |
|
406 | - $descriptor = [ |
|
407 | - 0 => ['pipe', 'r'], |
|
408 | - 1 => ['pipe', 'w'], |
|
409 | - 2 => ['pipe', 'w'], |
|
410 | - ]; |
|
411 | - $process = proc_open('php console.php ' . $args, $descriptor, $pipes, $ocPath = '../..'); |
|
412 | - $lastStdOut = stream_get_contents($pipes[1]); |
|
413 | - proc_close($process); |
|
414 | - |
|
415 | - return trim($lastStdOut); |
|
416 | - } |
|
417 | - |
|
418 | - /** |
|
419 | - * @Given file :filename is created :times times in :user user data |
|
420 | - * @param string $filename |
|
421 | - * @param string $times |
|
422 | - * @param string $user |
|
423 | - */ |
|
424 | - public function fileIsCreatedTimesInUserData($filename, $times, $user) { |
|
425 | - for ($i = 0; $i < $times; $i++) { |
|
426 | - file_put_contents($this->getDataDirectory() . "/$user/files" . "$filename-$i", "content-$i"); |
|
427 | - } |
|
428 | - } |
|
429 | - |
|
430 | - public function createFileSpecificSize($name, $size) { |
|
431 | - $file = fopen('work/' . "$name", 'w'); |
|
432 | - fseek($file, $size - 1, SEEK_CUR); |
|
433 | - fwrite($file, 'a'); // write a dummy char at SIZE position |
|
434 | - fclose($file); |
|
435 | - } |
|
436 | - |
|
437 | - public function createFileWithText($name, $text) { |
|
438 | - $file = fopen('work/' . "$name", 'w'); |
|
439 | - fwrite($file, $text); |
|
440 | - fclose($file); |
|
441 | - } |
|
442 | - |
|
443 | - /** |
|
444 | - * @Given file :filename of size :size is created in local storage |
|
445 | - * @param string $filename |
|
446 | - * @param string $size |
|
447 | - */ |
|
448 | - public function fileIsCreatedInLocalStorageWithSize($filename, $size) { |
|
449 | - $this->createFileSpecificSize("local_storage/$filename", $size); |
|
450 | - } |
|
451 | - |
|
452 | - /** |
|
453 | - * @Given file :filename with text :text is created in local storage |
|
454 | - * @param string $filename |
|
455 | - * @param string $text |
|
456 | - */ |
|
457 | - public function fileIsCreatedInLocalStorageWithText($filename, $text) { |
|
458 | - $this->createFileWithText("local_storage/$filename", $text); |
|
459 | - } |
|
460 | - |
|
461 | - /** |
|
462 | - * @When Sleep for :seconds seconds |
|
463 | - * @param int $seconds |
|
464 | - */ |
|
465 | - public function sleepForSeconds($seconds) { |
|
466 | - sleep((int)$seconds); |
|
467 | - } |
|
468 | - |
|
469 | - /** |
|
470 | - * @BeforeSuite |
|
471 | - */ |
|
472 | - public static function addFilesToSkeleton() { |
|
473 | - for ($i = 0; $i < 5; $i++) { |
|
474 | - file_put_contents('../../core/skeleton/' . 'textfile' . "$i" . '.txt', "Nextcloud test text file\n"); |
|
475 | - } |
|
476 | - if (!file_exists('../../core/skeleton/FOLDER')) { |
|
477 | - mkdir('../../core/skeleton/FOLDER', 0777, true); |
|
478 | - } |
|
479 | - if (!file_exists('../../core/skeleton/PARENT')) { |
|
480 | - mkdir('../../core/skeleton/PARENT', 0777, true); |
|
481 | - } |
|
482 | - file_put_contents('../../core/skeleton/PARENT/' . 'parent.txt', "Nextcloud test text file\n"); |
|
483 | - if (!file_exists('../../core/skeleton/PARENT/CHILD')) { |
|
484 | - mkdir('../../core/skeleton/PARENT/CHILD', 0777, true); |
|
485 | - } |
|
486 | - file_put_contents('../../core/skeleton/PARENT/CHILD/' . 'child.txt', "Nextcloud test text file\n"); |
|
487 | - } |
|
488 | - |
|
489 | - /** |
|
490 | - * @AfterSuite |
|
491 | - */ |
|
492 | - public static function removeFilesFromSkeleton() { |
|
493 | - for ($i = 0; $i < 5; $i++) { |
|
494 | - self::removeFile('../../core/skeleton/', 'textfile' . "$i" . '.txt'); |
|
495 | - } |
|
496 | - if (is_dir('../../core/skeleton/FOLDER')) { |
|
497 | - rmdir('../../core/skeleton/FOLDER'); |
|
498 | - } |
|
499 | - self::removeFile('../../core/skeleton/PARENT/CHILD/', 'child.txt'); |
|
500 | - if (is_dir('../../core/skeleton/PARENT/CHILD')) { |
|
501 | - rmdir('../../core/skeleton/PARENT/CHILD'); |
|
502 | - } |
|
503 | - self::removeFile('../../core/skeleton/PARENT/', 'parent.txt'); |
|
504 | - if (is_dir('../../core/skeleton/PARENT')) { |
|
505 | - rmdir('../../core/skeleton/PARENT'); |
|
506 | - } |
|
507 | - } |
|
508 | - |
|
509 | - /** |
|
510 | - * @BeforeScenario @local_storage |
|
511 | - */ |
|
512 | - public static function removeFilesFromLocalStorageBefore() { |
|
513 | - $dir = './work/local_storage/'; |
|
514 | - $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); |
|
515 | - $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); |
|
516 | - foreach ($ri as $file) { |
|
517 | - $file->isDir() ? rmdir($file) : unlink($file); |
|
518 | - } |
|
519 | - } |
|
520 | - |
|
521 | - /** |
|
522 | - * @AfterScenario @local_storage |
|
523 | - */ |
|
524 | - public static function removeFilesFromLocalStorageAfter() { |
|
525 | - $dir = './work/local_storage/'; |
|
526 | - $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); |
|
527 | - $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); |
|
528 | - foreach ($ri as $file) { |
|
529 | - $file->isDir() ? rmdir($file) : unlink($file); |
|
530 | - } |
|
531 | - } |
|
532 | - |
|
533 | - /** |
|
534 | - * @Given /^cookies are reset$/ |
|
535 | - */ |
|
536 | - public function cookiesAreReset() { |
|
537 | - $this->cookieJar = new CookieJar(); |
|
538 | - } |
|
539 | - |
|
540 | - /** |
|
541 | - * @Then The following headers should be set |
|
542 | - * @param TableNode $table |
|
543 | - * @throws \Exception |
|
544 | - */ |
|
545 | - public function theFollowingHeadersShouldBeSet(TableNode $table) { |
|
546 | - foreach ($table->getTable() as $header) { |
|
547 | - $headerName = $header[0]; |
|
548 | - $expectedHeaderValue = $header[1]; |
|
549 | - $returnedHeader = $this->response->getHeader($headerName)[0]; |
|
550 | - if ($returnedHeader !== $expectedHeaderValue) { |
|
551 | - throw new \Exception( |
|
552 | - sprintf( |
|
553 | - "Expected value '%s' for header '%s', got '%s'", |
|
554 | - $expectedHeaderValue, |
|
555 | - $headerName, |
|
556 | - $returnedHeader |
|
557 | - ) |
|
558 | - ); |
|
559 | - } |
|
560 | - } |
|
561 | - } |
|
19 | + use Auth; |
|
20 | + use Avatar; |
|
21 | + use Download; |
|
22 | + use Mail; |
|
23 | + use Theming; |
|
24 | + |
|
25 | + /** @var string */ |
|
26 | + private $currentUser = ''; |
|
27 | + |
|
28 | + /** @var string */ |
|
29 | + private $currentServer = ''; |
|
30 | + |
|
31 | + /** @var string */ |
|
32 | + private $baseUrl = ''; |
|
33 | + |
|
34 | + /** @var int */ |
|
35 | + private $apiVersion = 1; |
|
36 | + |
|
37 | + /** @var ResponseInterface */ |
|
38 | + private $response = null; |
|
39 | + |
|
40 | + /** @var CookieJar */ |
|
41 | + private $cookieJar; |
|
42 | + |
|
43 | + /** @var string */ |
|
44 | + private $requestToken; |
|
45 | + |
|
46 | + protected $adminUser; |
|
47 | + protected $regularUser; |
|
48 | + protected $localBaseUrl; |
|
49 | + protected $remoteBaseUrl; |
|
50 | + |
|
51 | + public function __construct($baseUrl, $admin, $regular_user_password) { |
|
52 | + // Initialize your context here |
|
53 | + $this->baseUrl = $baseUrl; |
|
54 | + $this->adminUser = $admin; |
|
55 | + $this->regularUser = $regular_user_password; |
|
56 | + $this->localBaseUrl = $this->baseUrl; |
|
57 | + $this->remoteBaseUrl = $this->baseUrl; |
|
58 | + $this->currentServer = 'LOCAL'; |
|
59 | + $this->cookieJar = new CookieJar(); |
|
60 | + |
|
61 | + // in case of ci deployment we take the server url from the environment |
|
62 | + $testServerUrl = getenv('TEST_SERVER_URL'); |
|
63 | + if ($testServerUrl !== false) { |
|
64 | + $this->baseUrl = $testServerUrl; |
|
65 | + $this->localBaseUrl = $testServerUrl; |
|
66 | + } |
|
67 | + |
|
68 | + // federated server url from the environment |
|
69 | + $testRemoteServerUrl = getenv('TEST_SERVER_FED_URL'); |
|
70 | + if ($testRemoteServerUrl !== false) { |
|
71 | + $this->remoteBaseUrl = $testRemoteServerUrl; |
|
72 | + } |
|
73 | + } |
|
74 | + |
|
75 | + /** |
|
76 | + * @Given /^using api version "(\d+)"$/ |
|
77 | + * @param string $version |
|
78 | + */ |
|
79 | + public function usingApiVersion($version) { |
|
80 | + $this->apiVersion = (int)$version; |
|
81 | + } |
|
82 | + |
|
83 | + /** |
|
84 | + * @Given /^As an "([^"]*)"$/ |
|
85 | + * @param string $user |
|
86 | + */ |
|
87 | + public function asAn($user) { |
|
88 | + $this->currentUser = $user; |
|
89 | + } |
|
90 | + |
|
91 | + /** |
|
92 | + * @Given /^Using server "(LOCAL|REMOTE)"$/ |
|
93 | + * @param string $server |
|
94 | + * @return string Previous used server |
|
95 | + */ |
|
96 | + public function usingServer($server) { |
|
97 | + $previousServer = $this->currentServer; |
|
98 | + if ($server === 'LOCAL') { |
|
99 | + $this->baseUrl = $this->localBaseUrl; |
|
100 | + $this->currentServer = 'LOCAL'; |
|
101 | + return $previousServer; |
|
102 | + } else { |
|
103 | + $this->baseUrl = $this->remoteBaseUrl; |
|
104 | + $this->currentServer = 'REMOTE'; |
|
105 | + return $previousServer; |
|
106 | + } |
|
107 | + } |
|
108 | + |
|
109 | + /** |
|
110 | + * @When /^sending "([^"]*)" to "([^"]*)"$/ |
|
111 | + * @param string $verb |
|
112 | + * @param string $url |
|
113 | + */ |
|
114 | + public function sendingTo($verb, $url) { |
|
115 | + $this->sendingToWith($verb, $url, null); |
|
116 | + } |
|
117 | + |
|
118 | + /** |
|
119 | + * Parses the xml answer to get ocs response which doesn't match with |
|
120 | + * http one in v1 of the api. |
|
121 | + * |
|
122 | + * @param ResponseInterface $response |
|
123 | + * @return string |
|
124 | + */ |
|
125 | + public function getOCSResponse($response) { |
|
126 | + $body = simplexml_load_string((string)$response->getBody()); |
|
127 | + if ($body === false) { |
|
128 | + throw new \RuntimeException('Could not parse OCS response, body is not valid XML'); |
|
129 | + } |
|
130 | + return $body->meta[0]->statuscode; |
|
131 | + } |
|
132 | + |
|
133 | + /** |
|
134 | + * This function is needed to use a vertical fashion in the gherkin tables. |
|
135 | + * |
|
136 | + * @param array $arrayOfArrays |
|
137 | + * @return array |
|
138 | + */ |
|
139 | + public function simplifyArray($arrayOfArrays) { |
|
140 | + $a = array_map(function ($subArray) { |
|
141 | + return $subArray[0]; |
|
142 | + }, $arrayOfArrays); |
|
143 | + return $a; |
|
144 | + } |
|
145 | + |
|
146 | + /** |
|
147 | + * @When /^sending "([^"]*)" to "([^"]*)" with$/ |
|
148 | + * @param string $verb |
|
149 | + * @param string $url |
|
150 | + * @param TableNode $body |
|
151 | + */ |
|
152 | + public function sendingToWith($verb, $url, $body) { |
|
153 | + $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php" . $url; |
|
154 | + $client = new Client(); |
|
155 | + $options = []; |
|
156 | + if ($this->currentUser === 'admin') { |
|
157 | + $options['auth'] = $this->adminUser; |
|
158 | + } elseif (strpos($this->currentUser, 'anonymous') !== 0) { |
|
159 | + $options['auth'] = [$this->currentUser, $this->regularUser]; |
|
160 | + } |
|
161 | + $options['headers'] = [ |
|
162 | + 'OCS-APIRequest' => 'true' |
|
163 | + ]; |
|
164 | + if ($body instanceof TableNode) { |
|
165 | + $fd = $body->getRowsHash(); |
|
166 | + $options['form_params'] = $fd; |
|
167 | + } |
|
168 | + |
|
169 | + // TODO: Fix this hack! |
|
170 | + if ($verb === 'PUT' && $body === null) { |
|
171 | + $options['form_params'] = [ |
|
172 | + 'foo' => 'bar', |
|
173 | + ]; |
|
174 | + } |
|
175 | + |
|
176 | + try { |
|
177 | + $this->response = $client->request($verb, $fullUrl, $options); |
|
178 | + } catch (ClientException $ex) { |
|
179 | + $this->response = $ex->getResponse(); |
|
180 | + } catch (ServerException $ex) { |
|
181 | + $this->response = $ex->getResponse(); |
|
182 | + } |
|
183 | + } |
|
184 | + |
|
185 | + /** |
|
186 | + * @param string $verb |
|
187 | + * @param string $url |
|
188 | + * @param TableNode|array|null $body |
|
189 | + * @param array $headers |
|
190 | + */ |
|
191 | + protected function sendRequestForJSON(string $verb, string $url, $body = null, array $headers = []): void { |
|
192 | + $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php" . $url; |
|
193 | + $client = new Client(); |
|
194 | + $options = []; |
|
195 | + if ($this->currentUser === 'admin') { |
|
196 | + $options['auth'] = ['admin', 'admin']; |
|
197 | + } elseif (strpos($this->currentUser, 'anonymous') !== 0) { |
|
198 | + $options['auth'] = [$this->currentUser, $this->regularUser]; |
|
199 | + } |
|
200 | + if ($body instanceof TableNode) { |
|
201 | + $fd = $body->getRowsHash(); |
|
202 | + $options['form_params'] = $fd; |
|
203 | + } elseif (is_array($body)) { |
|
204 | + $options['form_params'] = $body; |
|
205 | + } |
|
206 | + |
|
207 | + $options['headers'] = array_merge($headers, [ |
|
208 | + 'OCS-ApiRequest' => 'true', |
|
209 | + 'Accept' => 'application/json', |
|
210 | + ]); |
|
211 | + |
|
212 | + try { |
|
213 | + $this->response = $client->{$verb}($fullUrl, $options); |
|
214 | + } catch (ClientException $ex) { |
|
215 | + $this->response = $ex->getResponse(); |
|
216 | + } |
|
217 | + } |
|
218 | + |
|
219 | + /** |
|
220 | + * @When /^sending "([^"]*)" with exact url to "([^"]*)"$/ |
|
221 | + * @param string $verb |
|
222 | + * @param string $url |
|
223 | + */ |
|
224 | + public function sendingToDirectUrl($verb, $url) { |
|
225 | + $this->sendingToWithDirectUrl($verb, $url, null); |
|
226 | + } |
|
227 | + |
|
228 | + public function sendingToWithDirectUrl($verb, $url, $body) { |
|
229 | + $fullUrl = substr($this->baseUrl, 0, -5) . $url; |
|
230 | + $client = new Client(); |
|
231 | + $options = []; |
|
232 | + if ($this->currentUser === 'admin') { |
|
233 | + $options['auth'] = $this->adminUser; |
|
234 | + } elseif (strpos($this->currentUser, 'anonymous') !== 0) { |
|
235 | + $options['auth'] = [$this->currentUser, $this->regularUser]; |
|
236 | + } |
|
237 | + if ($body instanceof TableNode) { |
|
238 | + $fd = $body->getRowsHash(); |
|
239 | + $options['form_params'] = $fd; |
|
240 | + } |
|
241 | + |
|
242 | + try { |
|
243 | + $this->response = $client->request($verb, $fullUrl, $options); |
|
244 | + } catch (ClientException $ex) { |
|
245 | + $this->response = $ex->getResponse(); |
|
246 | + } |
|
247 | + } |
|
248 | + |
|
249 | + public function isExpectedUrl($possibleUrl, $finalPart) { |
|
250 | + $baseUrlChopped = substr($this->baseUrl, 0, -4); |
|
251 | + $endCharacter = strlen($baseUrlChopped) + strlen($finalPart); |
|
252 | + return (substr($possibleUrl, 0, $endCharacter) == "$baseUrlChopped" . "$finalPart"); |
|
253 | + } |
|
254 | + |
|
255 | + /** |
|
256 | + * @Then /^the OCS status code should be "([^"]*)"$/ |
|
257 | + * @param int $statusCode |
|
258 | + */ |
|
259 | + public function theOCSStatusCodeShouldBe($statusCode) { |
|
260 | + Assert::assertEquals($statusCode, $this->getOCSResponse($this->response)); |
|
261 | + } |
|
262 | + |
|
263 | + /** |
|
264 | + * @Then /^the HTTP status code should be "([^"]*)"$/ |
|
265 | + * @param int $statusCode |
|
266 | + */ |
|
267 | + public function theHTTPStatusCodeShouldBe($statusCode) { |
|
268 | + Assert::assertEquals($statusCode, $this->response->getStatusCode()); |
|
269 | + } |
|
270 | + |
|
271 | + /** |
|
272 | + * @Then /^the Content-Type should be "([^"]*)"$/ |
|
273 | + * @param string $contentType |
|
274 | + */ |
|
275 | + public function theContentTypeShouldbe($contentType) { |
|
276 | + Assert::assertEquals($contentType, $this->response->getHeader('Content-Type')[0]); |
|
277 | + } |
|
278 | + |
|
279 | + /** |
|
280 | + * @param ResponseInterface $response |
|
281 | + */ |
|
282 | + private function extracRequestTokenFromResponse(ResponseInterface $response) { |
|
283 | + $this->requestToken = substr(preg_replace('/(.*)data-requesttoken="(.*)">(.*)/sm', '\2', $response->getBody()->getContents()), 0, 89); |
|
284 | + } |
|
285 | + |
|
286 | + /** |
|
287 | + * @Given Logging in using web as :user |
|
288 | + * @param string $user |
|
289 | + */ |
|
290 | + public function loggingInUsingWebAs($user) { |
|
291 | + $baseUrl = substr($this->baseUrl, 0, -5); |
|
292 | + $loginUrl = $baseUrl . '/index.php/login'; |
|
293 | + // Request a new session and extract CSRF token |
|
294 | + $client = new Client(); |
|
295 | + $response = $client->get( |
|
296 | + $loginUrl, |
|
297 | + [ |
|
298 | + 'cookies' => $this->cookieJar, |
|
299 | + ] |
|
300 | + ); |
|
301 | + $this->extracRequestTokenFromResponse($response); |
|
302 | + |
|
303 | + // Login and extract new token |
|
304 | + $password = ($user === 'admin') ? 'admin' : '123456'; |
|
305 | + $client = new Client(); |
|
306 | + $response = $client->post( |
|
307 | + $loginUrl, |
|
308 | + [ |
|
309 | + 'form_params' => [ |
|
310 | + 'user' => $user, |
|
311 | + 'password' => $password, |
|
312 | + 'requesttoken' => $this->requestToken, |
|
313 | + ], |
|
314 | + 'cookies' => $this->cookieJar, |
|
315 | + 'headers' => [ |
|
316 | + 'Origin' => $baseUrl, |
|
317 | + ], |
|
318 | + ] |
|
319 | + ); |
|
320 | + $this->extracRequestTokenFromResponse($response); |
|
321 | + } |
|
322 | + |
|
323 | + /** |
|
324 | + * @When Sending a :method to :url with requesttoken |
|
325 | + * @param string $method |
|
326 | + * @param string $url |
|
327 | + * @param TableNode|array|null $body |
|
328 | + */ |
|
329 | + public function sendingAToWithRequesttoken($method, $url, $body = null) { |
|
330 | + $baseUrl = substr($this->baseUrl, 0, -5); |
|
331 | + |
|
332 | + $options = [ |
|
333 | + 'cookies' => $this->cookieJar, |
|
334 | + 'headers' => [ |
|
335 | + 'requesttoken' => $this->requestToken |
|
336 | + ], |
|
337 | + ]; |
|
338 | + |
|
339 | + if ($body instanceof TableNode) { |
|
340 | + $fd = $body->getRowsHash(); |
|
341 | + $options['form_params'] = $fd; |
|
342 | + } elseif ($body) { |
|
343 | + $options = array_merge_recursive($options, $body); |
|
344 | + } |
|
345 | + |
|
346 | + $client = new Client(); |
|
347 | + try { |
|
348 | + $this->response = $client->request( |
|
349 | + $method, |
|
350 | + $baseUrl . $url, |
|
351 | + $options |
|
352 | + ); |
|
353 | + } catch (ClientException $e) { |
|
354 | + $this->response = $e->getResponse(); |
|
355 | + } |
|
356 | + } |
|
357 | + |
|
358 | + /** |
|
359 | + * @When Sending a :method to :url without requesttoken |
|
360 | + * @param string $method |
|
361 | + * @param string $url |
|
362 | + */ |
|
363 | + public function sendingAToWithoutRequesttoken($method, $url) { |
|
364 | + $baseUrl = substr($this->baseUrl, 0, -5); |
|
365 | + |
|
366 | + $client = new Client(); |
|
367 | + try { |
|
368 | + $this->response = $client->request( |
|
369 | + $method, |
|
370 | + $baseUrl . $url, |
|
371 | + [ |
|
372 | + 'cookies' => $this->cookieJar |
|
373 | + ] |
|
374 | + ); |
|
375 | + } catch (ClientException $e) { |
|
376 | + $this->response = $e->getResponse(); |
|
377 | + } |
|
378 | + } |
|
379 | + |
|
380 | + public static function removeFile($path, $filename) { |
|
381 | + if (file_exists("$path" . "$filename")) { |
|
382 | + unlink("$path" . "$filename"); |
|
383 | + } |
|
384 | + } |
|
385 | + |
|
386 | + /** |
|
387 | + * @Given User :user modifies text of :filename with text :text |
|
388 | + * @param string $user |
|
389 | + * @param string $filename |
|
390 | + * @param string $text |
|
391 | + */ |
|
392 | + public function modifyTextOfFile($user, $filename, $text) { |
|
393 | + self::removeFile($this->getDataDirectory() . "/$user/files", "$filename"); |
|
394 | + file_put_contents($this->getDataDirectory() . "/$user/files" . "$filename", "$text"); |
|
395 | + } |
|
396 | + |
|
397 | + private function getDataDirectory() { |
|
398 | + // Based on "runOcc" from CommandLine trait |
|
399 | + $args = ['config:system:get', 'datadirectory']; |
|
400 | + $args = array_map(function ($arg) { |
|
401 | + return escapeshellarg($arg); |
|
402 | + }, $args); |
|
403 | + $args[] = '--no-ansi --no-warnings'; |
|
404 | + $args = implode(' ', $args); |
|
405 | + |
|
406 | + $descriptor = [ |
|
407 | + 0 => ['pipe', 'r'], |
|
408 | + 1 => ['pipe', 'w'], |
|
409 | + 2 => ['pipe', 'w'], |
|
410 | + ]; |
|
411 | + $process = proc_open('php console.php ' . $args, $descriptor, $pipes, $ocPath = '../..'); |
|
412 | + $lastStdOut = stream_get_contents($pipes[1]); |
|
413 | + proc_close($process); |
|
414 | + |
|
415 | + return trim($lastStdOut); |
|
416 | + } |
|
417 | + |
|
418 | + /** |
|
419 | + * @Given file :filename is created :times times in :user user data |
|
420 | + * @param string $filename |
|
421 | + * @param string $times |
|
422 | + * @param string $user |
|
423 | + */ |
|
424 | + public function fileIsCreatedTimesInUserData($filename, $times, $user) { |
|
425 | + for ($i = 0; $i < $times; $i++) { |
|
426 | + file_put_contents($this->getDataDirectory() . "/$user/files" . "$filename-$i", "content-$i"); |
|
427 | + } |
|
428 | + } |
|
429 | + |
|
430 | + public function createFileSpecificSize($name, $size) { |
|
431 | + $file = fopen('work/' . "$name", 'w'); |
|
432 | + fseek($file, $size - 1, SEEK_CUR); |
|
433 | + fwrite($file, 'a'); // write a dummy char at SIZE position |
|
434 | + fclose($file); |
|
435 | + } |
|
436 | + |
|
437 | + public function createFileWithText($name, $text) { |
|
438 | + $file = fopen('work/' . "$name", 'w'); |
|
439 | + fwrite($file, $text); |
|
440 | + fclose($file); |
|
441 | + } |
|
442 | + |
|
443 | + /** |
|
444 | + * @Given file :filename of size :size is created in local storage |
|
445 | + * @param string $filename |
|
446 | + * @param string $size |
|
447 | + */ |
|
448 | + public function fileIsCreatedInLocalStorageWithSize($filename, $size) { |
|
449 | + $this->createFileSpecificSize("local_storage/$filename", $size); |
|
450 | + } |
|
451 | + |
|
452 | + /** |
|
453 | + * @Given file :filename with text :text is created in local storage |
|
454 | + * @param string $filename |
|
455 | + * @param string $text |
|
456 | + */ |
|
457 | + public function fileIsCreatedInLocalStorageWithText($filename, $text) { |
|
458 | + $this->createFileWithText("local_storage/$filename", $text); |
|
459 | + } |
|
460 | + |
|
461 | + /** |
|
462 | + * @When Sleep for :seconds seconds |
|
463 | + * @param int $seconds |
|
464 | + */ |
|
465 | + public function sleepForSeconds($seconds) { |
|
466 | + sleep((int)$seconds); |
|
467 | + } |
|
468 | + |
|
469 | + /** |
|
470 | + * @BeforeSuite |
|
471 | + */ |
|
472 | + public static function addFilesToSkeleton() { |
|
473 | + for ($i = 0; $i < 5; $i++) { |
|
474 | + file_put_contents('../../core/skeleton/' . 'textfile' . "$i" . '.txt', "Nextcloud test text file\n"); |
|
475 | + } |
|
476 | + if (!file_exists('../../core/skeleton/FOLDER')) { |
|
477 | + mkdir('../../core/skeleton/FOLDER', 0777, true); |
|
478 | + } |
|
479 | + if (!file_exists('../../core/skeleton/PARENT')) { |
|
480 | + mkdir('../../core/skeleton/PARENT', 0777, true); |
|
481 | + } |
|
482 | + file_put_contents('../../core/skeleton/PARENT/' . 'parent.txt', "Nextcloud test text file\n"); |
|
483 | + if (!file_exists('../../core/skeleton/PARENT/CHILD')) { |
|
484 | + mkdir('../../core/skeleton/PARENT/CHILD', 0777, true); |
|
485 | + } |
|
486 | + file_put_contents('../../core/skeleton/PARENT/CHILD/' . 'child.txt', "Nextcloud test text file\n"); |
|
487 | + } |
|
488 | + |
|
489 | + /** |
|
490 | + * @AfterSuite |
|
491 | + */ |
|
492 | + public static function removeFilesFromSkeleton() { |
|
493 | + for ($i = 0; $i < 5; $i++) { |
|
494 | + self::removeFile('../../core/skeleton/', 'textfile' . "$i" . '.txt'); |
|
495 | + } |
|
496 | + if (is_dir('../../core/skeleton/FOLDER')) { |
|
497 | + rmdir('../../core/skeleton/FOLDER'); |
|
498 | + } |
|
499 | + self::removeFile('../../core/skeleton/PARENT/CHILD/', 'child.txt'); |
|
500 | + if (is_dir('../../core/skeleton/PARENT/CHILD')) { |
|
501 | + rmdir('../../core/skeleton/PARENT/CHILD'); |
|
502 | + } |
|
503 | + self::removeFile('../../core/skeleton/PARENT/', 'parent.txt'); |
|
504 | + if (is_dir('../../core/skeleton/PARENT')) { |
|
505 | + rmdir('../../core/skeleton/PARENT'); |
|
506 | + } |
|
507 | + } |
|
508 | + |
|
509 | + /** |
|
510 | + * @BeforeScenario @local_storage |
|
511 | + */ |
|
512 | + public static function removeFilesFromLocalStorageBefore() { |
|
513 | + $dir = './work/local_storage/'; |
|
514 | + $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); |
|
515 | + $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); |
|
516 | + foreach ($ri as $file) { |
|
517 | + $file->isDir() ? rmdir($file) : unlink($file); |
|
518 | + } |
|
519 | + } |
|
520 | + |
|
521 | + /** |
|
522 | + * @AfterScenario @local_storage |
|
523 | + */ |
|
524 | + public static function removeFilesFromLocalStorageAfter() { |
|
525 | + $dir = './work/local_storage/'; |
|
526 | + $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); |
|
527 | + $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); |
|
528 | + foreach ($ri as $file) { |
|
529 | + $file->isDir() ? rmdir($file) : unlink($file); |
|
530 | + } |
|
531 | + } |
|
532 | + |
|
533 | + /** |
|
534 | + * @Given /^cookies are reset$/ |
|
535 | + */ |
|
536 | + public function cookiesAreReset() { |
|
537 | + $this->cookieJar = new CookieJar(); |
|
538 | + } |
|
539 | + |
|
540 | + /** |
|
541 | + * @Then The following headers should be set |
|
542 | + * @param TableNode $table |
|
543 | + * @throws \Exception |
|
544 | + */ |
|
545 | + public function theFollowingHeadersShouldBeSet(TableNode $table) { |
|
546 | + foreach ($table->getTable() as $header) { |
|
547 | + $headerName = $header[0]; |
|
548 | + $expectedHeaderValue = $header[1]; |
|
549 | + $returnedHeader = $this->response->getHeader($headerName)[0]; |
|
550 | + if ($returnedHeader !== $expectedHeaderValue) { |
|
551 | + throw new \Exception( |
|
552 | + sprintf( |
|
553 | + "Expected value '%s' for header '%s', got '%s'", |
|
554 | + $expectedHeaderValue, |
|
555 | + $headerName, |
|
556 | + $returnedHeader |
|
557 | + ) |
|
558 | + ); |
|
559 | + } |
|
560 | + } |
|
561 | + } |
|
562 | 562 | } |
@@ -8,42 +8,42 @@ |
||
8 | 8 | |
9 | 9 | trait Theming { |
10 | 10 | |
11 | - private bool $undoAllThemingChangesAfterScenario = false; |
|
12 | - |
|
13 | - /** |
|
14 | - * @AfterScenario |
|
15 | - */ |
|
16 | - public function undoAllThemingChanges() { |
|
17 | - if (!$this->undoAllThemingChangesAfterScenario) { |
|
18 | - return; |
|
19 | - } |
|
20 | - |
|
21 | - $this->loggingInUsingWebAs('admin'); |
|
22 | - $this->sendingAToWithRequesttoken('POST', '/index.php/apps/theming/ajax/undoAllChanges'); |
|
23 | - |
|
24 | - $this->undoAllThemingChangesAfterScenario = false; |
|
25 | - } |
|
26 | - |
|
27 | - /** |
|
28 | - * @When logged in admin uploads theming image for :key from file :source |
|
29 | - * |
|
30 | - * @param string $key |
|
31 | - * @param string $source |
|
32 | - */ |
|
33 | - public function loggedInAdminUploadsThemingImageForFromFile(string $key, string $source) { |
|
34 | - $this->undoAllThemingChangesAfterScenario = true; |
|
35 | - |
|
36 | - $file = \GuzzleHttp\Psr7\Utils::streamFor(fopen($source, 'r')); |
|
37 | - |
|
38 | - $this->sendingAToWithRequesttoken('POST', '/index.php/apps/theming/ajax/uploadImage?key=' . $key, |
|
39 | - [ |
|
40 | - 'multipart' => [ |
|
41 | - [ |
|
42 | - 'name' => 'image', |
|
43 | - 'contents' => $file |
|
44 | - ] |
|
45 | - ] |
|
46 | - ]); |
|
47 | - $this->theHTTPStatusCodeShouldBe('200'); |
|
48 | - } |
|
11 | + private bool $undoAllThemingChangesAfterScenario = false; |
|
12 | + |
|
13 | + /** |
|
14 | + * @AfterScenario |
|
15 | + */ |
|
16 | + public function undoAllThemingChanges() { |
|
17 | + if (!$this->undoAllThemingChangesAfterScenario) { |
|
18 | + return; |
|
19 | + } |
|
20 | + |
|
21 | + $this->loggingInUsingWebAs('admin'); |
|
22 | + $this->sendingAToWithRequesttoken('POST', '/index.php/apps/theming/ajax/undoAllChanges'); |
|
23 | + |
|
24 | + $this->undoAllThemingChangesAfterScenario = false; |
|
25 | + } |
|
26 | + |
|
27 | + /** |
|
28 | + * @When logged in admin uploads theming image for :key from file :source |
|
29 | + * |
|
30 | + * @param string $key |
|
31 | + * @param string $source |
|
32 | + */ |
|
33 | + public function loggedInAdminUploadsThemingImageForFromFile(string $key, string $source) { |
|
34 | + $this->undoAllThemingChangesAfterScenario = true; |
|
35 | + |
|
36 | + $file = \GuzzleHttp\Psr7\Utils::streamFor(fopen($source, 'r')); |
|
37 | + |
|
38 | + $this->sendingAToWithRequesttoken('POST', '/index.php/apps/theming/ajax/uploadImage?key=' . $key, |
|
39 | + [ |
|
40 | + 'multipart' => [ |
|
41 | + [ |
|
42 | + 'name' => 'image', |
|
43 | + 'contents' => $file |
|
44 | + ] |
|
45 | + ] |
|
46 | + ]); |
|
47 | + $this->theHTTPStatusCodeShouldBe('200'); |
|
48 | + } |
|
49 | 49 | } |
@@ -40,366 +40,366 @@ |
||
40 | 40 | * logout() |
41 | 41 | */ |
42 | 42 | class OC_User { |
43 | - private static $_setupedBackends = []; |
|
44 | - |
|
45 | - // bool, stores if a user want to access a resource anonymously, e.g if they open a public link |
|
46 | - private static $incognitoMode = false; |
|
47 | - |
|
48 | - /** |
|
49 | - * Adds the backend to the list of used backends |
|
50 | - * |
|
51 | - * @param string|\OCP\UserInterface $backend default: database The backend to use for user management |
|
52 | - * @return bool |
|
53 | - * @deprecated 32.0.0 Use IUserManager::registerBackend instead |
|
54 | - * |
|
55 | - * Set the User Authentication Module |
|
56 | - */ |
|
57 | - public static function useBackend($backend = 'database') { |
|
58 | - if ($backend instanceof \OCP\UserInterface) { |
|
59 | - Server::get(IUserManager::class)->registerBackend($backend); |
|
60 | - } else { |
|
61 | - // You'll never know what happens |
|
62 | - if ($backend === null or !is_string($backend)) { |
|
63 | - $backend = 'database'; |
|
64 | - } |
|
65 | - |
|
66 | - // Load backend |
|
67 | - switch ($backend) { |
|
68 | - case 'database': |
|
69 | - case 'mysql': |
|
70 | - case 'sqlite': |
|
71 | - Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']); |
|
72 | - Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
73 | - break; |
|
74 | - case 'dummy': |
|
75 | - Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); |
|
76 | - break; |
|
77 | - default: |
|
78 | - Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']); |
|
79 | - $className = 'OC_USER_' . strtoupper($backend); |
|
80 | - Server::get(IUserManager::class)->registerBackend(new $className()); |
|
81 | - break; |
|
82 | - } |
|
83 | - } |
|
84 | - return true; |
|
85 | - } |
|
86 | - |
|
87 | - /** |
|
88 | - * remove all used backends |
|
89 | - * @deprecated 32.0.0 Use IUserManager::clearBackends instead |
|
90 | - */ |
|
91 | - public static function clearBackends() { |
|
92 | - Server::get(IUserManager::class)->clearBackends(); |
|
93 | - } |
|
94 | - |
|
95 | - /** |
|
96 | - * setup the configured backends in config.php |
|
97 | - * @suppress PhanDeprecatedFunction |
|
98 | - */ |
|
99 | - public static function setupBackends() { |
|
100 | - OC_App::loadApps(['prelogin']); |
|
101 | - $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []); |
|
102 | - if (isset($backends['default']) && !$backends['default']) { |
|
103 | - // clear default backends |
|
104 | - self::clearBackends(); |
|
105 | - } |
|
106 | - foreach ($backends as $i => $config) { |
|
107 | - if (!is_array($config)) { |
|
108 | - continue; |
|
109 | - } |
|
110 | - $class = $config['class']; |
|
111 | - $arguments = $config['arguments']; |
|
112 | - if (class_exists($class)) { |
|
113 | - if (!in_array($i, self::$_setupedBackends)) { |
|
114 | - // make a reflection object |
|
115 | - $reflectionObj = new ReflectionClass($class); |
|
116 | - |
|
117 | - // use Reflection to create a new instance, using the $args |
|
118 | - $backend = $reflectionObj->newInstanceArgs($arguments); |
|
119 | - self::useBackend($backend); |
|
120 | - self::$_setupedBackends[] = $i; |
|
121 | - } else { |
|
122 | - Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']); |
|
123 | - } |
|
124 | - } else { |
|
125 | - Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']); |
|
126 | - } |
|
127 | - } |
|
128 | - } |
|
129 | - |
|
130 | - /** |
|
131 | - * Try to login a user, assuming authentication |
|
132 | - * has already happened (e.g. via Single Sign On). |
|
133 | - * |
|
134 | - * Log in a user and regenerate a new session. |
|
135 | - * |
|
136 | - * @param \OCP\Authentication\IApacheBackend $backend |
|
137 | - * @return bool |
|
138 | - */ |
|
139 | - public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { |
|
140 | - $uid = $backend->getCurrentUserId(); |
|
141 | - $run = true; |
|
142 | - OC_Hook::emit('OC_User', 'pre_login', ['run' => &$run, 'uid' => $uid, 'backend' => $backend]); |
|
143 | - |
|
144 | - if ($uid) { |
|
145 | - if (self::getUser() !== $uid) { |
|
146 | - self::setUserId($uid); |
|
147 | - $userSession = \OC::$server->getUserSession(); |
|
148 | - |
|
149 | - /** @var IEventDispatcher $dispatcher */ |
|
150 | - $dispatcher = \OC::$server->get(IEventDispatcher::class); |
|
151 | - |
|
152 | - if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) { |
|
153 | - $message = \OC::$server->getL10N('lib')->t('Account disabled'); |
|
154 | - throw new DisabledUserException($message); |
|
155 | - } |
|
156 | - $userSession->setLoginName($uid); |
|
157 | - $request = OC::$server->getRequest(); |
|
158 | - $password = null; |
|
159 | - if ($backend instanceof \OCP\Authentication\IProvideUserSecretBackend) { |
|
160 | - $password = $backend->getCurrentUserSecret(); |
|
161 | - } |
|
162 | - |
|
163 | - /** @var IEventDispatcher $dispatcher */ |
|
164 | - $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend)); |
|
165 | - |
|
166 | - $userSession->createSessionToken($request, $uid, $uid, $password); |
|
167 | - $userSession->createRememberMeToken($userSession->getUser()); |
|
168 | - |
|
169 | - if (empty($password)) { |
|
170 | - $tokenProvider = \OC::$server->get(IProvider::class); |
|
171 | - try { |
|
172 | - $token = $tokenProvider->getToken($userSession->getSession()->getId()); |
|
173 | - $token->setScope([ |
|
174 | - IToken::SCOPE_SKIP_PASSWORD_VALIDATION => true, |
|
175 | - IToken::SCOPE_FILESYSTEM => true, |
|
176 | - ]); |
|
177 | - $tokenProvider->updateToken($token); |
|
178 | - } catch (InvalidTokenException|WipeTokenException|SessionNotAvailableException) { |
|
179 | - // swallow the exceptions as we do not deal with them here |
|
180 | - // simply skip updating the token when is it missing |
|
181 | - } |
|
182 | - } |
|
183 | - |
|
184 | - // setup the filesystem |
|
185 | - OC_Util::setupFS($uid); |
|
186 | - // first call the post_login hooks, the login-process needs to be |
|
187 | - // completed before we can safely create the users folder. |
|
188 | - // For example encryption needs to initialize the users keys first |
|
189 | - // before we can create the user folder with the skeleton files |
|
190 | - OC_Hook::emit( |
|
191 | - 'OC_User', |
|
192 | - 'post_login', |
|
193 | - [ |
|
194 | - 'uid' => $uid, |
|
195 | - 'password' => $password, |
|
196 | - 'isTokenLogin' => false, |
|
197 | - ] |
|
198 | - ); |
|
199 | - $dispatcher->dispatchTyped(new UserLoggedInEvent( |
|
200 | - \OC::$server->get(IUserManager::class)->get($uid), |
|
201 | - $uid, |
|
202 | - null, |
|
203 | - false) |
|
204 | - ); |
|
205 | - |
|
206 | - //trigger creation of user home and /files folder |
|
207 | - \OC::$server->getUserFolder($uid); |
|
208 | - } |
|
209 | - return true; |
|
210 | - } |
|
211 | - return false; |
|
212 | - } |
|
213 | - |
|
214 | - /** |
|
215 | - * Verify with Apache whether user is authenticated. |
|
216 | - * |
|
217 | - * @return boolean|null |
|
218 | - * true: authenticated |
|
219 | - * false: not authenticated |
|
220 | - * null: not handled / no backend available |
|
221 | - */ |
|
222 | - public static function handleApacheAuth() { |
|
223 | - $backend = self::findFirstActiveUsedBackend(); |
|
224 | - if ($backend) { |
|
225 | - OC_App::loadApps(); |
|
226 | - |
|
227 | - //setup extra user backends |
|
228 | - self::setupBackends(); |
|
229 | - \OC::$server->getUserSession()->unsetMagicInCookie(); |
|
230 | - |
|
231 | - return self::loginWithApache($backend); |
|
232 | - } |
|
233 | - |
|
234 | - return null; |
|
235 | - } |
|
236 | - |
|
237 | - |
|
238 | - /** |
|
239 | - * Sets user id for session and triggers emit |
|
240 | - * |
|
241 | - * @param string $uid |
|
242 | - */ |
|
243 | - public static function setUserId($uid) { |
|
244 | - $userSession = \OC::$server->getUserSession(); |
|
245 | - $userManager = Server::get(IUserManager::class); |
|
246 | - if ($user = $userManager->get($uid)) { |
|
247 | - $userSession->setUser($user); |
|
248 | - } else { |
|
249 | - \OC::$server->getSession()->set('user_id', $uid); |
|
250 | - } |
|
251 | - } |
|
252 | - |
|
253 | - /** |
|
254 | - * Check if the user is logged in, considers also the HTTP basic credentials |
|
255 | - * |
|
256 | - * @deprecated 12.0.0 use \OC::$server->getUserSession()->isLoggedIn() |
|
257 | - * @return bool |
|
258 | - */ |
|
259 | - public static function isLoggedIn() { |
|
260 | - return \OC::$server->getUserSession()->isLoggedIn(); |
|
261 | - } |
|
262 | - |
|
263 | - /** |
|
264 | - * set incognito mode, e.g. if a user wants to open a public link |
|
265 | - * |
|
266 | - * @param bool $status |
|
267 | - */ |
|
268 | - public static function setIncognitoMode($status) { |
|
269 | - self::$incognitoMode = $status; |
|
270 | - } |
|
271 | - |
|
272 | - /** |
|
273 | - * get incognito mode status |
|
274 | - * |
|
275 | - * @return bool |
|
276 | - */ |
|
277 | - public static function isIncognitoMode() { |
|
278 | - return self::$incognitoMode; |
|
279 | - } |
|
280 | - |
|
281 | - /** |
|
282 | - * Returns the current logout URL valid for the currently logged-in user |
|
283 | - * |
|
284 | - * @param \OCP\IURLGenerator $urlGenerator |
|
285 | - * @return string |
|
286 | - */ |
|
287 | - public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) { |
|
288 | - $backend = self::findFirstActiveUsedBackend(); |
|
289 | - if ($backend) { |
|
290 | - return $backend->getLogoutUrl(); |
|
291 | - } |
|
292 | - |
|
293 | - $user = \OC::$server->getUserSession()->getUser(); |
|
294 | - if ($user instanceof IUser) { |
|
295 | - $backend = $user->getBackend(); |
|
296 | - if ($backend instanceof \OCP\User\Backend\ICustomLogout) { |
|
297 | - return $backend->getLogoutUrl(); |
|
298 | - } |
|
299 | - } |
|
300 | - |
|
301 | - $logoutUrl = $urlGenerator->linkToRoute('core.login.logout'); |
|
302 | - $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister()); |
|
303 | - |
|
304 | - return $logoutUrl; |
|
305 | - } |
|
306 | - |
|
307 | - /** |
|
308 | - * Check if the user is an admin user |
|
309 | - * |
|
310 | - * @param string $uid uid of the admin |
|
311 | - * @return bool |
|
312 | - */ |
|
313 | - public static function isAdminUser($uid) { |
|
314 | - $user = Server::get(IUserManager::class)->get($uid); |
|
315 | - $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID()); |
|
316 | - return $isAdmin && self::$incognitoMode === false; |
|
317 | - } |
|
318 | - |
|
319 | - |
|
320 | - /** |
|
321 | - * get the user id of the user currently logged in. |
|
322 | - * |
|
323 | - * @return string|false uid or false |
|
324 | - */ |
|
325 | - public static function getUser() { |
|
326 | - $uid = Server::get(ISession::class)?->get('user_id'); |
|
327 | - if (!is_null($uid) && self::$incognitoMode === false) { |
|
328 | - return $uid; |
|
329 | - } else { |
|
330 | - return false; |
|
331 | - } |
|
332 | - } |
|
333 | - |
|
334 | - /** |
|
335 | - * Set password |
|
336 | - * |
|
337 | - * @param string $uid The username |
|
338 | - * @param string $password The new password |
|
339 | - * @param string $recoveryPassword for the encryption app to reset encryption keys |
|
340 | - * @return bool |
|
341 | - * |
|
342 | - * Change the password of a user |
|
343 | - */ |
|
344 | - public static function setPassword($uid, $password, $recoveryPassword = null) { |
|
345 | - $user = Server::get(IUserManager::class)->get($uid); |
|
346 | - if ($user) { |
|
347 | - return $user->setPassword($password, $recoveryPassword); |
|
348 | - } else { |
|
349 | - return false; |
|
350 | - } |
|
351 | - } |
|
352 | - |
|
353 | - /** |
|
354 | - * @param string $uid The username |
|
355 | - * @return string |
|
356 | - * |
|
357 | - * returns the path to the users home directory |
|
358 | - * @deprecated 12.0.0 Use \OC::$server->getUserManager->getHome() |
|
359 | - */ |
|
360 | - public static function getHome($uid) { |
|
361 | - $user = Server::get(IUserManager::class)->get($uid); |
|
362 | - if ($user) { |
|
363 | - return $user->getHome(); |
|
364 | - } else { |
|
365 | - return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid; |
|
366 | - } |
|
367 | - } |
|
368 | - |
|
369 | - /** |
|
370 | - * Get a list of all users display name |
|
371 | - * |
|
372 | - * @param string $search |
|
373 | - * @param int $limit |
|
374 | - * @param int $offset |
|
375 | - * @return array associative array with all display names (value) and corresponding uids (key) |
|
376 | - * |
|
377 | - * Get a list of all display names and user ids. |
|
378 | - * @deprecated 12.0.0 Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead. |
|
379 | - */ |
|
380 | - public static function getDisplayNames($search = '', $limit = null, $offset = null) { |
|
381 | - $displayNames = []; |
|
382 | - $users = Server::get(IUserManager::class)->searchDisplayName($search, $limit, $offset); |
|
383 | - foreach ($users as $user) { |
|
384 | - $displayNames[$user->getUID()] = $user->getDisplayName(); |
|
385 | - } |
|
386 | - return $displayNames; |
|
387 | - } |
|
388 | - |
|
389 | - /** |
|
390 | - * Returns the first active backend from self::$_usedBackends. |
|
391 | - * |
|
392 | - * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend |
|
393 | - */ |
|
394 | - private static function findFirstActiveUsedBackend() { |
|
395 | - foreach (Server::get(IUserManager::class)->getBackends() as $backend) { |
|
396 | - if ($backend instanceof OCP\Authentication\IApacheBackend) { |
|
397 | - if ($backend->isSessionActive()) { |
|
398 | - return $backend; |
|
399 | - } |
|
400 | - } |
|
401 | - } |
|
402 | - |
|
403 | - return null; |
|
404 | - } |
|
43 | + private static $_setupedBackends = []; |
|
44 | + |
|
45 | + // bool, stores if a user want to access a resource anonymously, e.g if they open a public link |
|
46 | + private static $incognitoMode = false; |
|
47 | + |
|
48 | + /** |
|
49 | + * Adds the backend to the list of used backends |
|
50 | + * |
|
51 | + * @param string|\OCP\UserInterface $backend default: database The backend to use for user management |
|
52 | + * @return bool |
|
53 | + * @deprecated 32.0.0 Use IUserManager::registerBackend instead |
|
54 | + * |
|
55 | + * Set the User Authentication Module |
|
56 | + */ |
|
57 | + public static function useBackend($backend = 'database') { |
|
58 | + if ($backend instanceof \OCP\UserInterface) { |
|
59 | + Server::get(IUserManager::class)->registerBackend($backend); |
|
60 | + } else { |
|
61 | + // You'll never know what happens |
|
62 | + if ($backend === null or !is_string($backend)) { |
|
63 | + $backend = 'database'; |
|
64 | + } |
|
65 | + |
|
66 | + // Load backend |
|
67 | + switch ($backend) { |
|
68 | + case 'database': |
|
69 | + case 'mysql': |
|
70 | + case 'sqlite': |
|
71 | + Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']); |
|
72 | + Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
73 | + break; |
|
74 | + case 'dummy': |
|
75 | + Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); |
|
76 | + break; |
|
77 | + default: |
|
78 | + Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']); |
|
79 | + $className = 'OC_USER_' . strtoupper($backend); |
|
80 | + Server::get(IUserManager::class)->registerBackend(new $className()); |
|
81 | + break; |
|
82 | + } |
|
83 | + } |
|
84 | + return true; |
|
85 | + } |
|
86 | + |
|
87 | + /** |
|
88 | + * remove all used backends |
|
89 | + * @deprecated 32.0.0 Use IUserManager::clearBackends instead |
|
90 | + */ |
|
91 | + public static function clearBackends() { |
|
92 | + Server::get(IUserManager::class)->clearBackends(); |
|
93 | + } |
|
94 | + |
|
95 | + /** |
|
96 | + * setup the configured backends in config.php |
|
97 | + * @suppress PhanDeprecatedFunction |
|
98 | + */ |
|
99 | + public static function setupBackends() { |
|
100 | + OC_App::loadApps(['prelogin']); |
|
101 | + $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []); |
|
102 | + if (isset($backends['default']) && !$backends['default']) { |
|
103 | + // clear default backends |
|
104 | + self::clearBackends(); |
|
105 | + } |
|
106 | + foreach ($backends as $i => $config) { |
|
107 | + if (!is_array($config)) { |
|
108 | + continue; |
|
109 | + } |
|
110 | + $class = $config['class']; |
|
111 | + $arguments = $config['arguments']; |
|
112 | + if (class_exists($class)) { |
|
113 | + if (!in_array($i, self::$_setupedBackends)) { |
|
114 | + // make a reflection object |
|
115 | + $reflectionObj = new ReflectionClass($class); |
|
116 | + |
|
117 | + // use Reflection to create a new instance, using the $args |
|
118 | + $backend = $reflectionObj->newInstanceArgs($arguments); |
|
119 | + self::useBackend($backend); |
|
120 | + self::$_setupedBackends[] = $i; |
|
121 | + } else { |
|
122 | + Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']); |
|
123 | + } |
|
124 | + } else { |
|
125 | + Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']); |
|
126 | + } |
|
127 | + } |
|
128 | + } |
|
129 | + |
|
130 | + /** |
|
131 | + * Try to login a user, assuming authentication |
|
132 | + * has already happened (e.g. via Single Sign On). |
|
133 | + * |
|
134 | + * Log in a user and regenerate a new session. |
|
135 | + * |
|
136 | + * @param \OCP\Authentication\IApacheBackend $backend |
|
137 | + * @return bool |
|
138 | + */ |
|
139 | + public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { |
|
140 | + $uid = $backend->getCurrentUserId(); |
|
141 | + $run = true; |
|
142 | + OC_Hook::emit('OC_User', 'pre_login', ['run' => &$run, 'uid' => $uid, 'backend' => $backend]); |
|
143 | + |
|
144 | + if ($uid) { |
|
145 | + if (self::getUser() !== $uid) { |
|
146 | + self::setUserId($uid); |
|
147 | + $userSession = \OC::$server->getUserSession(); |
|
148 | + |
|
149 | + /** @var IEventDispatcher $dispatcher */ |
|
150 | + $dispatcher = \OC::$server->get(IEventDispatcher::class); |
|
151 | + |
|
152 | + if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) { |
|
153 | + $message = \OC::$server->getL10N('lib')->t('Account disabled'); |
|
154 | + throw new DisabledUserException($message); |
|
155 | + } |
|
156 | + $userSession->setLoginName($uid); |
|
157 | + $request = OC::$server->getRequest(); |
|
158 | + $password = null; |
|
159 | + if ($backend instanceof \OCP\Authentication\IProvideUserSecretBackend) { |
|
160 | + $password = $backend->getCurrentUserSecret(); |
|
161 | + } |
|
162 | + |
|
163 | + /** @var IEventDispatcher $dispatcher */ |
|
164 | + $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend)); |
|
165 | + |
|
166 | + $userSession->createSessionToken($request, $uid, $uid, $password); |
|
167 | + $userSession->createRememberMeToken($userSession->getUser()); |
|
168 | + |
|
169 | + if (empty($password)) { |
|
170 | + $tokenProvider = \OC::$server->get(IProvider::class); |
|
171 | + try { |
|
172 | + $token = $tokenProvider->getToken($userSession->getSession()->getId()); |
|
173 | + $token->setScope([ |
|
174 | + IToken::SCOPE_SKIP_PASSWORD_VALIDATION => true, |
|
175 | + IToken::SCOPE_FILESYSTEM => true, |
|
176 | + ]); |
|
177 | + $tokenProvider->updateToken($token); |
|
178 | + } catch (InvalidTokenException|WipeTokenException|SessionNotAvailableException) { |
|
179 | + // swallow the exceptions as we do not deal with them here |
|
180 | + // simply skip updating the token when is it missing |
|
181 | + } |
|
182 | + } |
|
183 | + |
|
184 | + // setup the filesystem |
|
185 | + OC_Util::setupFS($uid); |
|
186 | + // first call the post_login hooks, the login-process needs to be |
|
187 | + // completed before we can safely create the users folder. |
|
188 | + // For example encryption needs to initialize the users keys first |
|
189 | + // before we can create the user folder with the skeleton files |
|
190 | + OC_Hook::emit( |
|
191 | + 'OC_User', |
|
192 | + 'post_login', |
|
193 | + [ |
|
194 | + 'uid' => $uid, |
|
195 | + 'password' => $password, |
|
196 | + 'isTokenLogin' => false, |
|
197 | + ] |
|
198 | + ); |
|
199 | + $dispatcher->dispatchTyped(new UserLoggedInEvent( |
|
200 | + \OC::$server->get(IUserManager::class)->get($uid), |
|
201 | + $uid, |
|
202 | + null, |
|
203 | + false) |
|
204 | + ); |
|
205 | + |
|
206 | + //trigger creation of user home and /files folder |
|
207 | + \OC::$server->getUserFolder($uid); |
|
208 | + } |
|
209 | + return true; |
|
210 | + } |
|
211 | + return false; |
|
212 | + } |
|
213 | + |
|
214 | + /** |
|
215 | + * Verify with Apache whether user is authenticated. |
|
216 | + * |
|
217 | + * @return boolean|null |
|
218 | + * true: authenticated |
|
219 | + * false: not authenticated |
|
220 | + * null: not handled / no backend available |
|
221 | + */ |
|
222 | + public static function handleApacheAuth() { |
|
223 | + $backend = self::findFirstActiveUsedBackend(); |
|
224 | + if ($backend) { |
|
225 | + OC_App::loadApps(); |
|
226 | + |
|
227 | + //setup extra user backends |
|
228 | + self::setupBackends(); |
|
229 | + \OC::$server->getUserSession()->unsetMagicInCookie(); |
|
230 | + |
|
231 | + return self::loginWithApache($backend); |
|
232 | + } |
|
233 | + |
|
234 | + return null; |
|
235 | + } |
|
236 | + |
|
237 | + |
|
238 | + /** |
|
239 | + * Sets user id for session and triggers emit |
|
240 | + * |
|
241 | + * @param string $uid |
|
242 | + */ |
|
243 | + public static function setUserId($uid) { |
|
244 | + $userSession = \OC::$server->getUserSession(); |
|
245 | + $userManager = Server::get(IUserManager::class); |
|
246 | + if ($user = $userManager->get($uid)) { |
|
247 | + $userSession->setUser($user); |
|
248 | + } else { |
|
249 | + \OC::$server->getSession()->set('user_id', $uid); |
|
250 | + } |
|
251 | + } |
|
252 | + |
|
253 | + /** |
|
254 | + * Check if the user is logged in, considers also the HTTP basic credentials |
|
255 | + * |
|
256 | + * @deprecated 12.0.0 use \OC::$server->getUserSession()->isLoggedIn() |
|
257 | + * @return bool |
|
258 | + */ |
|
259 | + public static function isLoggedIn() { |
|
260 | + return \OC::$server->getUserSession()->isLoggedIn(); |
|
261 | + } |
|
262 | + |
|
263 | + /** |
|
264 | + * set incognito mode, e.g. if a user wants to open a public link |
|
265 | + * |
|
266 | + * @param bool $status |
|
267 | + */ |
|
268 | + public static function setIncognitoMode($status) { |
|
269 | + self::$incognitoMode = $status; |
|
270 | + } |
|
271 | + |
|
272 | + /** |
|
273 | + * get incognito mode status |
|
274 | + * |
|
275 | + * @return bool |
|
276 | + */ |
|
277 | + public static function isIncognitoMode() { |
|
278 | + return self::$incognitoMode; |
|
279 | + } |
|
280 | + |
|
281 | + /** |
|
282 | + * Returns the current logout URL valid for the currently logged-in user |
|
283 | + * |
|
284 | + * @param \OCP\IURLGenerator $urlGenerator |
|
285 | + * @return string |
|
286 | + */ |
|
287 | + public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) { |
|
288 | + $backend = self::findFirstActiveUsedBackend(); |
|
289 | + if ($backend) { |
|
290 | + return $backend->getLogoutUrl(); |
|
291 | + } |
|
292 | + |
|
293 | + $user = \OC::$server->getUserSession()->getUser(); |
|
294 | + if ($user instanceof IUser) { |
|
295 | + $backend = $user->getBackend(); |
|
296 | + if ($backend instanceof \OCP\User\Backend\ICustomLogout) { |
|
297 | + return $backend->getLogoutUrl(); |
|
298 | + } |
|
299 | + } |
|
300 | + |
|
301 | + $logoutUrl = $urlGenerator->linkToRoute('core.login.logout'); |
|
302 | + $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister()); |
|
303 | + |
|
304 | + return $logoutUrl; |
|
305 | + } |
|
306 | + |
|
307 | + /** |
|
308 | + * Check if the user is an admin user |
|
309 | + * |
|
310 | + * @param string $uid uid of the admin |
|
311 | + * @return bool |
|
312 | + */ |
|
313 | + public static function isAdminUser($uid) { |
|
314 | + $user = Server::get(IUserManager::class)->get($uid); |
|
315 | + $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID()); |
|
316 | + return $isAdmin && self::$incognitoMode === false; |
|
317 | + } |
|
318 | + |
|
319 | + |
|
320 | + /** |
|
321 | + * get the user id of the user currently logged in. |
|
322 | + * |
|
323 | + * @return string|false uid or false |
|
324 | + */ |
|
325 | + public static function getUser() { |
|
326 | + $uid = Server::get(ISession::class)?->get('user_id'); |
|
327 | + if (!is_null($uid) && self::$incognitoMode === false) { |
|
328 | + return $uid; |
|
329 | + } else { |
|
330 | + return false; |
|
331 | + } |
|
332 | + } |
|
333 | + |
|
334 | + /** |
|
335 | + * Set password |
|
336 | + * |
|
337 | + * @param string $uid The username |
|
338 | + * @param string $password The new password |
|
339 | + * @param string $recoveryPassword for the encryption app to reset encryption keys |
|
340 | + * @return bool |
|
341 | + * |
|
342 | + * Change the password of a user |
|
343 | + */ |
|
344 | + public static function setPassword($uid, $password, $recoveryPassword = null) { |
|
345 | + $user = Server::get(IUserManager::class)->get($uid); |
|
346 | + if ($user) { |
|
347 | + return $user->setPassword($password, $recoveryPassword); |
|
348 | + } else { |
|
349 | + return false; |
|
350 | + } |
|
351 | + } |
|
352 | + |
|
353 | + /** |
|
354 | + * @param string $uid The username |
|
355 | + * @return string |
|
356 | + * |
|
357 | + * returns the path to the users home directory |
|
358 | + * @deprecated 12.0.0 Use \OC::$server->getUserManager->getHome() |
|
359 | + */ |
|
360 | + public static function getHome($uid) { |
|
361 | + $user = Server::get(IUserManager::class)->get($uid); |
|
362 | + if ($user) { |
|
363 | + return $user->getHome(); |
|
364 | + } else { |
|
365 | + return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid; |
|
366 | + } |
|
367 | + } |
|
368 | + |
|
369 | + /** |
|
370 | + * Get a list of all users display name |
|
371 | + * |
|
372 | + * @param string $search |
|
373 | + * @param int $limit |
|
374 | + * @param int $offset |
|
375 | + * @return array associative array with all display names (value) and corresponding uids (key) |
|
376 | + * |
|
377 | + * Get a list of all display names and user ids. |
|
378 | + * @deprecated 12.0.0 Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead. |
|
379 | + */ |
|
380 | + public static function getDisplayNames($search = '', $limit = null, $offset = null) { |
|
381 | + $displayNames = []; |
|
382 | + $users = Server::get(IUserManager::class)->searchDisplayName($search, $limit, $offset); |
|
383 | + foreach ($users as $user) { |
|
384 | + $displayNames[$user->getUID()] = $user->getDisplayName(); |
|
385 | + } |
|
386 | + return $displayNames; |
|
387 | + } |
|
388 | + |
|
389 | + /** |
|
390 | + * Returns the first active backend from self::$_usedBackends. |
|
391 | + * |
|
392 | + * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend |
|
393 | + */ |
|
394 | + private static function findFirstActiveUsedBackend() { |
|
395 | + foreach (Server::get(IUserManager::class)->getBackends() as $backend) { |
|
396 | + if ($backend instanceof OCP\Authentication\IApacheBackend) { |
|
397 | + if ($backend->isSessionActive()) { |
|
398 | + return $backend; |
|
399 | + } |
|
400 | + } |
|
401 | + } |
|
402 | + |
|
403 | + return null; |
|
404 | + } |
|
405 | 405 | } |
@@ -65,987 +65,987 @@ |
||
65 | 65 | * @package OC\User |
66 | 66 | */ |
67 | 67 | class Session implements IUserSession, Emitter { |
68 | - use TTransactional; |
|
69 | - |
|
70 | - /** @var User $activeUser */ |
|
71 | - protected $activeUser; |
|
72 | - |
|
73 | - public function __construct( |
|
74 | - private Manager $manager, |
|
75 | - private ISession $session, |
|
76 | - private ITimeFactory $timeFactory, |
|
77 | - private ?IProvider $tokenProvider, |
|
78 | - private IConfig $config, |
|
79 | - private ISecureRandom $random, |
|
80 | - private ILockdownManager $lockdownManager, |
|
81 | - private LoggerInterface $logger, |
|
82 | - private IEventDispatcher $dispatcher, |
|
83 | - ) { |
|
84 | - } |
|
85 | - |
|
86 | - /** |
|
87 | - * @param IProvider $provider |
|
88 | - */ |
|
89 | - public function setTokenProvider(IProvider $provider) { |
|
90 | - $this->tokenProvider = $provider; |
|
91 | - } |
|
92 | - |
|
93 | - /** |
|
94 | - * @param string $scope |
|
95 | - * @param string $method |
|
96 | - * @param callable $callback |
|
97 | - */ |
|
98 | - public function listen($scope, $method, callable $callback) { |
|
99 | - $this->manager->listen($scope, $method, $callback); |
|
100 | - } |
|
101 | - |
|
102 | - /** |
|
103 | - * @param string $scope optional |
|
104 | - * @param string $method optional |
|
105 | - * @param callable $callback optional |
|
106 | - */ |
|
107 | - public function removeListener($scope = null, $method = null, ?callable $callback = null) { |
|
108 | - $this->manager->removeListener($scope, $method, $callback); |
|
109 | - } |
|
110 | - |
|
111 | - /** |
|
112 | - * get the manager object |
|
113 | - * |
|
114 | - * @return Manager|PublicEmitter |
|
115 | - */ |
|
116 | - public function getManager() { |
|
117 | - return $this->manager; |
|
118 | - } |
|
119 | - |
|
120 | - /** |
|
121 | - * get the session object |
|
122 | - * |
|
123 | - * @return ISession |
|
124 | - */ |
|
125 | - public function getSession() { |
|
126 | - return $this->session; |
|
127 | - } |
|
128 | - |
|
129 | - /** |
|
130 | - * set the session object |
|
131 | - * |
|
132 | - * @param ISession $session |
|
133 | - */ |
|
134 | - public function setSession(ISession $session) { |
|
135 | - if ($this->session instanceof ISession) { |
|
136 | - $this->session->close(); |
|
137 | - } |
|
138 | - $this->session = $session; |
|
139 | - $this->activeUser = null; |
|
140 | - } |
|
141 | - |
|
142 | - /** |
|
143 | - * set the currently active user |
|
144 | - * |
|
145 | - * @param IUser|null $user |
|
146 | - */ |
|
147 | - public function setUser($user) { |
|
148 | - if (is_null($user)) { |
|
149 | - $this->session->remove('user_id'); |
|
150 | - } else { |
|
151 | - $this->session->set('user_id', $user->getUID()); |
|
152 | - } |
|
153 | - $this->activeUser = $user; |
|
154 | - } |
|
155 | - |
|
156 | - /** |
|
157 | - * Temporarily set the currently active user without persisting in the session |
|
158 | - * |
|
159 | - * @param IUser|null $user |
|
160 | - */ |
|
161 | - public function setVolatileActiveUser(?IUser $user): void { |
|
162 | - $this->activeUser = $user; |
|
163 | - } |
|
164 | - |
|
165 | - /** |
|
166 | - * get the current active user |
|
167 | - * |
|
168 | - * @return IUser|null Current user, otherwise null |
|
169 | - */ |
|
170 | - public function getUser() { |
|
171 | - // FIXME: This is a quick'n dirty work-around for the incognito mode as |
|
172 | - // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155 |
|
173 | - if (OC_User::isIncognitoMode()) { |
|
174 | - return null; |
|
175 | - } |
|
176 | - if (is_null($this->activeUser)) { |
|
177 | - $uid = $this->session->get('user_id'); |
|
178 | - if (is_null($uid)) { |
|
179 | - return null; |
|
180 | - } |
|
181 | - $this->activeUser = $this->manager->get($uid); |
|
182 | - if (is_null($this->activeUser)) { |
|
183 | - return null; |
|
184 | - } |
|
185 | - $this->validateSession(); |
|
186 | - } |
|
187 | - return $this->activeUser; |
|
188 | - } |
|
189 | - |
|
190 | - /** |
|
191 | - * Validate whether the current session is valid |
|
192 | - * |
|
193 | - * - For token-authenticated clients, the token validity is checked |
|
194 | - * - For browsers, the session token validity is checked |
|
195 | - */ |
|
196 | - protected function validateSession() { |
|
197 | - $token = null; |
|
198 | - $appPassword = $this->session->get('app_password'); |
|
199 | - |
|
200 | - if (is_null($appPassword)) { |
|
201 | - try { |
|
202 | - $token = $this->session->getId(); |
|
203 | - } catch (SessionNotAvailableException $ex) { |
|
204 | - return; |
|
205 | - } |
|
206 | - } else { |
|
207 | - $token = $appPassword; |
|
208 | - } |
|
209 | - |
|
210 | - if (!$this->validateToken($token)) { |
|
211 | - // Session was invalidated |
|
212 | - $this->logout(); |
|
213 | - } |
|
214 | - } |
|
215 | - |
|
216 | - /** |
|
217 | - * Checks whether the user is logged in |
|
218 | - * |
|
219 | - * @return bool if logged in |
|
220 | - */ |
|
221 | - public function isLoggedIn() { |
|
222 | - $user = $this->getUser(); |
|
223 | - if (is_null($user)) { |
|
224 | - return false; |
|
225 | - } |
|
226 | - |
|
227 | - return $user->isEnabled(); |
|
228 | - } |
|
229 | - |
|
230 | - /** |
|
231 | - * set the login name |
|
232 | - * |
|
233 | - * @param string|null $loginName for the logged in user |
|
234 | - */ |
|
235 | - public function setLoginName($loginName) { |
|
236 | - if (is_null($loginName)) { |
|
237 | - $this->session->remove('loginname'); |
|
238 | - } else { |
|
239 | - $this->session->set('loginname', $loginName); |
|
240 | - } |
|
241 | - } |
|
242 | - |
|
243 | - /** |
|
244 | - * Get the login name of the current user |
|
245 | - * |
|
246 | - * @return ?string |
|
247 | - */ |
|
248 | - public function getLoginName() { |
|
249 | - if ($this->activeUser) { |
|
250 | - return $this->session->get('loginname'); |
|
251 | - } |
|
252 | - |
|
253 | - $uid = $this->session->get('user_id'); |
|
254 | - if ($uid) { |
|
255 | - $this->activeUser = $this->manager->get($uid); |
|
256 | - return $this->session->get('loginname'); |
|
257 | - } |
|
258 | - |
|
259 | - return null; |
|
260 | - } |
|
261 | - |
|
262 | - /** |
|
263 | - * @return null|string |
|
264 | - */ |
|
265 | - public function getImpersonatingUserID(): ?string { |
|
266 | - return $this->session->get('oldUserId'); |
|
267 | - } |
|
268 | - |
|
269 | - public function setImpersonatingUserID(bool $useCurrentUser = true): void { |
|
270 | - if ($useCurrentUser === false) { |
|
271 | - $this->session->remove('oldUserId'); |
|
272 | - return; |
|
273 | - } |
|
274 | - |
|
275 | - $currentUser = $this->getUser(); |
|
276 | - |
|
277 | - if ($currentUser === null) { |
|
278 | - throw new \OC\User\NoUserException(); |
|
279 | - } |
|
280 | - $this->session->set('oldUserId', $currentUser->getUID()); |
|
281 | - } |
|
282 | - /** |
|
283 | - * set the token id |
|
284 | - * |
|
285 | - * @param int|null $token that was used to log in |
|
286 | - */ |
|
287 | - protected function setToken($token) { |
|
288 | - if ($token === null) { |
|
289 | - $this->session->remove('token-id'); |
|
290 | - } else { |
|
291 | - $this->session->set('token-id', $token); |
|
292 | - } |
|
293 | - } |
|
294 | - |
|
295 | - /** |
|
296 | - * try to log in with the provided credentials |
|
297 | - * |
|
298 | - * @param string $uid |
|
299 | - * @param string $password |
|
300 | - * @return boolean|null |
|
301 | - * @throws LoginException |
|
302 | - */ |
|
303 | - public function login($uid, $password) { |
|
304 | - $this->session->regenerateId(); |
|
305 | - if ($this->validateToken($password, $uid)) { |
|
306 | - return $this->loginWithToken($password); |
|
307 | - } |
|
308 | - return $this->loginWithPassword($uid, $password); |
|
309 | - } |
|
310 | - |
|
311 | - /** |
|
312 | - * @param IUser $user |
|
313 | - * @param array $loginDetails |
|
314 | - * @param bool $regenerateSessionId |
|
315 | - * @return true returns true if login successful or an exception otherwise |
|
316 | - * @throws LoginException |
|
317 | - */ |
|
318 | - public function completeLogin(IUser $user, array $loginDetails, $regenerateSessionId = true) { |
|
319 | - if (!$user->isEnabled()) { |
|
320 | - // disabled users can not log in |
|
321 | - // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory |
|
322 | - $message = \OCP\Util::getL10N('lib')->t('Account disabled'); |
|
323 | - throw new DisabledUserException($message); |
|
324 | - } |
|
325 | - |
|
326 | - if ($regenerateSessionId) { |
|
327 | - $this->session->regenerateId(); |
|
328 | - $this->session->remove(Auth::DAV_AUTHENTICATED); |
|
329 | - } |
|
330 | - |
|
331 | - $this->setUser($user); |
|
332 | - $this->setLoginName($loginDetails['loginName']); |
|
333 | - |
|
334 | - $isToken = isset($loginDetails['token']) && $loginDetails['token'] instanceof IToken; |
|
335 | - if ($isToken) { |
|
336 | - $this->setToken($loginDetails['token']->getId()); |
|
337 | - $this->lockdownManager->setToken($loginDetails['token']); |
|
338 | - $user->updateLastLoginTimestamp(); |
|
339 | - $firstTimeLogin = false; |
|
340 | - } else { |
|
341 | - $this->setToken(null); |
|
342 | - $firstTimeLogin = $user->updateLastLoginTimestamp(); |
|
343 | - } |
|
344 | - |
|
345 | - $this->dispatcher->dispatchTyped(new PostLoginEvent( |
|
346 | - $user, |
|
347 | - $loginDetails['loginName'], |
|
348 | - $loginDetails['password'], |
|
349 | - $isToken |
|
350 | - )); |
|
351 | - $this->manager->emit('\OC\User', 'postLogin', [ |
|
352 | - $user, |
|
353 | - $loginDetails['loginName'], |
|
354 | - $loginDetails['password'], |
|
355 | - $isToken, |
|
356 | - ]); |
|
357 | - if ($this->isLoggedIn()) { |
|
358 | - $this->prepareUserLogin($firstTimeLogin, $regenerateSessionId); |
|
359 | - return true; |
|
360 | - } |
|
361 | - |
|
362 | - $message = \OCP\Util::getL10N('lib')->t('Login canceled by app'); |
|
363 | - throw new LoginException($message); |
|
364 | - } |
|
365 | - |
|
366 | - /** |
|
367 | - * Tries to log in a client |
|
368 | - * |
|
369 | - * Checks token auth enforced |
|
370 | - * Checks 2FA enabled |
|
371 | - * |
|
372 | - * @param string $user |
|
373 | - * @param string $password |
|
374 | - * @param IRequest $request |
|
375 | - * @param IThrottler $throttler |
|
376 | - * @throws LoginException |
|
377 | - * @throws PasswordLoginForbiddenException |
|
378 | - * @return boolean |
|
379 | - */ |
|
380 | - public function logClientIn($user, |
|
381 | - $password, |
|
382 | - IRequest $request, |
|
383 | - IThrottler $throttler) { |
|
384 | - $remoteAddress = $request->getRemoteAddress(); |
|
385 | - $currentDelay = $throttler->sleepDelayOrThrowOnMax($remoteAddress, 'login'); |
|
386 | - |
|
387 | - if ($this->manager instanceof PublicEmitter) { |
|
388 | - $this->manager->emit('\OC\User', 'preLogin', [$user, $password]); |
|
389 | - } |
|
390 | - |
|
391 | - try { |
|
392 | - $isTokenPassword = $this->isTokenPassword($password); |
|
393 | - } catch (ExpiredTokenException $e) { |
|
394 | - // Just return on an expired token no need to check further or record a failed login |
|
395 | - return false; |
|
396 | - } |
|
397 | - |
|
398 | - if (!$isTokenPassword && $this->isTokenAuthEnforced()) { |
|
399 | - throw new PasswordLoginForbiddenException(); |
|
400 | - } |
|
401 | - if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) { |
|
402 | - throw new PasswordLoginForbiddenException(); |
|
403 | - } |
|
404 | - |
|
405 | - // Try to login with this username and password |
|
406 | - if (!$this->login($user, $password)) { |
|
407 | - // Failed, maybe the user used their email address |
|
408 | - if (!filter_var($user, FILTER_VALIDATE_EMAIL)) { |
|
409 | - $this->handleLoginFailed($throttler, $currentDelay, $remoteAddress, $user, $password); |
|
410 | - return false; |
|
411 | - } |
|
412 | - |
|
413 | - if ($isTokenPassword) { |
|
414 | - $dbToken = $this->tokenProvider->getToken($password); |
|
415 | - $userFromToken = $this->manager->get($dbToken->getUID()); |
|
416 | - $isValidEmailLogin = $userFromToken->getEMailAddress() === $user |
|
417 | - && $this->validateTokenLoginName($userFromToken->getEMailAddress(), $dbToken); |
|
418 | - } else { |
|
419 | - $users = $this->manager->getByEmail($user); |
|
420 | - $isValidEmailLogin = (\count($users) === 1 && $this->login($users[0]->getUID(), $password)); |
|
421 | - } |
|
422 | - |
|
423 | - if (!$isValidEmailLogin) { |
|
424 | - $this->handleLoginFailed($throttler, $currentDelay, $remoteAddress, $user, $password); |
|
425 | - return false; |
|
426 | - } |
|
427 | - } |
|
428 | - |
|
429 | - if ($isTokenPassword) { |
|
430 | - $this->session->set('app_password', $password); |
|
431 | - } elseif ($this->supportsCookies($request)) { |
|
432 | - // Password login, but cookies supported -> create (browser) session token |
|
433 | - $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password); |
|
434 | - } |
|
435 | - |
|
436 | - return true; |
|
437 | - } |
|
438 | - |
|
439 | - private function handleLoginFailed(IThrottler $throttler, int $currentDelay, string $remoteAddress, string $user, ?string $password) { |
|
440 | - $this->logger->warning("Login failed: '" . $user . "' (Remote IP: '" . $remoteAddress . "')", ['app' => 'core']); |
|
441 | - |
|
442 | - $throttler->registerAttempt('login', $remoteAddress, ['user' => $user]); |
|
443 | - $this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user, $password)); |
|
444 | - |
|
445 | - if ($currentDelay === 0) { |
|
446 | - $throttler->sleepDelayOrThrowOnMax($remoteAddress, 'login'); |
|
447 | - } |
|
448 | - } |
|
449 | - |
|
450 | - protected function supportsCookies(IRequest $request) { |
|
451 | - if (!is_null($request->getCookie('cookie_test'))) { |
|
452 | - return true; |
|
453 | - } |
|
454 | - setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600); |
|
455 | - return false; |
|
456 | - } |
|
457 | - |
|
458 | - private function isTokenAuthEnforced(): bool { |
|
459 | - return $this->config->getSystemValueBool('token_auth_enforced', false); |
|
460 | - } |
|
461 | - |
|
462 | - protected function isTwoFactorEnforced($username) { |
|
463 | - Util::emitHook( |
|
464 | - '\OCA\Files_Sharing\API\Server2Server', |
|
465 | - 'preLoginNameUsedAsUserName', |
|
466 | - ['uid' => &$username] |
|
467 | - ); |
|
468 | - $user = $this->manager->get($username); |
|
469 | - if (is_null($user)) { |
|
470 | - $users = $this->manager->getByEmail($username); |
|
471 | - if (empty($users)) { |
|
472 | - return false; |
|
473 | - } |
|
474 | - if (count($users) !== 1) { |
|
475 | - return true; |
|
476 | - } |
|
477 | - $user = $users[0]; |
|
478 | - } |
|
479 | - // DI not possible due to cyclic dependencies :'-/ |
|
480 | - return OC::$server->get(TwoFactorAuthManager::class)->isTwoFactorAuthenticated($user); |
|
481 | - } |
|
482 | - |
|
483 | - /** |
|
484 | - * Check if the given 'password' is actually a device token |
|
485 | - * |
|
486 | - * @param string $password |
|
487 | - * @return boolean |
|
488 | - * @throws ExpiredTokenException |
|
489 | - */ |
|
490 | - public function isTokenPassword($password) { |
|
491 | - try { |
|
492 | - $this->tokenProvider->getToken($password); |
|
493 | - return true; |
|
494 | - } catch (ExpiredTokenException $e) { |
|
495 | - throw $e; |
|
496 | - } catch (InvalidTokenException $ex) { |
|
497 | - $this->logger->debug('Token is not valid: ' . $ex->getMessage(), [ |
|
498 | - 'exception' => $ex, |
|
499 | - ]); |
|
500 | - return false; |
|
501 | - } |
|
502 | - } |
|
503 | - |
|
504 | - protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) { |
|
505 | - if ($refreshCsrfToken) { |
|
506 | - // TODO: mock/inject/use non-static |
|
507 | - // Refresh the token |
|
508 | - \OC::$server->get(CsrfTokenManager::class)->refreshToken(); |
|
509 | - } |
|
510 | - |
|
511 | - if ($firstTimeLogin) { |
|
512 | - //we need to pass the user name, which may differ from login name |
|
513 | - $user = $this->getUser()->getUID(); |
|
514 | - OC_Util::setupFS($user); |
|
515 | - |
|
516 | - // TODO: lock necessary? |
|
517 | - //trigger creation of user home and /files folder |
|
518 | - $userFolder = \OC::$server->getUserFolder($user); |
|
519 | - |
|
520 | - try { |
|
521 | - // copy skeleton |
|
522 | - \OC_Util::copySkeleton($user, $userFolder); |
|
523 | - } catch (NotPermittedException $ex) { |
|
524 | - // read only uses |
|
525 | - } |
|
526 | - |
|
527 | - // trigger any other initialization |
|
528 | - \OC::$server->get(IEventDispatcher::class)->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser())); |
|
529 | - \OC::$server->get(IEventDispatcher::class)->dispatchTyped(new UserFirstTimeLoggedInEvent($this->getUser())); |
|
530 | - } |
|
531 | - } |
|
532 | - |
|
533 | - /** |
|
534 | - * Tries to login the user with HTTP Basic Authentication |
|
535 | - * |
|
536 | - * @todo do not allow basic auth if the user is 2FA enforced |
|
537 | - * @param IRequest $request |
|
538 | - * @param IThrottler $throttler |
|
539 | - * @return boolean if the login was successful |
|
540 | - */ |
|
541 | - public function tryBasicAuthLogin(IRequest $request, |
|
542 | - IThrottler $throttler) { |
|
543 | - if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) { |
|
544 | - try { |
|
545 | - if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) { |
|
546 | - /** |
|
547 | - * Add DAV authenticated. This should in an ideal world not be |
|
548 | - * necessary but the iOS App reads cookies from anywhere instead |
|
549 | - * only the DAV endpoint. |
|
550 | - * This makes sure that the cookies will be valid for the whole scope |
|
551 | - * @see https://github.com/owncloud/core/issues/22893 |
|
552 | - */ |
|
553 | - $this->session->set( |
|
554 | - Auth::DAV_AUTHENTICATED, $this->getUser()->getUID() |
|
555 | - ); |
|
556 | - |
|
557 | - // Set the last-password-confirm session to make the sudo mode work |
|
558 | - $this->session->set('last-password-confirm', $this->timeFactory->getTime()); |
|
559 | - |
|
560 | - return true; |
|
561 | - } |
|
562 | - // If credentials were provided, they need to be valid, otherwise we do boom |
|
563 | - throw new LoginException(); |
|
564 | - } catch (PasswordLoginForbiddenException $ex) { |
|
565 | - // Nothing to do |
|
566 | - } |
|
567 | - } |
|
568 | - return false; |
|
569 | - } |
|
570 | - |
|
571 | - /** |
|
572 | - * Log an user in via login name and password |
|
573 | - * |
|
574 | - * @param string $uid |
|
575 | - * @param string $password |
|
576 | - * @return boolean |
|
577 | - * @throws LoginException if an app canceld the login process or the user is not enabled |
|
578 | - */ |
|
579 | - private function loginWithPassword($uid, $password) { |
|
580 | - $user = $this->manager->checkPasswordNoLogging($uid, $password); |
|
581 | - if ($user === false) { |
|
582 | - // Password check failed |
|
583 | - return false; |
|
584 | - } |
|
585 | - |
|
586 | - return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false); |
|
587 | - } |
|
588 | - |
|
589 | - /** |
|
590 | - * Log an user in with a given token (id) |
|
591 | - * |
|
592 | - * @param string $token |
|
593 | - * @return boolean |
|
594 | - * @throws LoginException if an app canceled the login process or the user is not enabled |
|
595 | - */ |
|
596 | - private function loginWithToken($token) { |
|
597 | - try { |
|
598 | - $dbToken = $this->tokenProvider->getToken($token); |
|
599 | - } catch (InvalidTokenException $ex) { |
|
600 | - return false; |
|
601 | - } |
|
602 | - $uid = $dbToken->getUID(); |
|
603 | - |
|
604 | - // When logging in with token, the password must be decrypted first before passing to login hook |
|
605 | - $password = ''; |
|
606 | - try { |
|
607 | - $password = $this->tokenProvider->getPassword($dbToken, $token); |
|
608 | - } catch (PasswordlessTokenException $ex) { |
|
609 | - // Ignore and use empty string instead |
|
610 | - } |
|
611 | - |
|
612 | - $this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]); |
|
613 | - |
|
614 | - $user = $this->manager->get($uid); |
|
615 | - if (is_null($user)) { |
|
616 | - // user does not exist |
|
617 | - return false; |
|
618 | - } |
|
619 | - |
|
620 | - return $this->completeLogin( |
|
621 | - $user, |
|
622 | - [ |
|
623 | - 'loginName' => $dbToken->getLoginName(), |
|
624 | - 'password' => $password, |
|
625 | - 'token' => $dbToken |
|
626 | - ], |
|
627 | - false); |
|
628 | - } |
|
629 | - |
|
630 | - /** |
|
631 | - * Create a new session token for the given user credentials |
|
632 | - * |
|
633 | - * @param IRequest $request |
|
634 | - * @param string $uid user UID |
|
635 | - * @param string $loginName login name |
|
636 | - * @param string $password |
|
637 | - * @param int $remember |
|
638 | - * @return boolean |
|
639 | - */ |
|
640 | - public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) { |
|
641 | - if (is_null($this->manager->get($uid))) { |
|
642 | - // User does not exist |
|
643 | - return false; |
|
644 | - } |
|
645 | - $name = isset($request->server['HTTP_USER_AGENT']) ? mb_convert_encoding($request->server['HTTP_USER_AGENT'], 'UTF-8', 'ISO-8859-1') : 'unknown browser'; |
|
646 | - try { |
|
647 | - $sessionId = $this->session->getId(); |
|
648 | - $pwd = $this->getPassword($password); |
|
649 | - // Make sure the current sessionId has no leftover tokens |
|
650 | - $this->atomic(function () use ($sessionId, $uid, $loginName, $pwd, $name, $remember) { |
|
651 | - $this->tokenProvider->invalidateToken($sessionId); |
|
652 | - $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember); |
|
653 | - }, \OCP\Server::get(IDBConnection::class)); |
|
654 | - return true; |
|
655 | - } catch (SessionNotAvailableException $ex) { |
|
656 | - // This can happen with OCC, where a memory session is used |
|
657 | - // if a memory session is used, we shouldn't create a session token anyway |
|
658 | - return false; |
|
659 | - } |
|
660 | - } |
|
661 | - |
|
662 | - /** |
|
663 | - * Checks if the given password is a token. |
|
664 | - * If yes, the password is extracted from the token. |
|
665 | - * If no, the same password is returned. |
|
666 | - * |
|
667 | - * @param string $password either the login password or a device token |
|
668 | - * @return string|null the password or null if none was set in the token |
|
669 | - */ |
|
670 | - private function getPassword($password) { |
|
671 | - if (is_null($password)) { |
|
672 | - // This is surely no token ;-) |
|
673 | - return null; |
|
674 | - } |
|
675 | - try { |
|
676 | - $token = $this->tokenProvider->getToken($password); |
|
677 | - try { |
|
678 | - return $this->tokenProvider->getPassword($token, $password); |
|
679 | - } catch (PasswordlessTokenException $ex) { |
|
680 | - return null; |
|
681 | - } |
|
682 | - } catch (InvalidTokenException $ex) { |
|
683 | - return $password; |
|
684 | - } |
|
685 | - } |
|
686 | - |
|
687 | - /** |
|
688 | - * @param IToken $dbToken |
|
689 | - * @param string $token |
|
690 | - * @return boolean |
|
691 | - */ |
|
692 | - private function checkTokenCredentials(IToken $dbToken, $token) { |
|
693 | - // Check whether login credentials are still valid and the user was not disabled |
|
694 | - // This check is performed each 5 minutes |
|
695 | - $lastCheck = $dbToken->getLastCheck() ? : 0; |
|
696 | - $now = $this->timeFactory->getTime(); |
|
697 | - if ($lastCheck > ($now - 60 * 5)) { |
|
698 | - // Checked performed recently, nothing to do now |
|
699 | - return true; |
|
700 | - } |
|
701 | - |
|
702 | - try { |
|
703 | - $pwd = $this->tokenProvider->getPassword($dbToken, $token); |
|
704 | - } catch (InvalidTokenException $ex) { |
|
705 | - // An invalid token password was used -> log user out |
|
706 | - return false; |
|
707 | - } catch (PasswordlessTokenException $ex) { |
|
708 | - // Token has no password |
|
709 | - |
|
710 | - if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) { |
|
711 | - $this->tokenProvider->invalidateToken($token); |
|
712 | - return false; |
|
713 | - } |
|
714 | - |
|
715 | - return true; |
|
716 | - } |
|
717 | - |
|
718 | - // Invalidate token if the user is no longer active |
|
719 | - if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) { |
|
720 | - $this->tokenProvider->invalidateToken($token); |
|
721 | - return false; |
|
722 | - } |
|
723 | - |
|
724 | - // If the token password is no longer valid mark it as such |
|
725 | - if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) { |
|
726 | - $this->tokenProvider->markPasswordInvalid($dbToken, $token); |
|
727 | - // User is logged out |
|
728 | - return false; |
|
729 | - } |
|
730 | - |
|
731 | - $dbToken->setLastCheck($now); |
|
732 | - if ($dbToken instanceof PublicKeyToken) { |
|
733 | - $dbToken->setLastActivity($now); |
|
734 | - } |
|
735 | - $this->tokenProvider->updateToken($dbToken); |
|
736 | - return true; |
|
737 | - } |
|
738 | - |
|
739 | - /** |
|
740 | - * Check if the given token exists and performs password/user-enabled checks |
|
741 | - * |
|
742 | - * Invalidates the token if checks fail |
|
743 | - * |
|
744 | - * @param string $token |
|
745 | - * @param string $user login name |
|
746 | - * @return boolean |
|
747 | - */ |
|
748 | - private function validateToken($token, $user = null) { |
|
749 | - try { |
|
750 | - $dbToken = $this->tokenProvider->getToken($token); |
|
751 | - } catch (InvalidTokenException $ex) { |
|
752 | - $this->logger->debug('Session token is invalid because it does not exist', [ |
|
753 | - 'app' => 'core', |
|
754 | - 'user' => $user, |
|
755 | - 'exception' => $ex, |
|
756 | - ]); |
|
757 | - return false; |
|
758 | - } |
|
759 | - |
|
760 | - if (!is_null($user) && !$this->validateTokenLoginName($user, $dbToken)) { |
|
761 | - return false; |
|
762 | - } |
|
763 | - |
|
764 | - if (!$this->checkTokenCredentials($dbToken, $token)) { |
|
765 | - $this->logger->warning('Session token credentials are invalid', [ |
|
766 | - 'app' => 'core', |
|
767 | - 'user' => $user, |
|
768 | - ]); |
|
769 | - return false; |
|
770 | - } |
|
771 | - |
|
772 | - // Update token scope |
|
773 | - $this->lockdownManager->setToken($dbToken); |
|
774 | - |
|
775 | - $this->tokenProvider->updateTokenActivity($dbToken); |
|
776 | - |
|
777 | - return true; |
|
778 | - } |
|
779 | - |
|
780 | - /** |
|
781 | - * Check if login names match |
|
782 | - */ |
|
783 | - private function validateTokenLoginName(?string $loginName, IToken $token): bool { |
|
784 | - if (mb_strtolower($token->getLoginName()) !== mb_strtolower($loginName ?? '')) { |
|
785 | - // TODO: this makes it impossible to use different login names on browser and client |
|
786 | - // e.g. login by e-mail '[email protected]' on browser for generating the token will not |
|
787 | - // allow to use the client token with the login name 'user'. |
|
788 | - $this->logger->error('App token login name does not match', [ |
|
789 | - 'tokenLoginName' => $token->getLoginName(), |
|
790 | - 'sessionLoginName' => $loginName, |
|
791 | - 'app' => 'core', |
|
792 | - 'user' => $token->getUID(), |
|
793 | - ]); |
|
794 | - |
|
795 | - return false; |
|
796 | - } |
|
797 | - |
|
798 | - return true; |
|
799 | - } |
|
800 | - |
|
801 | - /** |
|
802 | - * Tries to login the user with auth token header |
|
803 | - * |
|
804 | - * @param IRequest $request |
|
805 | - * @todo check remember me cookie |
|
806 | - * @return boolean |
|
807 | - */ |
|
808 | - public function tryTokenLogin(IRequest $request) { |
|
809 | - $authHeader = $request->getHeader('Authorization'); |
|
810 | - if (str_starts_with($authHeader, 'Bearer ')) { |
|
811 | - $token = substr($authHeader, 7); |
|
812 | - } elseif ($request->getCookie($this->config->getSystemValueString('instanceid')) !== null) { |
|
813 | - // No auth header, let's try session id, but only if this is an existing |
|
814 | - // session and the request has a session cookie |
|
815 | - try { |
|
816 | - $token = $this->session->getId(); |
|
817 | - } catch (SessionNotAvailableException $ex) { |
|
818 | - return false; |
|
819 | - } |
|
820 | - } else { |
|
821 | - return false; |
|
822 | - } |
|
823 | - |
|
824 | - if (!$this->loginWithToken($token)) { |
|
825 | - return false; |
|
826 | - } |
|
827 | - if (!$this->validateToken($token)) { |
|
828 | - return false; |
|
829 | - } |
|
830 | - |
|
831 | - try { |
|
832 | - $dbToken = $this->tokenProvider->getToken($token); |
|
833 | - } catch (InvalidTokenException $e) { |
|
834 | - // Can't really happen but better save than sorry |
|
835 | - return true; |
|
836 | - } |
|
837 | - |
|
838 | - // Set the session variable so we know this is an app password |
|
839 | - if ($dbToken instanceof PublicKeyToken && $dbToken->getType() === IToken::PERMANENT_TOKEN) { |
|
840 | - $this->session->set('app_password', $token); |
|
841 | - } |
|
842 | - |
|
843 | - return true; |
|
844 | - } |
|
845 | - |
|
846 | - /** |
|
847 | - * perform login using the magic cookie (remember login) |
|
848 | - * |
|
849 | - * @param string $uid the username |
|
850 | - * @param string $currentToken |
|
851 | - * @param string $oldSessionId |
|
852 | - * @return bool |
|
853 | - */ |
|
854 | - public function loginWithCookie($uid, $currentToken, $oldSessionId) { |
|
855 | - $this->session->regenerateId(); |
|
856 | - $this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]); |
|
857 | - $user = $this->manager->get($uid); |
|
858 | - if (is_null($user)) { |
|
859 | - // user does not exist |
|
860 | - return false; |
|
861 | - } |
|
862 | - |
|
863 | - // get stored tokens |
|
864 | - $tokens = $this->config->getUserKeys($uid, 'login_token'); |
|
865 | - // test cookies token against stored tokens |
|
866 | - if (!in_array($currentToken, $tokens, true)) { |
|
867 | - $this->logger->info('Tried to log in but could not verify token', [ |
|
868 | - 'app' => 'core', |
|
869 | - 'user' => $uid, |
|
870 | - ]); |
|
871 | - return false; |
|
872 | - } |
|
873 | - // replace successfully used token with a new one |
|
874 | - $this->config->deleteUserValue($uid, 'login_token', $currentToken); |
|
875 | - $newToken = $this->random->generate(32); |
|
876 | - $this->config->setUserValue($uid, 'login_token', $newToken, (string)$this->timeFactory->getTime()); |
|
877 | - $this->logger->debug('Remember-me token replaced', [ |
|
878 | - 'app' => 'core', |
|
879 | - 'user' => $uid, |
|
880 | - ]); |
|
881 | - |
|
882 | - try { |
|
883 | - $sessionId = $this->session->getId(); |
|
884 | - $token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId); |
|
885 | - $this->logger->debug('Session token replaced', [ |
|
886 | - 'app' => 'core', |
|
887 | - 'user' => $uid, |
|
888 | - ]); |
|
889 | - } catch (SessionNotAvailableException $ex) { |
|
890 | - $this->logger->critical('Could not renew session token for {uid} because the session is unavailable', [ |
|
891 | - 'app' => 'core', |
|
892 | - 'uid' => $uid, |
|
893 | - 'user' => $uid, |
|
894 | - ]); |
|
895 | - return false; |
|
896 | - } catch (InvalidTokenException $ex) { |
|
897 | - $this->logger->error('Renewing session token failed: ' . $ex->getMessage(), [ |
|
898 | - 'app' => 'core', |
|
899 | - 'user' => $uid, |
|
900 | - 'exception' => $ex, |
|
901 | - ]); |
|
902 | - return false; |
|
903 | - } |
|
904 | - |
|
905 | - $this->setMagicInCookie($user->getUID(), $newToken); |
|
906 | - |
|
907 | - //login |
|
908 | - $this->setUser($user); |
|
909 | - $this->setLoginName($token->getLoginName()); |
|
910 | - $this->setToken($token->getId()); |
|
911 | - $this->lockdownManager->setToken($token); |
|
912 | - $user->updateLastLoginTimestamp(); |
|
913 | - $password = null; |
|
914 | - try { |
|
915 | - $password = $this->tokenProvider->getPassword($token, $sessionId); |
|
916 | - } catch (PasswordlessTokenException $ex) { |
|
917 | - // Ignore |
|
918 | - } |
|
919 | - $this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]); |
|
920 | - return true; |
|
921 | - } |
|
922 | - |
|
923 | - /** |
|
924 | - * @param IUser $user |
|
925 | - */ |
|
926 | - public function createRememberMeToken(IUser $user) { |
|
927 | - $token = $this->random->generate(32); |
|
928 | - $this->config->setUserValue($user->getUID(), 'login_token', $token, (string)$this->timeFactory->getTime()); |
|
929 | - $this->setMagicInCookie($user->getUID(), $token); |
|
930 | - } |
|
931 | - |
|
932 | - /** |
|
933 | - * logout the user from the session |
|
934 | - */ |
|
935 | - public function logout() { |
|
936 | - $user = $this->getUser(); |
|
937 | - $this->manager->emit('\OC\User', 'logout', [$user]); |
|
938 | - if ($user !== null) { |
|
939 | - try { |
|
940 | - $token = $this->session->getId(); |
|
941 | - $this->tokenProvider->invalidateToken($token); |
|
942 | - $this->logger->debug('Session token invalidated before logout', [ |
|
943 | - 'user' => $user->getUID(), |
|
944 | - ]); |
|
945 | - } catch (SessionNotAvailableException $ex) { |
|
946 | - } |
|
947 | - } |
|
948 | - $this->logger->debug('Logging out', [ |
|
949 | - 'user' => $user === null ? null : $user->getUID(), |
|
950 | - ]); |
|
951 | - $this->setUser(null); |
|
952 | - $this->setLoginName(null); |
|
953 | - $this->setToken(null); |
|
954 | - $this->unsetMagicInCookie(); |
|
955 | - $this->session->clear(); |
|
956 | - $this->manager->emit('\OC\User', 'postLogout', [$user]); |
|
957 | - } |
|
958 | - |
|
959 | - /** |
|
960 | - * Set cookie value to use in next page load |
|
961 | - * |
|
962 | - * @param string $username username to be set |
|
963 | - * @param string $token |
|
964 | - */ |
|
965 | - public function setMagicInCookie($username, $token) { |
|
966 | - $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https'; |
|
967 | - $webRoot = \OC::$WEBROOT; |
|
968 | - if ($webRoot === '') { |
|
969 | - $webRoot = '/'; |
|
970 | - } |
|
971 | - $domain = $this->config->getSystemValueString('cookie_domain'); |
|
972 | - |
|
973 | - $maxAge = $this->config->getSystemValueInt('remember_login_cookie_lifetime', 60 * 60 * 24 * 15); |
|
974 | - \OC\Http\CookieHelper::setCookie( |
|
975 | - 'nc_username', |
|
976 | - $username, |
|
977 | - $maxAge, |
|
978 | - $webRoot, |
|
979 | - $domain, |
|
980 | - $secureCookie, |
|
981 | - true, |
|
982 | - \OC\Http\CookieHelper::SAMESITE_LAX |
|
983 | - ); |
|
984 | - \OC\Http\CookieHelper::setCookie( |
|
985 | - 'nc_token', |
|
986 | - $token, |
|
987 | - $maxAge, |
|
988 | - $webRoot, |
|
989 | - $domain, |
|
990 | - $secureCookie, |
|
991 | - true, |
|
992 | - \OC\Http\CookieHelper::SAMESITE_LAX |
|
993 | - ); |
|
994 | - try { |
|
995 | - \OC\Http\CookieHelper::setCookie( |
|
996 | - 'nc_session_id', |
|
997 | - $this->session->getId(), |
|
998 | - $maxAge, |
|
999 | - $webRoot, |
|
1000 | - $domain, |
|
1001 | - $secureCookie, |
|
1002 | - true, |
|
1003 | - \OC\Http\CookieHelper::SAMESITE_LAX |
|
1004 | - ); |
|
1005 | - } catch (SessionNotAvailableException $ex) { |
|
1006 | - // ignore |
|
1007 | - } |
|
1008 | - } |
|
1009 | - |
|
1010 | - /** |
|
1011 | - * Remove cookie for "remember username" |
|
1012 | - */ |
|
1013 | - public function unsetMagicInCookie() { |
|
1014 | - //TODO: DI for cookies and IRequest |
|
1015 | - $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https'; |
|
1016 | - $domain = $this->config->getSystemValueString('cookie_domain'); |
|
1017 | - |
|
1018 | - unset($_COOKIE['nc_username']); //TODO: DI |
|
1019 | - unset($_COOKIE['nc_token']); |
|
1020 | - unset($_COOKIE['nc_session_id']); |
|
1021 | - setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, $domain, $secureCookie, true); |
|
1022 | - setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, $domain, $secureCookie, true); |
|
1023 | - setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, $domain, $secureCookie, true); |
|
1024 | - // old cookies might be stored under /webroot/ instead of /webroot |
|
1025 | - // and Firefox doesn't like it! |
|
1026 | - setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', $domain, $secureCookie, true); |
|
1027 | - setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', $domain, $secureCookie, true); |
|
1028 | - setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', $domain, $secureCookie, true); |
|
1029 | - } |
|
1030 | - |
|
1031 | - /** |
|
1032 | - * Update password of the browser session token if there is one |
|
1033 | - * |
|
1034 | - * @param string $password |
|
1035 | - */ |
|
1036 | - public function updateSessionTokenPassword($password) { |
|
1037 | - try { |
|
1038 | - $sessionId = $this->session->getId(); |
|
1039 | - $token = $this->tokenProvider->getToken($sessionId); |
|
1040 | - $this->tokenProvider->setPassword($token, $sessionId, $password); |
|
1041 | - } catch (SessionNotAvailableException $ex) { |
|
1042 | - // Nothing to do |
|
1043 | - } catch (InvalidTokenException $ex) { |
|
1044 | - // Nothing to do |
|
1045 | - } |
|
1046 | - } |
|
1047 | - |
|
1048 | - public function updateTokens(string $uid, string $password) { |
|
1049 | - $this->tokenProvider->updatePasswords($uid, $password); |
|
1050 | - } |
|
68 | + use TTransactional; |
|
69 | + |
|
70 | + /** @var User $activeUser */ |
|
71 | + protected $activeUser; |
|
72 | + |
|
73 | + public function __construct( |
|
74 | + private Manager $manager, |
|
75 | + private ISession $session, |
|
76 | + private ITimeFactory $timeFactory, |
|
77 | + private ?IProvider $tokenProvider, |
|
78 | + private IConfig $config, |
|
79 | + private ISecureRandom $random, |
|
80 | + private ILockdownManager $lockdownManager, |
|
81 | + private LoggerInterface $logger, |
|
82 | + private IEventDispatcher $dispatcher, |
|
83 | + ) { |
|
84 | + } |
|
85 | + |
|
86 | + /** |
|
87 | + * @param IProvider $provider |
|
88 | + */ |
|
89 | + public function setTokenProvider(IProvider $provider) { |
|
90 | + $this->tokenProvider = $provider; |
|
91 | + } |
|
92 | + |
|
93 | + /** |
|
94 | + * @param string $scope |
|
95 | + * @param string $method |
|
96 | + * @param callable $callback |
|
97 | + */ |
|
98 | + public function listen($scope, $method, callable $callback) { |
|
99 | + $this->manager->listen($scope, $method, $callback); |
|
100 | + } |
|
101 | + |
|
102 | + /** |
|
103 | + * @param string $scope optional |
|
104 | + * @param string $method optional |
|
105 | + * @param callable $callback optional |
|
106 | + */ |
|
107 | + public function removeListener($scope = null, $method = null, ?callable $callback = null) { |
|
108 | + $this->manager->removeListener($scope, $method, $callback); |
|
109 | + } |
|
110 | + |
|
111 | + /** |
|
112 | + * get the manager object |
|
113 | + * |
|
114 | + * @return Manager|PublicEmitter |
|
115 | + */ |
|
116 | + public function getManager() { |
|
117 | + return $this->manager; |
|
118 | + } |
|
119 | + |
|
120 | + /** |
|
121 | + * get the session object |
|
122 | + * |
|
123 | + * @return ISession |
|
124 | + */ |
|
125 | + public function getSession() { |
|
126 | + return $this->session; |
|
127 | + } |
|
128 | + |
|
129 | + /** |
|
130 | + * set the session object |
|
131 | + * |
|
132 | + * @param ISession $session |
|
133 | + */ |
|
134 | + public function setSession(ISession $session) { |
|
135 | + if ($this->session instanceof ISession) { |
|
136 | + $this->session->close(); |
|
137 | + } |
|
138 | + $this->session = $session; |
|
139 | + $this->activeUser = null; |
|
140 | + } |
|
141 | + |
|
142 | + /** |
|
143 | + * set the currently active user |
|
144 | + * |
|
145 | + * @param IUser|null $user |
|
146 | + */ |
|
147 | + public function setUser($user) { |
|
148 | + if (is_null($user)) { |
|
149 | + $this->session->remove('user_id'); |
|
150 | + } else { |
|
151 | + $this->session->set('user_id', $user->getUID()); |
|
152 | + } |
|
153 | + $this->activeUser = $user; |
|
154 | + } |
|
155 | + |
|
156 | + /** |
|
157 | + * Temporarily set the currently active user without persisting in the session |
|
158 | + * |
|
159 | + * @param IUser|null $user |
|
160 | + */ |
|
161 | + public function setVolatileActiveUser(?IUser $user): void { |
|
162 | + $this->activeUser = $user; |
|
163 | + } |
|
164 | + |
|
165 | + /** |
|
166 | + * get the current active user |
|
167 | + * |
|
168 | + * @return IUser|null Current user, otherwise null |
|
169 | + */ |
|
170 | + public function getUser() { |
|
171 | + // FIXME: This is a quick'n dirty work-around for the incognito mode as |
|
172 | + // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155 |
|
173 | + if (OC_User::isIncognitoMode()) { |
|
174 | + return null; |
|
175 | + } |
|
176 | + if (is_null($this->activeUser)) { |
|
177 | + $uid = $this->session->get('user_id'); |
|
178 | + if (is_null($uid)) { |
|
179 | + return null; |
|
180 | + } |
|
181 | + $this->activeUser = $this->manager->get($uid); |
|
182 | + if (is_null($this->activeUser)) { |
|
183 | + return null; |
|
184 | + } |
|
185 | + $this->validateSession(); |
|
186 | + } |
|
187 | + return $this->activeUser; |
|
188 | + } |
|
189 | + |
|
190 | + /** |
|
191 | + * Validate whether the current session is valid |
|
192 | + * |
|
193 | + * - For token-authenticated clients, the token validity is checked |
|
194 | + * - For browsers, the session token validity is checked |
|
195 | + */ |
|
196 | + protected function validateSession() { |
|
197 | + $token = null; |
|
198 | + $appPassword = $this->session->get('app_password'); |
|
199 | + |
|
200 | + if (is_null($appPassword)) { |
|
201 | + try { |
|
202 | + $token = $this->session->getId(); |
|
203 | + } catch (SessionNotAvailableException $ex) { |
|
204 | + return; |
|
205 | + } |
|
206 | + } else { |
|
207 | + $token = $appPassword; |
|
208 | + } |
|
209 | + |
|
210 | + if (!$this->validateToken($token)) { |
|
211 | + // Session was invalidated |
|
212 | + $this->logout(); |
|
213 | + } |
|
214 | + } |
|
215 | + |
|
216 | + /** |
|
217 | + * Checks whether the user is logged in |
|
218 | + * |
|
219 | + * @return bool if logged in |
|
220 | + */ |
|
221 | + public function isLoggedIn() { |
|
222 | + $user = $this->getUser(); |
|
223 | + if (is_null($user)) { |
|
224 | + return false; |
|
225 | + } |
|
226 | + |
|
227 | + return $user->isEnabled(); |
|
228 | + } |
|
229 | + |
|
230 | + /** |
|
231 | + * set the login name |
|
232 | + * |
|
233 | + * @param string|null $loginName for the logged in user |
|
234 | + */ |
|
235 | + public function setLoginName($loginName) { |
|
236 | + if (is_null($loginName)) { |
|
237 | + $this->session->remove('loginname'); |
|
238 | + } else { |
|
239 | + $this->session->set('loginname', $loginName); |
|
240 | + } |
|
241 | + } |
|
242 | + |
|
243 | + /** |
|
244 | + * Get the login name of the current user |
|
245 | + * |
|
246 | + * @return ?string |
|
247 | + */ |
|
248 | + public function getLoginName() { |
|
249 | + if ($this->activeUser) { |
|
250 | + return $this->session->get('loginname'); |
|
251 | + } |
|
252 | + |
|
253 | + $uid = $this->session->get('user_id'); |
|
254 | + if ($uid) { |
|
255 | + $this->activeUser = $this->manager->get($uid); |
|
256 | + return $this->session->get('loginname'); |
|
257 | + } |
|
258 | + |
|
259 | + return null; |
|
260 | + } |
|
261 | + |
|
262 | + /** |
|
263 | + * @return null|string |
|
264 | + */ |
|
265 | + public function getImpersonatingUserID(): ?string { |
|
266 | + return $this->session->get('oldUserId'); |
|
267 | + } |
|
268 | + |
|
269 | + public function setImpersonatingUserID(bool $useCurrentUser = true): void { |
|
270 | + if ($useCurrentUser === false) { |
|
271 | + $this->session->remove('oldUserId'); |
|
272 | + return; |
|
273 | + } |
|
274 | + |
|
275 | + $currentUser = $this->getUser(); |
|
276 | + |
|
277 | + if ($currentUser === null) { |
|
278 | + throw new \OC\User\NoUserException(); |
|
279 | + } |
|
280 | + $this->session->set('oldUserId', $currentUser->getUID()); |
|
281 | + } |
|
282 | + /** |
|
283 | + * set the token id |
|
284 | + * |
|
285 | + * @param int|null $token that was used to log in |
|
286 | + */ |
|
287 | + protected function setToken($token) { |
|
288 | + if ($token === null) { |
|
289 | + $this->session->remove('token-id'); |
|
290 | + } else { |
|
291 | + $this->session->set('token-id', $token); |
|
292 | + } |
|
293 | + } |
|
294 | + |
|
295 | + /** |
|
296 | + * try to log in with the provided credentials |
|
297 | + * |
|
298 | + * @param string $uid |
|
299 | + * @param string $password |
|
300 | + * @return boolean|null |
|
301 | + * @throws LoginException |
|
302 | + */ |
|
303 | + public function login($uid, $password) { |
|
304 | + $this->session->regenerateId(); |
|
305 | + if ($this->validateToken($password, $uid)) { |
|
306 | + return $this->loginWithToken($password); |
|
307 | + } |
|
308 | + return $this->loginWithPassword($uid, $password); |
|
309 | + } |
|
310 | + |
|
311 | + /** |
|
312 | + * @param IUser $user |
|
313 | + * @param array $loginDetails |
|
314 | + * @param bool $regenerateSessionId |
|
315 | + * @return true returns true if login successful or an exception otherwise |
|
316 | + * @throws LoginException |
|
317 | + */ |
|
318 | + public function completeLogin(IUser $user, array $loginDetails, $regenerateSessionId = true) { |
|
319 | + if (!$user->isEnabled()) { |
|
320 | + // disabled users can not log in |
|
321 | + // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory |
|
322 | + $message = \OCP\Util::getL10N('lib')->t('Account disabled'); |
|
323 | + throw new DisabledUserException($message); |
|
324 | + } |
|
325 | + |
|
326 | + if ($regenerateSessionId) { |
|
327 | + $this->session->regenerateId(); |
|
328 | + $this->session->remove(Auth::DAV_AUTHENTICATED); |
|
329 | + } |
|
330 | + |
|
331 | + $this->setUser($user); |
|
332 | + $this->setLoginName($loginDetails['loginName']); |
|
333 | + |
|
334 | + $isToken = isset($loginDetails['token']) && $loginDetails['token'] instanceof IToken; |
|
335 | + if ($isToken) { |
|
336 | + $this->setToken($loginDetails['token']->getId()); |
|
337 | + $this->lockdownManager->setToken($loginDetails['token']); |
|
338 | + $user->updateLastLoginTimestamp(); |
|
339 | + $firstTimeLogin = false; |
|
340 | + } else { |
|
341 | + $this->setToken(null); |
|
342 | + $firstTimeLogin = $user->updateLastLoginTimestamp(); |
|
343 | + } |
|
344 | + |
|
345 | + $this->dispatcher->dispatchTyped(new PostLoginEvent( |
|
346 | + $user, |
|
347 | + $loginDetails['loginName'], |
|
348 | + $loginDetails['password'], |
|
349 | + $isToken |
|
350 | + )); |
|
351 | + $this->manager->emit('\OC\User', 'postLogin', [ |
|
352 | + $user, |
|
353 | + $loginDetails['loginName'], |
|
354 | + $loginDetails['password'], |
|
355 | + $isToken, |
|
356 | + ]); |
|
357 | + if ($this->isLoggedIn()) { |
|
358 | + $this->prepareUserLogin($firstTimeLogin, $regenerateSessionId); |
|
359 | + return true; |
|
360 | + } |
|
361 | + |
|
362 | + $message = \OCP\Util::getL10N('lib')->t('Login canceled by app'); |
|
363 | + throw new LoginException($message); |
|
364 | + } |
|
365 | + |
|
366 | + /** |
|
367 | + * Tries to log in a client |
|
368 | + * |
|
369 | + * Checks token auth enforced |
|
370 | + * Checks 2FA enabled |
|
371 | + * |
|
372 | + * @param string $user |
|
373 | + * @param string $password |
|
374 | + * @param IRequest $request |
|
375 | + * @param IThrottler $throttler |
|
376 | + * @throws LoginException |
|
377 | + * @throws PasswordLoginForbiddenException |
|
378 | + * @return boolean |
|
379 | + */ |
|
380 | + public function logClientIn($user, |
|
381 | + $password, |
|
382 | + IRequest $request, |
|
383 | + IThrottler $throttler) { |
|
384 | + $remoteAddress = $request->getRemoteAddress(); |
|
385 | + $currentDelay = $throttler->sleepDelayOrThrowOnMax($remoteAddress, 'login'); |
|
386 | + |
|
387 | + if ($this->manager instanceof PublicEmitter) { |
|
388 | + $this->manager->emit('\OC\User', 'preLogin', [$user, $password]); |
|
389 | + } |
|
390 | + |
|
391 | + try { |
|
392 | + $isTokenPassword = $this->isTokenPassword($password); |
|
393 | + } catch (ExpiredTokenException $e) { |
|
394 | + // Just return on an expired token no need to check further or record a failed login |
|
395 | + return false; |
|
396 | + } |
|
397 | + |
|
398 | + if (!$isTokenPassword && $this->isTokenAuthEnforced()) { |
|
399 | + throw new PasswordLoginForbiddenException(); |
|
400 | + } |
|
401 | + if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) { |
|
402 | + throw new PasswordLoginForbiddenException(); |
|
403 | + } |
|
404 | + |
|
405 | + // Try to login with this username and password |
|
406 | + if (!$this->login($user, $password)) { |
|
407 | + // Failed, maybe the user used their email address |
|
408 | + if (!filter_var($user, FILTER_VALIDATE_EMAIL)) { |
|
409 | + $this->handleLoginFailed($throttler, $currentDelay, $remoteAddress, $user, $password); |
|
410 | + return false; |
|
411 | + } |
|
412 | + |
|
413 | + if ($isTokenPassword) { |
|
414 | + $dbToken = $this->tokenProvider->getToken($password); |
|
415 | + $userFromToken = $this->manager->get($dbToken->getUID()); |
|
416 | + $isValidEmailLogin = $userFromToken->getEMailAddress() === $user |
|
417 | + && $this->validateTokenLoginName($userFromToken->getEMailAddress(), $dbToken); |
|
418 | + } else { |
|
419 | + $users = $this->manager->getByEmail($user); |
|
420 | + $isValidEmailLogin = (\count($users) === 1 && $this->login($users[0]->getUID(), $password)); |
|
421 | + } |
|
422 | + |
|
423 | + if (!$isValidEmailLogin) { |
|
424 | + $this->handleLoginFailed($throttler, $currentDelay, $remoteAddress, $user, $password); |
|
425 | + return false; |
|
426 | + } |
|
427 | + } |
|
428 | + |
|
429 | + if ($isTokenPassword) { |
|
430 | + $this->session->set('app_password', $password); |
|
431 | + } elseif ($this->supportsCookies($request)) { |
|
432 | + // Password login, but cookies supported -> create (browser) session token |
|
433 | + $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password); |
|
434 | + } |
|
435 | + |
|
436 | + return true; |
|
437 | + } |
|
438 | + |
|
439 | + private function handleLoginFailed(IThrottler $throttler, int $currentDelay, string $remoteAddress, string $user, ?string $password) { |
|
440 | + $this->logger->warning("Login failed: '" . $user . "' (Remote IP: '" . $remoteAddress . "')", ['app' => 'core']); |
|
441 | + |
|
442 | + $throttler->registerAttempt('login', $remoteAddress, ['user' => $user]); |
|
443 | + $this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user, $password)); |
|
444 | + |
|
445 | + if ($currentDelay === 0) { |
|
446 | + $throttler->sleepDelayOrThrowOnMax($remoteAddress, 'login'); |
|
447 | + } |
|
448 | + } |
|
449 | + |
|
450 | + protected function supportsCookies(IRequest $request) { |
|
451 | + if (!is_null($request->getCookie('cookie_test'))) { |
|
452 | + return true; |
|
453 | + } |
|
454 | + setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600); |
|
455 | + return false; |
|
456 | + } |
|
457 | + |
|
458 | + private function isTokenAuthEnforced(): bool { |
|
459 | + return $this->config->getSystemValueBool('token_auth_enforced', false); |
|
460 | + } |
|
461 | + |
|
462 | + protected function isTwoFactorEnforced($username) { |
|
463 | + Util::emitHook( |
|
464 | + '\OCA\Files_Sharing\API\Server2Server', |
|
465 | + 'preLoginNameUsedAsUserName', |
|
466 | + ['uid' => &$username] |
|
467 | + ); |
|
468 | + $user = $this->manager->get($username); |
|
469 | + if (is_null($user)) { |
|
470 | + $users = $this->manager->getByEmail($username); |
|
471 | + if (empty($users)) { |
|
472 | + return false; |
|
473 | + } |
|
474 | + if (count($users) !== 1) { |
|
475 | + return true; |
|
476 | + } |
|
477 | + $user = $users[0]; |
|
478 | + } |
|
479 | + // DI not possible due to cyclic dependencies :'-/ |
|
480 | + return OC::$server->get(TwoFactorAuthManager::class)->isTwoFactorAuthenticated($user); |
|
481 | + } |
|
482 | + |
|
483 | + /** |
|
484 | + * Check if the given 'password' is actually a device token |
|
485 | + * |
|
486 | + * @param string $password |
|
487 | + * @return boolean |
|
488 | + * @throws ExpiredTokenException |
|
489 | + */ |
|
490 | + public function isTokenPassword($password) { |
|
491 | + try { |
|
492 | + $this->tokenProvider->getToken($password); |
|
493 | + return true; |
|
494 | + } catch (ExpiredTokenException $e) { |
|
495 | + throw $e; |
|
496 | + } catch (InvalidTokenException $ex) { |
|
497 | + $this->logger->debug('Token is not valid: ' . $ex->getMessage(), [ |
|
498 | + 'exception' => $ex, |
|
499 | + ]); |
|
500 | + return false; |
|
501 | + } |
|
502 | + } |
|
503 | + |
|
504 | + protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) { |
|
505 | + if ($refreshCsrfToken) { |
|
506 | + // TODO: mock/inject/use non-static |
|
507 | + // Refresh the token |
|
508 | + \OC::$server->get(CsrfTokenManager::class)->refreshToken(); |
|
509 | + } |
|
510 | + |
|
511 | + if ($firstTimeLogin) { |
|
512 | + //we need to pass the user name, which may differ from login name |
|
513 | + $user = $this->getUser()->getUID(); |
|
514 | + OC_Util::setupFS($user); |
|
515 | + |
|
516 | + // TODO: lock necessary? |
|
517 | + //trigger creation of user home and /files folder |
|
518 | + $userFolder = \OC::$server->getUserFolder($user); |
|
519 | + |
|
520 | + try { |
|
521 | + // copy skeleton |
|
522 | + \OC_Util::copySkeleton($user, $userFolder); |
|
523 | + } catch (NotPermittedException $ex) { |
|
524 | + // read only uses |
|
525 | + } |
|
526 | + |
|
527 | + // trigger any other initialization |
|
528 | + \OC::$server->get(IEventDispatcher::class)->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser())); |
|
529 | + \OC::$server->get(IEventDispatcher::class)->dispatchTyped(new UserFirstTimeLoggedInEvent($this->getUser())); |
|
530 | + } |
|
531 | + } |
|
532 | + |
|
533 | + /** |
|
534 | + * Tries to login the user with HTTP Basic Authentication |
|
535 | + * |
|
536 | + * @todo do not allow basic auth if the user is 2FA enforced |
|
537 | + * @param IRequest $request |
|
538 | + * @param IThrottler $throttler |
|
539 | + * @return boolean if the login was successful |
|
540 | + */ |
|
541 | + public function tryBasicAuthLogin(IRequest $request, |
|
542 | + IThrottler $throttler) { |
|
543 | + if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) { |
|
544 | + try { |
|
545 | + if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) { |
|
546 | + /** |
|
547 | + * Add DAV authenticated. This should in an ideal world not be |
|
548 | + * necessary but the iOS App reads cookies from anywhere instead |
|
549 | + * only the DAV endpoint. |
|
550 | + * This makes sure that the cookies will be valid for the whole scope |
|
551 | + * @see https://github.com/owncloud/core/issues/22893 |
|
552 | + */ |
|
553 | + $this->session->set( |
|
554 | + Auth::DAV_AUTHENTICATED, $this->getUser()->getUID() |
|
555 | + ); |
|
556 | + |
|
557 | + // Set the last-password-confirm session to make the sudo mode work |
|
558 | + $this->session->set('last-password-confirm', $this->timeFactory->getTime()); |
|
559 | + |
|
560 | + return true; |
|
561 | + } |
|
562 | + // If credentials were provided, they need to be valid, otherwise we do boom |
|
563 | + throw new LoginException(); |
|
564 | + } catch (PasswordLoginForbiddenException $ex) { |
|
565 | + // Nothing to do |
|
566 | + } |
|
567 | + } |
|
568 | + return false; |
|
569 | + } |
|
570 | + |
|
571 | + /** |
|
572 | + * Log an user in via login name and password |
|
573 | + * |
|
574 | + * @param string $uid |
|
575 | + * @param string $password |
|
576 | + * @return boolean |
|
577 | + * @throws LoginException if an app canceld the login process or the user is not enabled |
|
578 | + */ |
|
579 | + private function loginWithPassword($uid, $password) { |
|
580 | + $user = $this->manager->checkPasswordNoLogging($uid, $password); |
|
581 | + if ($user === false) { |
|
582 | + // Password check failed |
|
583 | + return false; |
|
584 | + } |
|
585 | + |
|
586 | + return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false); |
|
587 | + } |
|
588 | + |
|
589 | + /** |
|
590 | + * Log an user in with a given token (id) |
|
591 | + * |
|
592 | + * @param string $token |
|
593 | + * @return boolean |
|
594 | + * @throws LoginException if an app canceled the login process or the user is not enabled |
|
595 | + */ |
|
596 | + private function loginWithToken($token) { |
|
597 | + try { |
|
598 | + $dbToken = $this->tokenProvider->getToken($token); |
|
599 | + } catch (InvalidTokenException $ex) { |
|
600 | + return false; |
|
601 | + } |
|
602 | + $uid = $dbToken->getUID(); |
|
603 | + |
|
604 | + // When logging in with token, the password must be decrypted first before passing to login hook |
|
605 | + $password = ''; |
|
606 | + try { |
|
607 | + $password = $this->tokenProvider->getPassword($dbToken, $token); |
|
608 | + } catch (PasswordlessTokenException $ex) { |
|
609 | + // Ignore and use empty string instead |
|
610 | + } |
|
611 | + |
|
612 | + $this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]); |
|
613 | + |
|
614 | + $user = $this->manager->get($uid); |
|
615 | + if (is_null($user)) { |
|
616 | + // user does not exist |
|
617 | + return false; |
|
618 | + } |
|
619 | + |
|
620 | + return $this->completeLogin( |
|
621 | + $user, |
|
622 | + [ |
|
623 | + 'loginName' => $dbToken->getLoginName(), |
|
624 | + 'password' => $password, |
|
625 | + 'token' => $dbToken |
|
626 | + ], |
|
627 | + false); |
|
628 | + } |
|
629 | + |
|
630 | + /** |
|
631 | + * Create a new session token for the given user credentials |
|
632 | + * |
|
633 | + * @param IRequest $request |
|
634 | + * @param string $uid user UID |
|
635 | + * @param string $loginName login name |
|
636 | + * @param string $password |
|
637 | + * @param int $remember |
|
638 | + * @return boolean |
|
639 | + */ |
|
640 | + public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) { |
|
641 | + if (is_null($this->manager->get($uid))) { |
|
642 | + // User does not exist |
|
643 | + return false; |
|
644 | + } |
|
645 | + $name = isset($request->server['HTTP_USER_AGENT']) ? mb_convert_encoding($request->server['HTTP_USER_AGENT'], 'UTF-8', 'ISO-8859-1') : 'unknown browser'; |
|
646 | + try { |
|
647 | + $sessionId = $this->session->getId(); |
|
648 | + $pwd = $this->getPassword($password); |
|
649 | + // Make sure the current sessionId has no leftover tokens |
|
650 | + $this->atomic(function () use ($sessionId, $uid, $loginName, $pwd, $name, $remember) { |
|
651 | + $this->tokenProvider->invalidateToken($sessionId); |
|
652 | + $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember); |
|
653 | + }, \OCP\Server::get(IDBConnection::class)); |
|
654 | + return true; |
|
655 | + } catch (SessionNotAvailableException $ex) { |
|
656 | + // This can happen with OCC, where a memory session is used |
|
657 | + // if a memory session is used, we shouldn't create a session token anyway |
|
658 | + return false; |
|
659 | + } |
|
660 | + } |
|
661 | + |
|
662 | + /** |
|
663 | + * Checks if the given password is a token. |
|
664 | + * If yes, the password is extracted from the token. |
|
665 | + * If no, the same password is returned. |
|
666 | + * |
|
667 | + * @param string $password either the login password or a device token |
|
668 | + * @return string|null the password or null if none was set in the token |
|
669 | + */ |
|
670 | + private function getPassword($password) { |
|
671 | + if (is_null($password)) { |
|
672 | + // This is surely no token ;-) |
|
673 | + return null; |
|
674 | + } |
|
675 | + try { |
|
676 | + $token = $this->tokenProvider->getToken($password); |
|
677 | + try { |
|
678 | + return $this->tokenProvider->getPassword($token, $password); |
|
679 | + } catch (PasswordlessTokenException $ex) { |
|
680 | + return null; |
|
681 | + } |
|
682 | + } catch (InvalidTokenException $ex) { |
|
683 | + return $password; |
|
684 | + } |
|
685 | + } |
|
686 | + |
|
687 | + /** |
|
688 | + * @param IToken $dbToken |
|
689 | + * @param string $token |
|
690 | + * @return boolean |
|
691 | + */ |
|
692 | + private function checkTokenCredentials(IToken $dbToken, $token) { |
|
693 | + // Check whether login credentials are still valid and the user was not disabled |
|
694 | + // This check is performed each 5 minutes |
|
695 | + $lastCheck = $dbToken->getLastCheck() ? : 0; |
|
696 | + $now = $this->timeFactory->getTime(); |
|
697 | + if ($lastCheck > ($now - 60 * 5)) { |
|
698 | + // Checked performed recently, nothing to do now |
|
699 | + return true; |
|
700 | + } |
|
701 | + |
|
702 | + try { |
|
703 | + $pwd = $this->tokenProvider->getPassword($dbToken, $token); |
|
704 | + } catch (InvalidTokenException $ex) { |
|
705 | + // An invalid token password was used -> log user out |
|
706 | + return false; |
|
707 | + } catch (PasswordlessTokenException $ex) { |
|
708 | + // Token has no password |
|
709 | + |
|
710 | + if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) { |
|
711 | + $this->tokenProvider->invalidateToken($token); |
|
712 | + return false; |
|
713 | + } |
|
714 | + |
|
715 | + return true; |
|
716 | + } |
|
717 | + |
|
718 | + // Invalidate token if the user is no longer active |
|
719 | + if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) { |
|
720 | + $this->tokenProvider->invalidateToken($token); |
|
721 | + return false; |
|
722 | + } |
|
723 | + |
|
724 | + // If the token password is no longer valid mark it as such |
|
725 | + if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) { |
|
726 | + $this->tokenProvider->markPasswordInvalid($dbToken, $token); |
|
727 | + // User is logged out |
|
728 | + return false; |
|
729 | + } |
|
730 | + |
|
731 | + $dbToken->setLastCheck($now); |
|
732 | + if ($dbToken instanceof PublicKeyToken) { |
|
733 | + $dbToken->setLastActivity($now); |
|
734 | + } |
|
735 | + $this->tokenProvider->updateToken($dbToken); |
|
736 | + return true; |
|
737 | + } |
|
738 | + |
|
739 | + /** |
|
740 | + * Check if the given token exists and performs password/user-enabled checks |
|
741 | + * |
|
742 | + * Invalidates the token if checks fail |
|
743 | + * |
|
744 | + * @param string $token |
|
745 | + * @param string $user login name |
|
746 | + * @return boolean |
|
747 | + */ |
|
748 | + private function validateToken($token, $user = null) { |
|
749 | + try { |
|
750 | + $dbToken = $this->tokenProvider->getToken($token); |
|
751 | + } catch (InvalidTokenException $ex) { |
|
752 | + $this->logger->debug('Session token is invalid because it does not exist', [ |
|
753 | + 'app' => 'core', |
|
754 | + 'user' => $user, |
|
755 | + 'exception' => $ex, |
|
756 | + ]); |
|
757 | + return false; |
|
758 | + } |
|
759 | + |
|
760 | + if (!is_null($user) && !$this->validateTokenLoginName($user, $dbToken)) { |
|
761 | + return false; |
|
762 | + } |
|
763 | + |
|
764 | + if (!$this->checkTokenCredentials($dbToken, $token)) { |
|
765 | + $this->logger->warning('Session token credentials are invalid', [ |
|
766 | + 'app' => 'core', |
|
767 | + 'user' => $user, |
|
768 | + ]); |
|
769 | + return false; |
|
770 | + } |
|
771 | + |
|
772 | + // Update token scope |
|
773 | + $this->lockdownManager->setToken($dbToken); |
|
774 | + |
|
775 | + $this->tokenProvider->updateTokenActivity($dbToken); |
|
776 | + |
|
777 | + return true; |
|
778 | + } |
|
779 | + |
|
780 | + /** |
|
781 | + * Check if login names match |
|
782 | + */ |
|
783 | + private function validateTokenLoginName(?string $loginName, IToken $token): bool { |
|
784 | + if (mb_strtolower($token->getLoginName()) !== mb_strtolower($loginName ?? '')) { |
|
785 | + // TODO: this makes it impossible to use different login names on browser and client |
|
786 | + // e.g. login by e-mail '[email protected]' on browser for generating the token will not |
|
787 | + // allow to use the client token with the login name 'user'. |
|
788 | + $this->logger->error('App token login name does not match', [ |
|
789 | + 'tokenLoginName' => $token->getLoginName(), |
|
790 | + 'sessionLoginName' => $loginName, |
|
791 | + 'app' => 'core', |
|
792 | + 'user' => $token->getUID(), |
|
793 | + ]); |
|
794 | + |
|
795 | + return false; |
|
796 | + } |
|
797 | + |
|
798 | + return true; |
|
799 | + } |
|
800 | + |
|
801 | + /** |
|
802 | + * Tries to login the user with auth token header |
|
803 | + * |
|
804 | + * @param IRequest $request |
|
805 | + * @todo check remember me cookie |
|
806 | + * @return boolean |
|
807 | + */ |
|
808 | + public function tryTokenLogin(IRequest $request) { |
|
809 | + $authHeader = $request->getHeader('Authorization'); |
|
810 | + if (str_starts_with($authHeader, 'Bearer ')) { |
|
811 | + $token = substr($authHeader, 7); |
|
812 | + } elseif ($request->getCookie($this->config->getSystemValueString('instanceid')) !== null) { |
|
813 | + // No auth header, let's try session id, but only if this is an existing |
|
814 | + // session and the request has a session cookie |
|
815 | + try { |
|
816 | + $token = $this->session->getId(); |
|
817 | + } catch (SessionNotAvailableException $ex) { |
|
818 | + return false; |
|
819 | + } |
|
820 | + } else { |
|
821 | + return false; |
|
822 | + } |
|
823 | + |
|
824 | + if (!$this->loginWithToken($token)) { |
|
825 | + return false; |
|
826 | + } |
|
827 | + if (!$this->validateToken($token)) { |
|
828 | + return false; |
|
829 | + } |
|
830 | + |
|
831 | + try { |
|
832 | + $dbToken = $this->tokenProvider->getToken($token); |
|
833 | + } catch (InvalidTokenException $e) { |
|
834 | + // Can't really happen but better save than sorry |
|
835 | + return true; |
|
836 | + } |
|
837 | + |
|
838 | + // Set the session variable so we know this is an app password |
|
839 | + if ($dbToken instanceof PublicKeyToken && $dbToken->getType() === IToken::PERMANENT_TOKEN) { |
|
840 | + $this->session->set('app_password', $token); |
|
841 | + } |
|
842 | + |
|
843 | + return true; |
|
844 | + } |
|
845 | + |
|
846 | + /** |
|
847 | + * perform login using the magic cookie (remember login) |
|
848 | + * |
|
849 | + * @param string $uid the username |
|
850 | + * @param string $currentToken |
|
851 | + * @param string $oldSessionId |
|
852 | + * @return bool |
|
853 | + */ |
|
854 | + public function loginWithCookie($uid, $currentToken, $oldSessionId) { |
|
855 | + $this->session->regenerateId(); |
|
856 | + $this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]); |
|
857 | + $user = $this->manager->get($uid); |
|
858 | + if (is_null($user)) { |
|
859 | + // user does not exist |
|
860 | + return false; |
|
861 | + } |
|
862 | + |
|
863 | + // get stored tokens |
|
864 | + $tokens = $this->config->getUserKeys($uid, 'login_token'); |
|
865 | + // test cookies token against stored tokens |
|
866 | + if (!in_array($currentToken, $tokens, true)) { |
|
867 | + $this->logger->info('Tried to log in but could not verify token', [ |
|
868 | + 'app' => 'core', |
|
869 | + 'user' => $uid, |
|
870 | + ]); |
|
871 | + return false; |
|
872 | + } |
|
873 | + // replace successfully used token with a new one |
|
874 | + $this->config->deleteUserValue($uid, 'login_token', $currentToken); |
|
875 | + $newToken = $this->random->generate(32); |
|
876 | + $this->config->setUserValue($uid, 'login_token', $newToken, (string)$this->timeFactory->getTime()); |
|
877 | + $this->logger->debug('Remember-me token replaced', [ |
|
878 | + 'app' => 'core', |
|
879 | + 'user' => $uid, |
|
880 | + ]); |
|
881 | + |
|
882 | + try { |
|
883 | + $sessionId = $this->session->getId(); |
|
884 | + $token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId); |
|
885 | + $this->logger->debug('Session token replaced', [ |
|
886 | + 'app' => 'core', |
|
887 | + 'user' => $uid, |
|
888 | + ]); |
|
889 | + } catch (SessionNotAvailableException $ex) { |
|
890 | + $this->logger->critical('Could not renew session token for {uid} because the session is unavailable', [ |
|
891 | + 'app' => 'core', |
|
892 | + 'uid' => $uid, |
|
893 | + 'user' => $uid, |
|
894 | + ]); |
|
895 | + return false; |
|
896 | + } catch (InvalidTokenException $ex) { |
|
897 | + $this->logger->error('Renewing session token failed: ' . $ex->getMessage(), [ |
|
898 | + 'app' => 'core', |
|
899 | + 'user' => $uid, |
|
900 | + 'exception' => $ex, |
|
901 | + ]); |
|
902 | + return false; |
|
903 | + } |
|
904 | + |
|
905 | + $this->setMagicInCookie($user->getUID(), $newToken); |
|
906 | + |
|
907 | + //login |
|
908 | + $this->setUser($user); |
|
909 | + $this->setLoginName($token->getLoginName()); |
|
910 | + $this->setToken($token->getId()); |
|
911 | + $this->lockdownManager->setToken($token); |
|
912 | + $user->updateLastLoginTimestamp(); |
|
913 | + $password = null; |
|
914 | + try { |
|
915 | + $password = $this->tokenProvider->getPassword($token, $sessionId); |
|
916 | + } catch (PasswordlessTokenException $ex) { |
|
917 | + // Ignore |
|
918 | + } |
|
919 | + $this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]); |
|
920 | + return true; |
|
921 | + } |
|
922 | + |
|
923 | + /** |
|
924 | + * @param IUser $user |
|
925 | + */ |
|
926 | + public function createRememberMeToken(IUser $user) { |
|
927 | + $token = $this->random->generate(32); |
|
928 | + $this->config->setUserValue($user->getUID(), 'login_token', $token, (string)$this->timeFactory->getTime()); |
|
929 | + $this->setMagicInCookie($user->getUID(), $token); |
|
930 | + } |
|
931 | + |
|
932 | + /** |
|
933 | + * logout the user from the session |
|
934 | + */ |
|
935 | + public function logout() { |
|
936 | + $user = $this->getUser(); |
|
937 | + $this->manager->emit('\OC\User', 'logout', [$user]); |
|
938 | + if ($user !== null) { |
|
939 | + try { |
|
940 | + $token = $this->session->getId(); |
|
941 | + $this->tokenProvider->invalidateToken($token); |
|
942 | + $this->logger->debug('Session token invalidated before logout', [ |
|
943 | + 'user' => $user->getUID(), |
|
944 | + ]); |
|
945 | + } catch (SessionNotAvailableException $ex) { |
|
946 | + } |
|
947 | + } |
|
948 | + $this->logger->debug('Logging out', [ |
|
949 | + 'user' => $user === null ? null : $user->getUID(), |
|
950 | + ]); |
|
951 | + $this->setUser(null); |
|
952 | + $this->setLoginName(null); |
|
953 | + $this->setToken(null); |
|
954 | + $this->unsetMagicInCookie(); |
|
955 | + $this->session->clear(); |
|
956 | + $this->manager->emit('\OC\User', 'postLogout', [$user]); |
|
957 | + } |
|
958 | + |
|
959 | + /** |
|
960 | + * Set cookie value to use in next page load |
|
961 | + * |
|
962 | + * @param string $username username to be set |
|
963 | + * @param string $token |
|
964 | + */ |
|
965 | + public function setMagicInCookie($username, $token) { |
|
966 | + $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https'; |
|
967 | + $webRoot = \OC::$WEBROOT; |
|
968 | + if ($webRoot === '') { |
|
969 | + $webRoot = '/'; |
|
970 | + } |
|
971 | + $domain = $this->config->getSystemValueString('cookie_domain'); |
|
972 | + |
|
973 | + $maxAge = $this->config->getSystemValueInt('remember_login_cookie_lifetime', 60 * 60 * 24 * 15); |
|
974 | + \OC\Http\CookieHelper::setCookie( |
|
975 | + 'nc_username', |
|
976 | + $username, |
|
977 | + $maxAge, |
|
978 | + $webRoot, |
|
979 | + $domain, |
|
980 | + $secureCookie, |
|
981 | + true, |
|
982 | + \OC\Http\CookieHelper::SAMESITE_LAX |
|
983 | + ); |
|
984 | + \OC\Http\CookieHelper::setCookie( |
|
985 | + 'nc_token', |
|
986 | + $token, |
|
987 | + $maxAge, |
|
988 | + $webRoot, |
|
989 | + $domain, |
|
990 | + $secureCookie, |
|
991 | + true, |
|
992 | + \OC\Http\CookieHelper::SAMESITE_LAX |
|
993 | + ); |
|
994 | + try { |
|
995 | + \OC\Http\CookieHelper::setCookie( |
|
996 | + 'nc_session_id', |
|
997 | + $this->session->getId(), |
|
998 | + $maxAge, |
|
999 | + $webRoot, |
|
1000 | + $domain, |
|
1001 | + $secureCookie, |
|
1002 | + true, |
|
1003 | + \OC\Http\CookieHelper::SAMESITE_LAX |
|
1004 | + ); |
|
1005 | + } catch (SessionNotAvailableException $ex) { |
|
1006 | + // ignore |
|
1007 | + } |
|
1008 | + } |
|
1009 | + |
|
1010 | + /** |
|
1011 | + * Remove cookie for "remember username" |
|
1012 | + */ |
|
1013 | + public function unsetMagicInCookie() { |
|
1014 | + //TODO: DI for cookies and IRequest |
|
1015 | + $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https'; |
|
1016 | + $domain = $this->config->getSystemValueString('cookie_domain'); |
|
1017 | + |
|
1018 | + unset($_COOKIE['nc_username']); //TODO: DI |
|
1019 | + unset($_COOKIE['nc_token']); |
|
1020 | + unset($_COOKIE['nc_session_id']); |
|
1021 | + setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, $domain, $secureCookie, true); |
|
1022 | + setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, $domain, $secureCookie, true); |
|
1023 | + setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, $domain, $secureCookie, true); |
|
1024 | + // old cookies might be stored under /webroot/ instead of /webroot |
|
1025 | + // and Firefox doesn't like it! |
|
1026 | + setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', $domain, $secureCookie, true); |
|
1027 | + setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', $domain, $secureCookie, true); |
|
1028 | + setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', $domain, $secureCookie, true); |
|
1029 | + } |
|
1030 | + |
|
1031 | + /** |
|
1032 | + * Update password of the browser session token if there is one |
|
1033 | + * |
|
1034 | + * @param string $password |
|
1035 | + */ |
|
1036 | + public function updateSessionTokenPassword($password) { |
|
1037 | + try { |
|
1038 | + $sessionId = $this->session->getId(); |
|
1039 | + $token = $this->tokenProvider->getToken($sessionId); |
|
1040 | + $this->tokenProvider->setPassword($token, $sessionId, $password); |
|
1041 | + } catch (SessionNotAvailableException $ex) { |
|
1042 | + // Nothing to do |
|
1043 | + } catch (InvalidTokenException $ex) { |
|
1044 | + // Nothing to do |
|
1045 | + } |
|
1046 | + } |
|
1047 | + |
|
1048 | + public function updateTokens(string $uid, string $password) { |
|
1049 | + $this->tokenProvider->updatePasswords($uid, $password); |
|
1050 | + } |
|
1051 | 1051 | } |
@@ -40,1153 +40,1153 @@ |
||
40 | 40 | * OC_autoload! |
41 | 41 | */ |
42 | 42 | class OC { |
43 | - /** |
|
44 | - * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
45 | - */ |
|
46 | - public static string $SERVERROOT = ''; |
|
47 | - /** |
|
48 | - * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
49 | - */ |
|
50 | - private static string $SUBURI = ''; |
|
51 | - /** |
|
52 | - * the Nextcloud root path for http requests (e.g. /nextcloud) |
|
53 | - */ |
|
54 | - public static string $WEBROOT = ''; |
|
55 | - /** |
|
56 | - * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
57 | - * web path in 'url' |
|
58 | - */ |
|
59 | - public static array $APPSROOTS = []; |
|
60 | - |
|
61 | - public static string $configDir; |
|
62 | - |
|
63 | - /** |
|
64 | - * requested app |
|
65 | - */ |
|
66 | - public static string $REQUESTEDAPP = ''; |
|
67 | - |
|
68 | - /** |
|
69 | - * check if Nextcloud runs in cli mode |
|
70 | - */ |
|
71 | - public static bool $CLI = false; |
|
72 | - |
|
73 | - public static \Composer\Autoload\ClassLoader $composerAutoloader; |
|
74 | - |
|
75 | - public static \OC\Server $server; |
|
76 | - |
|
77 | - private static \OC\Config $config; |
|
78 | - |
|
79 | - /** |
|
80 | - * @throws \RuntimeException when the 3rdparty directory is missing or |
|
81 | - * the app path list is empty or contains an invalid path |
|
82 | - */ |
|
83 | - public static function initPaths(): void { |
|
84 | - if (defined('PHPUNIT_CONFIG_DIR')) { |
|
85 | - self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
86 | - } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
87 | - self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
88 | - } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
89 | - self::$configDir = rtrim($dir, '/') . '/'; |
|
90 | - } else { |
|
91 | - self::$configDir = OC::$SERVERROOT . '/config/'; |
|
92 | - } |
|
93 | - self::$config = new \OC\Config(self::$configDir); |
|
94 | - |
|
95 | - OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT))); |
|
96 | - /** |
|
97 | - * FIXME: The following lines are required because we can't yet instantiate |
|
98 | - * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist. |
|
99 | - */ |
|
100 | - $params = [ |
|
101 | - 'server' => [ |
|
102 | - 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null, |
|
103 | - 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null, |
|
104 | - ], |
|
105 | - ]; |
|
106 | - if (isset($_SERVER['REMOTE_ADDR'])) { |
|
107 | - $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; |
|
108 | - } |
|
109 | - $fakeRequest = new \OC\AppFramework\Http\Request( |
|
110 | - $params, |
|
111 | - new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()), |
|
112 | - new \OC\AllConfig(new \OC\SystemConfig(self::$config)) |
|
113 | - ); |
|
114 | - $scriptName = $fakeRequest->getScriptName(); |
|
115 | - if (substr($scriptName, -1) == '/') { |
|
116 | - $scriptName .= 'index.php'; |
|
117 | - //make sure suburi follows the same rules as scriptName |
|
118 | - if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
119 | - if (substr(OC::$SUBURI, -1) != '/') { |
|
120 | - OC::$SUBURI = OC::$SUBURI . '/'; |
|
121 | - } |
|
122 | - OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
123 | - } |
|
124 | - } |
|
125 | - |
|
126 | - if (OC::$CLI) { |
|
127 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
128 | - } else { |
|
129 | - if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
130 | - OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
131 | - |
|
132 | - if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
133 | - OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
134 | - } |
|
135 | - } else { |
|
136 | - // The scriptName is not ending with OC::$SUBURI |
|
137 | - // This most likely means that we are calling from CLI. |
|
138 | - // However some cron jobs still need to generate |
|
139 | - // a web URL, so we use overwritewebroot as a fallback. |
|
140 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
141 | - } |
|
142 | - |
|
143 | - // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
144 | - // slash which is required by URL generation. |
|
145 | - if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT |
|
146 | - && substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
147 | - header('Location: ' . \OC::$WEBROOT . '/'); |
|
148 | - exit(); |
|
149 | - } |
|
150 | - } |
|
151 | - |
|
152 | - // search the apps folder |
|
153 | - $config_paths = self::$config->getValue('apps_paths', []); |
|
154 | - if (!empty($config_paths)) { |
|
155 | - foreach ($config_paths as $paths) { |
|
156 | - if (isset($paths['url']) && isset($paths['path'])) { |
|
157 | - $paths['url'] = rtrim($paths['url'], '/'); |
|
158 | - $paths['path'] = rtrim($paths['path'], '/'); |
|
159 | - OC::$APPSROOTS[] = $paths; |
|
160 | - } |
|
161 | - } |
|
162 | - } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
163 | - OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
164 | - } |
|
165 | - |
|
166 | - if (empty(OC::$APPSROOTS)) { |
|
167 | - throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
168 | - . '. You can also configure the location in the config.php file.'); |
|
169 | - } |
|
170 | - $paths = []; |
|
171 | - foreach (OC::$APPSROOTS as $path) { |
|
172 | - $paths[] = $path['path']; |
|
173 | - if (!is_dir($path['path'])) { |
|
174 | - throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
175 | - . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
176 | - } |
|
177 | - } |
|
178 | - |
|
179 | - // set the right include path |
|
180 | - set_include_path( |
|
181 | - implode(PATH_SEPARATOR, $paths) |
|
182 | - ); |
|
183 | - } |
|
184 | - |
|
185 | - public static function checkConfig(): void { |
|
186 | - // Create config if it does not already exist |
|
187 | - $configFilePath = self::$configDir . '/config.php'; |
|
188 | - if (!file_exists($configFilePath)) { |
|
189 | - @touch($configFilePath); |
|
190 | - } |
|
191 | - |
|
192 | - // Check if config is writable |
|
193 | - $configFileWritable = is_writable($configFilePath); |
|
194 | - $configReadOnly = Server::get(IConfig::class)->getSystemValueBool('config_is_read_only'); |
|
195 | - if (!$configFileWritable && !$configReadOnly |
|
196 | - || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
197 | - $urlGenerator = Server::get(IURLGenerator::class); |
|
198 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
199 | - |
|
200 | - if (self::$CLI) { |
|
201 | - echo $l->t('Cannot write into "config" directory!') . "\n"; |
|
202 | - echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n"; |
|
203 | - echo "\n"; |
|
204 | - echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n"; |
|
205 | - echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n"; |
|
206 | - exit; |
|
207 | - } else { |
|
208 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
209 | - $l->t('Cannot write into "config" directory!'), |
|
210 | - $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' ' |
|
211 | - . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
212 | - . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
213 | - 503 |
|
214 | - ); |
|
215 | - } |
|
216 | - } |
|
217 | - } |
|
218 | - |
|
219 | - public static function checkInstalled(\OC\SystemConfig $systemConfig): void { |
|
220 | - if (defined('OC_CONSOLE')) { |
|
221 | - return; |
|
222 | - } |
|
223 | - // Redirect to installer if not installed |
|
224 | - if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
|
225 | - if (OC::$CLI) { |
|
226 | - throw new Exception('Not installed'); |
|
227 | - } else { |
|
228 | - $url = OC::$WEBROOT . '/index.php'; |
|
229 | - header('Location: ' . $url); |
|
230 | - } |
|
231 | - exit(); |
|
232 | - } |
|
233 | - } |
|
234 | - |
|
235 | - public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { |
|
236 | - // Allow ajax update script to execute without being stopped |
|
237 | - if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
238 | - // send http status 503 |
|
239 | - http_response_code(503); |
|
240 | - header('X-Nextcloud-Maintenance-Mode: 1'); |
|
241 | - header('Retry-After: 120'); |
|
242 | - |
|
243 | - // render error page |
|
244 | - $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest'); |
|
245 | - \OCP\Util::addScript('core', 'maintenance'); |
|
246 | - \OCP\Util::addStyle('core', 'guest'); |
|
247 | - $template->printPage(); |
|
248 | - die(); |
|
249 | - } |
|
250 | - } |
|
251 | - |
|
252 | - /** |
|
253 | - * Prints the upgrade page |
|
254 | - */ |
|
255 | - private static function printUpgradePage(\OC\SystemConfig $systemConfig): void { |
|
256 | - $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', ''); |
|
257 | - $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
258 | - $tooBig = false; |
|
259 | - if (!$disableWebUpdater) { |
|
260 | - $apps = Server::get(\OCP\App\IAppManager::class); |
|
261 | - if ($apps->isEnabledForAnyone('user_ldap')) { |
|
262 | - $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
263 | - |
|
264 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
265 | - ->from('ldap_user_mapping') |
|
266 | - ->executeQuery(); |
|
267 | - $row = $result->fetch(); |
|
268 | - $result->closeCursor(); |
|
269 | - |
|
270 | - $tooBig = ($row['user_count'] > 50); |
|
271 | - } |
|
272 | - if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) { |
|
273 | - $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
274 | - |
|
275 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
276 | - ->from('user_saml_users') |
|
277 | - ->executeQuery(); |
|
278 | - $row = $result->fetch(); |
|
279 | - $result->closeCursor(); |
|
280 | - |
|
281 | - $tooBig = ($row['user_count'] > 50); |
|
282 | - } |
|
283 | - if (!$tooBig) { |
|
284 | - // count users |
|
285 | - $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51); |
|
286 | - $tooBig = ($totalUsers > 50); |
|
287 | - } |
|
288 | - } |
|
289 | - $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) |
|
290 | - && $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
291 | - |
|
292 | - if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
293 | - // send http status 503 |
|
294 | - http_response_code(503); |
|
295 | - header('Retry-After: 120'); |
|
296 | - |
|
297 | - $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class); |
|
298 | - |
|
299 | - // render error page |
|
300 | - $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest'); |
|
301 | - $template->assign('productName', 'nextcloud'); // for now |
|
302 | - $template->assign('version', $serverVersion->getVersionString()); |
|
303 | - $template->assign('tooBig', $tooBig); |
|
304 | - $template->assign('cliUpgradeLink', $cliUpgradeLink); |
|
305 | - |
|
306 | - $template->printPage(); |
|
307 | - die(); |
|
308 | - } |
|
309 | - |
|
310 | - // check whether this is a core update or apps update |
|
311 | - $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
312 | - $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
313 | - |
|
314 | - // if not a core upgrade, then it's apps upgrade |
|
315 | - $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
316 | - |
|
317 | - $oldTheme = $systemConfig->getValue('theme'); |
|
318 | - $systemConfig->setValue('theme', ''); |
|
319 | - \OCP\Util::addScript('core', 'common'); |
|
320 | - \OCP\Util::addScript('core', 'main'); |
|
321 | - \OCP\Util::addTranslations('core'); |
|
322 | - \OCP\Util::addScript('core', 'update'); |
|
323 | - |
|
324 | - /** @var \OC\App\AppManager $appManager */ |
|
325 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
326 | - |
|
327 | - $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest'); |
|
328 | - $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString()); |
|
329 | - $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
330 | - |
|
331 | - // get third party apps |
|
332 | - $ocVersion = \OCP\Util::getVersion(); |
|
333 | - $ocVersion = implode('.', $ocVersion); |
|
334 | - $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
335 | - $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []); |
|
336 | - $incompatibleShippedApps = []; |
|
337 | - $incompatibleDisabledApps = []; |
|
338 | - foreach ($incompatibleApps as $appInfo) { |
|
339 | - if ($appManager->isShipped($appInfo['id'])) { |
|
340 | - $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
341 | - } |
|
342 | - if (!in_array($appInfo['id'], $incompatibleOverwrites)) { |
|
343 | - $incompatibleDisabledApps[] = $appInfo; |
|
344 | - } |
|
345 | - } |
|
346 | - |
|
347 | - if (!empty($incompatibleShippedApps)) { |
|
348 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('core'); |
|
349 | - $hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]); |
|
350 | - throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint); |
|
351 | - } |
|
352 | - |
|
353 | - $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
354 | - $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps); |
|
355 | - try { |
|
356 | - $defaults = new \OC_Defaults(); |
|
357 | - $tmpl->assign('productName', $defaults->getName()); |
|
358 | - } catch (Throwable $error) { |
|
359 | - $tmpl->assign('productName', 'Nextcloud'); |
|
360 | - } |
|
361 | - $tmpl->assign('oldTheme', $oldTheme); |
|
362 | - $tmpl->printPage(); |
|
363 | - } |
|
364 | - |
|
365 | - public static function initSession(): void { |
|
366 | - $request = Server::get(IRequest::class); |
|
367 | - |
|
368 | - // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies |
|
369 | - // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments |
|
370 | - // TODO: for further information. |
|
371 | - // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0; |
|
372 | - // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) { |
|
373 | - // setcookie('cookie_test', 'test', time() + 3600); |
|
374 | - // // Do not initialize the session if a request is authenticated directly |
|
375 | - // // unless there is a session cookie already sent along |
|
376 | - // return; |
|
377 | - // } |
|
378 | - |
|
379 | - if ($request->getServerProtocol() === 'https') { |
|
380 | - ini_set('session.cookie_secure', 'true'); |
|
381 | - } |
|
382 | - |
|
383 | - // prevents javascript from accessing php session cookies |
|
384 | - ini_set('session.cookie_httponly', 'true'); |
|
385 | - |
|
386 | - // Do not initialize sessions for 'status.php' requests |
|
387 | - // Monitoring endpoints can quickly flood session handlers |
|
388 | - // and 'status.php' doesn't require sessions anyway |
|
389 | - if (str_ends_with($request->getScriptName(), '/status.php')) { |
|
390 | - return; |
|
391 | - } |
|
392 | - |
|
393 | - // set the cookie path to the Nextcloud directory |
|
394 | - $cookie_path = OC::$WEBROOT ? : '/'; |
|
395 | - ini_set('session.cookie_path', $cookie_path); |
|
396 | - |
|
397 | - // set the cookie domain to the Nextcloud domain |
|
398 | - $cookie_domain = self::$config->getValue('cookie_domain', ''); |
|
399 | - if ($cookie_domain) { |
|
400 | - ini_set('session.cookie_domain', $cookie_domain); |
|
401 | - } |
|
402 | - |
|
403 | - // Let the session name be changed in the initSession Hook |
|
404 | - $sessionName = OC_Util::getInstanceId(); |
|
405 | - |
|
406 | - try { |
|
407 | - $logger = null; |
|
408 | - if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) { |
|
409 | - $logger = logger('core'); |
|
410 | - } |
|
411 | - |
|
412 | - // set the session name to the instance id - which is unique |
|
413 | - $session = new \OC\Session\Internal( |
|
414 | - $sessionName, |
|
415 | - $logger, |
|
416 | - ); |
|
417 | - |
|
418 | - $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class); |
|
419 | - $session = $cryptoWrapper->wrapSession($session); |
|
420 | - self::$server->setSession($session); |
|
421 | - |
|
422 | - // if session can't be started break with http 500 error |
|
423 | - } catch (Exception $e) { |
|
424 | - Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]); |
|
425 | - //show the user a detailed error page |
|
426 | - Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500); |
|
427 | - die(); |
|
428 | - } |
|
429 | - |
|
430 | - //try to set the session lifetime |
|
431 | - $sessionLifeTime = self::getSessionLifeTime(); |
|
432 | - |
|
433 | - // session timeout |
|
434 | - if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
435 | - if (isset($_COOKIE[session_name()])) { |
|
436 | - setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
437 | - } |
|
438 | - Server::get(IUserSession::class)->logout(); |
|
439 | - } |
|
440 | - |
|
441 | - if (!self::hasSessionRelaxedExpiry()) { |
|
442 | - $session->set('LAST_ACTIVITY', time()); |
|
443 | - } |
|
444 | - $session->close(); |
|
445 | - } |
|
446 | - |
|
447 | - private static function getSessionLifeTime(): int { |
|
448 | - return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24); |
|
449 | - } |
|
450 | - |
|
451 | - /** |
|
452 | - * @return bool true if the session expiry should only be done by gc instead of an explicit timeout |
|
453 | - */ |
|
454 | - public static function hasSessionRelaxedExpiry(): bool { |
|
455 | - return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false); |
|
456 | - } |
|
457 | - |
|
458 | - /** |
|
459 | - * Try to set some values to the required Nextcloud default |
|
460 | - */ |
|
461 | - public static function setRequiredIniValues(): void { |
|
462 | - // Don't display errors and log them |
|
463 | - @ini_set('display_errors', '0'); |
|
464 | - @ini_set('log_errors', '1'); |
|
465 | - |
|
466 | - // Try to configure php to enable big file uploads. |
|
467 | - // This doesn't work always depending on the webserver and php configuration. |
|
468 | - // Let's try to overwrite some defaults if they are smaller than 1 hour |
|
469 | - |
|
470 | - if (intval(@ini_get('max_execution_time') ?: 0) < 3600) { |
|
471 | - @ini_set('max_execution_time', strval(3600)); |
|
472 | - } |
|
473 | - |
|
474 | - if (intval(@ini_get('max_input_time') ?: 0) < 3600) { |
|
475 | - @ini_set('max_input_time', strval(3600)); |
|
476 | - } |
|
477 | - |
|
478 | - // Try to set the maximum execution time to the largest time limit we have |
|
479 | - if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
480 | - @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time')))); |
|
481 | - } |
|
482 | - |
|
483 | - @ini_set('default_charset', 'UTF-8'); |
|
484 | - @ini_set('gd.jpeg_ignore_warning', '1'); |
|
485 | - } |
|
486 | - |
|
487 | - /** |
|
488 | - * Send the same site cookies |
|
489 | - */ |
|
490 | - private static function sendSameSiteCookies(): void { |
|
491 | - $cookieParams = session_get_cookie_params(); |
|
492 | - $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
493 | - $policies = [ |
|
494 | - 'lax', |
|
495 | - 'strict', |
|
496 | - ]; |
|
497 | - |
|
498 | - // Append __Host to the cookie if it meets the requirements |
|
499 | - $cookiePrefix = ''; |
|
500 | - if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
501 | - $cookiePrefix = '__Host-'; |
|
502 | - } |
|
503 | - |
|
504 | - foreach ($policies as $policy) { |
|
505 | - header( |
|
506 | - sprintf( |
|
507 | - 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
508 | - $cookiePrefix, |
|
509 | - $policy, |
|
510 | - $cookieParams['path'], |
|
511 | - $policy |
|
512 | - ), |
|
513 | - false |
|
514 | - ); |
|
515 | - } |
|
516 | - } |
|
517 | - |
|
518 | - /** |
|
519 | - * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
520 | - * be set in every request if cookies are sent to add a second level of |
|
521 | - * defense against CSRF. |
|
522 | - * |
|
523 | - * If the cookie is not sent this will set the cookie and reload the page. |
|
524 | - * We use an additional cookie since we want to protect logout CSRF and |
|
525 | - * also we can't directly interfere with PHP's session mechanism. |
|
526 | - */ |
|
527 | - private static function performSameSiteCookieProtection(IConfig $config): void { |
|
528 | - $request = Server::get(IRequest::class); |
|
529 | - |
|
530 | - // Some user agents are notorious and don't really properly follow HTTP |
|
531 | - // specifications. For those, have an automated opt-out. Since the protection |
|
532 | - // for remote.php is applied in base.php as starting point we need to opt out |
|
533 | - // here. |
|
534 | - $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
535 | - |
|
536 | - // Fallback, if csrf.optout is unset |
|
537 | - if (!is_array($incompatibleUserAgents)) { |
|
538 | - $incompatibleUserAgents = [ |
|
539 | - // OS X Finder |
|
540 | - '/^WebDAVFS/', |
|
541 | - // Windows webdav drive |
|
542 | - '/^Microsoft-WebDAV-MiniRedir/', |
|
543 | - ]; |
|
544 | - } |
|
545 | - |
|
546 | - if ($request->isUserAgent($incompatibleUserAgents)) { |
|
547 | - return; |
|
548 | - } |
|
549 | - |
|
550 | - if (count($_COOKIE) > 0) { |
|
551 | - $requestUri = $request->getScriptName(); |
|
552 | - $processingScript = explode('/', $requestUri); |
|
553 | - $processingScript = $processingScript[count($processingScript) - 1]; |
|
554 | - |
|
555 | - if ($processingScript === 'index.php' // index.php routes are handled in the middleware |
|
556 | - || $processingScript === 'cron.php' // and cron.php does not need any authentication at all |
|
557 | - || $processingScript === 'public.php' // For public.php, auth for password protected shares is done in the PublicAuth plugin |
|
558 | - ) { |
|
559 | - return; |
|
560 | - } |
|
561 | - |
|
562 | - // All other endpoints require the lax and the strict cookie |
|
563 | - if (!$request->passesStrictCookieCheck()) { |
|
564 | - logger('core')->warning('Request does not pass strict cookie check'); |
|
565 | - self::sendSameSiteCookies(); |
|
566 | - // Debug mode gets access to the resources without strict cookie |
|
567 | - // due to the fact that the SabreDAV browser also lives there. |
|
568 | - if (!$config->getSystemValueBool('debug', false)) { |
|
569 | - http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED); |
|
570 | - header('Content-Type: application/json'); |
|
571 | - echo json_encode(['error' => 'Strict Cookie has not been found in request']); |
|
572 | - exit(); |
|
573 | - } |
|
574 | - } |
|
575 | - } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
576 | - self::sendSameSiteCookies(); |
|
577 | - } |
|
578 | - } |
|
579 | - |
|
580 | - public static function init(): void { |
|
581 | - // First handle PHP configuration and copy auth headers to the expected |
|
582 | - // $_SERVER variable before doing anything Server object related |
|
583 | - self::setRequiredIniValues(); |
|
584 | - self::handleAuthHeaders(); |
|
585 | - |
|
586 | - // prevent any XML processing from loading external entities |
|
587 | - libxml_set_external_entity_loader(static function () { |
|
588 | - return null; |
|
589 | - }); |
|
590 | - |
|
591 | - // Set default timezone before the Server object is booted |
|
592 | - if (!date_default_timezone_set('UTC')) { |
|
593 | - throw new \RuntimeException('Could not set timezone to UTC'); |
|
594 | - } |
|
595 | - |
|
596 | - // calculate the root directories |
|
597 | - OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4)); |
|
598 | - |
|
599 | - // register autoloader |
|
600 | - $loaderStart = microtime(true); |
|
601 | - |
|
602 | - self::$CLI = (php_sapi_name() == 'cli'); |
|
603 | - |
|
604 | - // Add default composer PSR-4 autoloader, ensure apcu to be disabled |
|
605 | - self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
606 | - self::$composerAutoloader->setApcuPrefix(null); |
|
607 | - |
|
608 | - |
|
609 | - try { |
|
610 | - self::initPaths(); |
|
611 | - // setup 3rdparty autoloader |
|
612 | - $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php'; |
|
613 | - if (!file_exists($vendorAutoLoad)) { |
|
614 | - throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); |
|
615 | - } |
|
616 | - require_once $vendorAutoLoad; |
|
617 | - } catch (\RuntimeException $e) { |
|
618 | - if (!self::$CLI) { |
|
619 | - http_response_code(503); |
|
620 | - } |
|
621 | - // we can't use the template error page here, because this needs the |
|
622 | - // DI container which isn't available yet |
|
623 | - print($e->getMessage()); |
|
624 | - exit(); |
|
625 | - } |
|
626 | - $loaderEnd = microtime(true); |
|
627 | - |
|
628 | - // Enable lazy loading if activated |
|
629 | - \OC\AppFramework\Utility\SimpleContainer::$useLazyObjects = (bool)self::$config->getValue('enable_lazy_objects', true); |
|
630 | - |
|
631 | - // setup the basic server |
|
632 | - self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
633 | - self::$server->boot(); |
|
634 | - |
|
635 | - try { |
|
636 | - $profiler = new BuiltInProfiler( |
|
637 | - Server::get(IConfig::class), |
|
638 | - Server::get(IRequest::class), |
|
639 | - ); |
|
640 | - $profiler->start(); |
|
641 | - } catch (\Throwable $e) { |
|
642 | - logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']); |
|
643 | - } |
|
644 | - |
|
645 | - if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) { |
|
646 | - \OC\Core\Listener\BeforeMessageLoggedEventListener::setup(); |
|
647 | - } |
|
648 | - |
|
649 | - $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class); |
|
650 | - $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
651 | - $eventLogger->start('boot', 'Initialize'); |
|
652 | - |
|
653 | - // Override php.ini and log everything if we're troubleshooting |
|
654 | - if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
655 | - error_reporting(E_ALL); |
|
656 | - } |
|
657 | - |
|
658 | - // initialize intl fallback if necessary |
|
659 | - OC_Util::isSetLocaleWorking(); |
|
660 | - |
|
661 | - $config = Server::get(IConfig::class); |
|
662 | - if (!defined('PHPUNIT_RUN')) { |
|
663 | - $errorHandler = new OC\Log\ErrorHandler( |
|
664 | - \OCP\Server::get(\Psr\Log\LoggerInterface::class), |
|
665 | - ); |
|
666 | - $exceptionHandler = [$errorHandler, 'onException']; |
|
667 | - if ($config->getSystemValueBool('debug', false)) { |
|
668 | - set_error_handler([$errorHandler, 'onAll'], E_ALL); |
|
669 | - if (\OC::$CLI) { |
|
670 | - $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage']; |
|
671 | - } |
|
672 | - } else { |
|
673 | - set_error_handler([$errorHandler, 'onError']); |
|
674 | - } |
|
675 | - register_shutdown_function([$errorHandler, 'onShutdown']); |
|
676 | - set_exception_handler($exceptionHandler); |
|
677 | - } |
|
678 | - |
|
679 | - /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
680 | - $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
681 | - $bootstrapCoordinator->runInitialRegistration(); |
|
682 | - |
|
683 | - $eventLogger->start('init_session', 'Initialize session'); |
|
684 | - |
|
685 | - // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users |
|
686 | - // see https://github.com/nextcloud/server/pull/2619 |
|
687 | - if (!function_exists('simplexml_load_file')) { |
|
688 | - throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.'); |
|
689 | - } |
|
690 | - |
|
691 | - $systemConfig = Server::get(\OC\SystemConfig::class); |
|
692 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
693 | - if ($systemConfig->getValue('installed', false)) { |
|
694 | - $appManager->loadApps(['session']); |
|
695 | - } |
|
696 | - if (!self::$CLI) { |
|
697 | - self::initSession(); |
|
698 | - } |
|
699 | - $eventLogger->end('init_session'); |
|
700 | - self::checkConfig(); |
|
701 | - self::checkInstalled($systemConfig); |
|
702 | - |
|
703 | - OC_Response::addSecurityHeaders(); |
|
704 | - |
|
705 | - self::performSameSiteCookieProtection($config); |
|
706 | - |
|
707 | - if (!defined('OC_CONSOLE')) { |
|
708 | - $eventLogger->start('check_server', 'Run a few configuration checks'); |
|
709 | - $errors = OC_Util::checkServer($systemConfig); |
|
710 | - if (count($errors) > 0) { |
|
711 | - if (!self::$CLI) { |
|
712 | - http_response_code(503); |
|
713 | - Util::addStyle('guest'); |
|
714 | - try { |
|
715 | - Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]); |
|
716 | - exit; |
|
717 | - } catch (\Exception $e) { |
|
718 | - // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
719 | - // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
720 | - } |
|
721 | - } |
|
722 | - |
|
723 | - // Convert l10n string into regular string for usage in database |
|
724 | - $staticErrors = []; |
|
725 | - foreach ($errors as $error) { |
|
726 | - echo $error['error'] . "\n"; |
|
727 | - echo $error['hint'] . "\n\n"; |
|
728 | - $staticErrors[] = [ |
|
729 | - 'error' => (string)$error['error'], |
|
730 | - 'hint' => (string)$error['hint'], |
|
731 | - ]; |
|
732 | - } |
|
733 | - |
|
734 | - try { |
|
735 | - $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
736 | - } catch (\Exception $e) { |
|
737 | - echo('Writing to database failed'); |
|
738 | - } |
|
739 | - exit(1); |
|
740 | - } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) { |
|
741 | - $config->deleteAppValue('core', 'cronErrors'); |
|
742 | - } |
|
743 | - $eventLogger->end('check_server'); |
|
744 | - } |
|
745 | - |
|
746 | - // User and Groups |
|
747 | - if (!$systemConfig->getValue('installed', false)) { |
|
748 | - self::$server->getSession()->set('user_id', ''); |
|
749 | - } |
|
750 | - |
|
751 | - $eventLogger->start('setup_backends', 'Setup group and user backends'); |
|
752 | - Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
753 | - Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database()); |
|
754 | - |
|
755 | - // Subscribe to the hook |
|
756 | - \OCP\Util::connectHook( |
|
757 | - '\OCA\Files_Sharing\API\Server2Server', |
|
758 | - 'preLoginNameUsedAsUserName', |
|
759 | - '\OC\User\Database', |
|
760 | - 'preLoginNameUsedAsUserName' |
|
761 | - ); |
|
762 | - |
|
763 | - //setup extra user backends |
|
764 | - if (!\OCP\Util::needUpgrade()) { |
|
765 | - OC_User::setupBackends(); |
|
766 | - } else { |
|
767 | - // Run upgrades in incognito mode |
|
768 | - OC_User::setIncognitoMode(true); |
|
769 | - } |
|
770 | - $eventLogger->end('setup_backends'); |
|
771 | - |
|
772 | - self::registerCleanupHooks($systemConfig); |
|
773 | - self::registerShareHooks($systemConfig); |
|
774 | - self::registerEncryptionWrapperAndHooks(); |
|
775 | - self::registerAccountHooks(); |
|
776 | - self::registerResourceCollectionHooks(); |
|
777 | - self::registerFileReferenceEventListener(); |
|
778 | - self::registerRenderReferenceEventListener(); |
|
779 | - self::registerAppRestrictionsHooks(); |
|
780 | - |
|
781 | - // Make sure that the application class is not loaded before the database is setup |
|
782 | - if ($systemConfig->getValue('installed', false)) { |
|
783 | - $appManager->loadApp('settings'); |
|
784 | - /* Run core application registration */ |
|
785 | - $bootstrapCoordinator->runLazyRegistration('core'); |
|
786 | - } |
|
787 | - |
|
788 | - //make sure temporary files are cleaned up |
|
789 | - $tmpManager = Server::get(\OCP\ITempManager::class); |
|
790 | - register_shutdown_function([$tmpManager, 'clean']); |
|
791 | - $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class); |
|
792 | - register_shutdown_function([$lockProvider, 'releaseAll']); |
|
793 | - |
|
794 | - // Check whether the sample configuration has been copied |
|
795 | - if ($systemConfig->getValue('copied_sample_config', false)) { |
|
796 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
797 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
798 | - $l->t('Sample configuration detected'), |
|
799 | - $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'), |
|
800 | - 503 |
|
801 | - ); |
|
802 | - return; |
|
803 | - } |
|
804 | - |
|
805 | - $request = Server::get(IRequest::class); |
|
806 | - $host = $request->getInsecureServerHost(); |
|
807 | - /** |
|
808 | - * if the host passed in headers isn't trusted |
|
809 | - * FIXME: Should not be in here at all :see_no_evil: |
|
810 | - */ |
|
811 | - if (!OC::$CLI |
|
812 | - && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host) |
|
813 | - && $config->getSystemValueBool('installed', false) |
|
814 | - ) { |
|
815 | - // Allow access to CSS resources |
|
816 | - $isScssRequest = false; |
|
817 | - if (strpos($request->getPathInfo() ?: '', '/css/') === 0) { |
|
818 | - $isScssRequest = true; |
|
819 | - } |
|
820 | - |
|
821 | - if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
822 | - http_response_code(400); |
|
823 | - header('Content-Type: application/json'); |
|
824 | - echo '{"error": "Trusted domain error.", "code": 15}'; |
|
825 | - exit(); |
|
826 | - } |
|
827 | - |
|
828 | - if (!$isScssRequest) { |
|
829 | - http_response_code(400); |
|
830 | - Server::get(LoggerInterface::class)->info( |
|
831 | - 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
832 | - [ |
|
833 | - 'app' => 'core', |
|
834 | - 'remoteAddress' => $request->getRemoteAddress(), |
|
835 | - 'host' => $host, |
|
836 | - ] |
|
837 | - ); |
|
838 | - |
|
839 | - $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest'); |
|
840 | - $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains')); |
|
841 | - $tmpl->printPage(); |
|
842 | - |
|
843 | - exit(); |
|
844 | - } |
|
845 | - } |
|
846 | - $eventLogger->end('boot'); |
|
847 | - $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true)); |
|
848 | - $eventLogger->start('runtime', 'Runtime'); |
|
849 | - $eventLogger->start('request', 'Full request after boot'); |
|
850 | - register_shutdown_function(function () use ($eventLogger) { |
|
851 | - $eventLogger->end('request'); |
|
852 | - }); |
|
853 | - |
|
854 | - register_shutdown_function(function () { |
|
855 | - $memoryPeak = memory_get_peak_usage(); |
|
856 | - $logLevel = match (true) { |
|
857 | - $memoryPeak > 500_000_000 => ILogger::FATAL, |
|
858 | - $memoryPeak > 400_000_000 => ILogger::ERROR, |
|
859 | - $memoryPeak > 300_000_000 => ILogger::WARN, |
|
860 | - default => null, |
|
861 | - }; |
|
862 | - if ($logLevel !== null) { |
|
863 | - $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak); |
|
864 | - $logger = Server::get(LoggerInterface::class); |
|
865 | - $logger->log($logLevel, $message, ['app' => 'core']); |
|
866 | - } |
|
867 | - }); |
|
868 | - } |
|
869 | - |
|
870 | - /** |
|
871 | - * register hooks for the cleanup of cache and bruteforce protection |
|
872 | - */ |
|
873 | - public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { |
|
874 | - //don't try to do this before we are properly setup |
|
875 | - if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
876 | - // NOTE: This will be replaced to use OCP |
|
877 | - $userSession = Server::get(\OC\User\Session::class); |
|
878 | - $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
879 | - if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
880 | - // reset brute force delay for this IP address and username |
|
881 | - $uid = $userSession->getUser()->getUID(); |
|
882 | - $request = Server::get(IRequest::class); |
|
883 | - $throttler = Server::get(IThrottler::class); |
|
884 | - $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
885 | - } |
|
886 | - |
|
887 | - try { |
|
888 | - $cache = new \OC\Cache\File(); |
|
889 | - $cache->gc(); |
|
890 | - } catch (\OC\ServerNotAvailableException $e) { |
|
891 | - // not a GC exception, pass it on |
|
892 | - throw $e; |
|
893 | - } catch (\OC\ForbiddenException $e) { |
|
894 | - // filesystem blocked for this request, ignore |
|
895 | - } catch (\Exception $e) { |
|
896 | - // a GC exception should not prevent users from using OC, |
|
897 | - // so log the exception |
|
898 | - Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [ |
|
899 | - 'app' => 'core', |
|
900 | - 'exception' => $e, |
|
901 | - ]); |
|
902 | - } |
|
903 | - }); |
|
904 | - } |
|
905 | - } |
|
906 | - |
|
907 | - private static function registerEncryptionWrapperAndHooks(): void { |
|
908 | - /** @var \OC\Encryption\Manager */ |
|
909 | - $manager = Server::get(\OCP\Encryption\IManager::class); |
|
910 | - Server::get(IEventDispatcher::class)->addListener( |
|
911 | - BeforeFileSystemSetupEvent::class, |
|
912 | - $manager->setupStorage(...), |
|
913 | - ); |
|
914 | - |
|
915 | - $enabled = $manager->isEnabled(); |
|
916 | - if ($enabled) { |
|
917 | - \OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class)); |
|
918 | - } |
|
919 | - } |
|
920 | - |
|
921 | - private static function registerAccountHooks(): void { |
|
922 | - /** @var IEventDispatcher $dispatcher */ |
|
923 | - $dispatcher = Server::get(IEventDispatcher::class); |
|
924 | - $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
925 | - } |
|
926 | - |
|
927 | - private static function registerAppRestrictionsHooks(): void { |
|
928 | - /** @var \OC\Group\Manager $groupManager */ |
|
929 | - $groupManager = Server::get(\OCP\IGroupManager::class); |
|
930 | - $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
931 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
932 | - $apps = $appManager->getEnabledAppsForGroup($group); |
|
933 | - foreach ($apps as $appId) { |
|
934 | - $restrictions = $appManager->getAppRestriction($appId); |
|
935 | - if (empty($restrictions)) { |
|
936 | - continue; |
|
937 | - } |
|
938 | - $key = array_search($group->getGID(), $restrictions); |
|
939 | - unset($restrictions[$key]); |
|
940 | - $restrictions = array_values($restrictions); |
|
941 | - if (empty($restrictions)) { |
|
942 | - $appManager->disableApp($appId); |
|
943 | - } else { |
|
944 | - $appManager->enableAppForGroups($appId, $restrictions); |
|
945 | - } |
|
946 | - } |
|
947 | - }); |
|
948 | - } |
|
949 | - |
|
950 | - private static function registerResourceCollectionHooks(): void { |
|
951 | - \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class)); |
|
952 | - } |
|
953 | - |
|
954 | - private static function registerFileReferenceEventListener(): void { |
|
955 | - \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
956 | - } |
|
957 | - |
|
958 | - private static function registerRenderReferenceEventListener() { |
|
959 | - \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
960 | - } |
|
961 | - |
|
962 | - /** |
|
963 | - * register hooks for sharing |
|
964 | - */ |
|
965 | - public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { |
|
966 | - if ($systemConfig->getValue('installed')) { |
|
967 | - |
|
968 | - $dispatcher = Server::get(IEventDispatcher::class); |
|
969 | - $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class); |
|
970 | - $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class); |
|
971 | - $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class); |
|
972 | - } |
|
973 | - } |
|
974 | - |
|
975 | - /** |
|
976 | - * Handle the request |
|
977 | - */ |
|
978 | - public static function handleRequest(): void { |
|
979 | - Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request'); |
|
980 | - $systemConfig = Server::get(\OC\SystemConfig::class); |
|
981 | - |
|
982 | - // Check if Nextcloud is installed or in maintenance (update) mode |
|
983 | - if (!$systemConfig->getValue('installed', false)) { |
|
984 | - \OC::$server->getSession()->clear(); |
|
985 | - $controller = Server::get(\OC\Core\Controller\SetupController::class); |
|
986 | - $controller->run($_POST); |
|
987 | - exit(); |
|
988 | - } |
|
989 | - |
|
990 | - $request = Server::get(IRequest::class); |
|
991 | - $request->throwDecodingExceptionIfAny(); |
|
992 | - $requestPath = $request->getRawPathInfo(); |
|
993 | - if ($requestPath === '/heartbeat') { |
|
994 | - return; |
|
995 | - } |
|
996 | - if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
997 | - self::checkMaintenanceMode($systemConfig); |
|
998 | - |
|
999 | - if (\OCP\Util::needUpgrade()) { |
|
1000 | - if (function_exists('opcache_reset')) { |
|
1001 | - opcache_reset(); |
|
1002 | - } |
|
1003 | - if (!((bool)$systemConfig->getValue('maintenance', false))) { |
|
1004 | - self::printUpgradePage($systemConfig); |
|
1005 | - exit(); |
|
1006 | - } |
|
1007 | - } |
|
1008 | - } |
|
1009 | - |
|
1010 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
1011 | - |
|
1012 | - // Always load authentication apps |
|
1013 | - $appManager->loadApps(['authentication']); |
|
1014 | - $appManager->loadApps(['extended_authentication']); |
|
1015 | - |
|
1016 | - // Load minimum set of apps |
|
1017 | - if (!\OCP\Util::needUpgrade() |
|
1018 | - && !((bool)$systemConfig->getValue('maintenance', false))) { |
|
1019 | - // For logged-in users: Load everything |
|
1020 | - if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1021 | - $appManager->loadApps(); |
|
1022 | - } else { |
|
1023 | - // For guests: Load only filesystem and logging |
|
1024 | - $appManager->loadApps(['filesystem', 'logging']); |
|
1025 | - |
|
1026 | - // Don't try to login when a client is trying to get a OAuth token. |
|
1027 | - // OAuth needs to support basic auth too, so the login is not valid |
|
1028 | - // inside Nextcloud and the Login exception would ruin it. |
|
1029 | - if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') { |
|
1030 | - try { |
|
1031 | - self::handleLogin($request); |
|
1032 | - } catch (DisabledUserException $e) { |
|
1033 | - // Disabled users would not be seen as logged in and |
|
1034 | - // trying to log them in would fail, so the login |
|
1035 | - // exception is ignored for the themed stylesheets and |
|
1036 | - // images. |
|
1037 | - if ($request->getRawPathInfo() !== '/apps/theming/theme/default.css' |
|
1038 | - && $request->getRawPathInfo() !== '/apps/theming/theme/light.css' |
|
1039 | - && $request->getRawPathInfo() !== '/apps/theming/theme/dark.css' |
|
1040 | - && $request->getRawPathInfo() !== '/apps/theming/theme/light-highcontrast.css' |
|
1041 | - && $request->getRawPathInfo() !== '/apps/theming/theme/dark-highcontrast.css' |
|
1042 | - && $request->getRawPathInfo() !== '/apps/theming/theme/opendyslexic.css' |
|
1043 | - && $request->getRawPathInfo() !== '/apps/theming/image/background' |
|
1044 | - && $request->getRawPathInfo() !== '/apps/theming/image/logo' |
|
1045 | - && $request->getRawPathInfo() !== '/apps/theming/image/logoheader' |
|
1046 | - && !str_starts_with($request->getRawPathInfo(), '/apps/theming/favicon') |
|
1047 | - && !str_starts_with($request->getRawPathInfo(), '/apps/theming/icon')) { |
|
1048 | - throw $e; |
|
1049 | - } |
|
1050 | - } |
|
1051 | - } |
|
1052 | - } |
|
1053 | - } |
|
1054 | - |
|
1055 | - if (!self::$CLI) { |
|
1056 | - try { |
|
1057 | - if (!\OCP\Util::needUpgrade()) { |
|
1058 | - $appManager->loadApps(['filesystem', 'logging']); |
|
1059 | - $appManager->loadApps(); |
|
1060 | - } |
|
1061 | - Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
1062 | - return; |
|
1063 | - } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
1064 | - //header('HTTP/1.0 404 Not Found'); |
|
1065 | - } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
1066 | - http_response_code(405); |
|
1067 | - return; |
|
1068 | - } |
|
1069 | - } |
|
1070 | - |
|
1071 | - // Handle WebDAV |
|
1072 | - if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
1073 | - // not allowed any more to prevent people |
|
1074 | - // mounting this root directly. |
|
1075 | - // Users need to mount remote.php/webdav instead. |
|
1076 | - http_response_code(405); |
|
1077 | - return; |
|
1078 | - } |
|
1079 | - |
|
1080 | - // Handle requests for JSON or XML |
|
1081 | - $acceptHeader = $request->getHeader('Accept'); |
|
1082 | - if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) { |
|
1083 | - http_response_code(404); |
|
1084 | - return; |
|
1085 | - } |
|
1086 | - |
|
1087 | - // Handle resources that can't be found |
|
1088 | - // This prevents browsers from redirecting to the default page and then |
|
1089 | - // attempting to parse HTML as CSS and similar. |
|
1090 | - $destinationHeader = $request->getHeader('Sec-Fetch-Dest'); |
|
1091 | - if (in_array($destinationHeader, ['font', 'script', 'style'])) { |
|
1092 | - http_response_code(404); |
|
1093 | - return; |
|
1094 | - } |
|
1095 | - |
|
1096 | - // Redirect to the default app or login only as an entry point |
|
1097 | - if ($requestPath === '') { |
|
1098 | - // Someone is logged in |
|
1099 | - if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1100 | - header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl()); |
|
1101 | - } else { |
|
1102 | - // Not handled and not logged in |
|
1103 | - header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm')); |
|
1104 | - } |
|
1105 | - return; |
|
1106 | - } |
|
1107 | - |
|
1108 | - try { |
|
1109 | - Server::get(\OC\Route\Router::class)->match('/error/404'); |
|
1110 | - } catch (\Exception $e) { |
|
1111 | - if (!$e instanceof MethodNotAllowedException) { |
|
1112 | - logger('core')->emergency($e->getMessage(), ['exception' => $e]); |
|
1113 | - } |
|
1114 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
1115 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
1116 | - '404', |
|
1117 | - $l->t('The page could not be found on the server.'), |
|
1118 | - 404 |
|
1119 | - ); |
|
1120 | - } |
|
1121 | - } |
|
1122 | - |
|
1123 | - /** |
|
1124 | - * Check login: apache auth, auth token, basic auth |
|
1125 | - */ |
|
1126 | - public static function handleLogin(OCP\IRequest $request): bool { |
|
1127 | - if ($request->getHeader('X-Nextcloud-Federation')) { |
|
1128 | - return false; |
|
1129 | - } |
|
1130 | - $userSession = Server::get(\OC\User\Session::class); |
|
1131 | - if (OC_User::handleApacheAuth()) { |
|
1132 | - return true; |
|
1133 | - } |
|
1134 | - if (self::tryAppAPILogin($request)) { |
|
1135 | - return true; |
|
1136 | - } |
|
1137 | - if ($userSession->tryTokenLogin($request)) { |
|
1138 | - return true; |
|
1139 | - } |
|
1140 | - if (isset($_COOKIE['nc_username']) |
|
1141 | - && isset($_COOKIE['nc_token']) |
|
1142 | - && isset($_COOKIE['nc_session_id']) |
|
1143 | - && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
1144 | - return true; |
|
1145 | - } |
|
1146 | - if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) { |
|
1147 | - return true; |
|
1148 | - } |
|
1149 | - return false; |
|
1150 | - } |
|
1151 | - |
|
1152 | - protected static function handleAuthHeaders(): void { |
|
1153 | - //copy http auth headers for apache+php-fcgid work around |
|
1154 | - if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
1155 | - $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
1156 | - } |
|
1157 | - |
|
1158 | - // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
1159 | - $vars = [ |
|
1160 | - 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
1161 | - 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
1162 | - ]; |
|
1163 | - foreach ($vars as $var) { |
|
1164 | - if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
1165 | - $credentials = explode(':', base64_decode($matches[1]), 2); |
|
1166 | - if (count($credentials) === 2) { |
|
1167 | - $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
1168 | - $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
1169 | - break; |
|
1170 | - } |
|
1171 | - } |
|
1172 | - } |
|
1173 | - } |
|
1174 | - |
|
1175 | - protected static function tryAppAPILogin(OCP\IRequest $request): bool { |
|
1176 | - if (!$request->getHeader('AUTHORIZATION-APP-API')) { |
|
1177 | - return false; |
|
1178 | - } |
|
1179 | - $appManager = Server::get(OCP\App\IAppManager::class); |
|
1180 | - if (!$appManager->isEnabledForAnyone('app_api')) { |
|
1181 | - return false; |
|
1182 | - } |
|
1183 | - try { |
|
1184 | - $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class); |
|
1185 | - return $appAPIService->validateExAppRequestToNC($request); |
|
1186 | - } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) { |
|
1187 | - return false; |
|
1188 | - } |
|
1189 | - } |
|
43 | + /** |
|
44 | + * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
45 | + */ |
|
46 | + public static string $SERVERROOT = ''; |
|
47 | + /** |
|
48 | + * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
49 | + */ |
|
50 | + private static string $SUBURI = ''; |
|
51 | + /** |
|
52 | + * the Nextcloud root path for http requests (e.g. /nextcloud) |
|
53 | + */ |
|
54 | + public static string $WEBROOT = ''; |
|
55 | + /** |
|
56 | + * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
57 | + * web path in 'url' |
|
58 | + */ |
|
59 | + public static array $APPSROOTS = []; |
|
60 | + |
|
61 | + public static string $configDir; |
|
62 | + |
|
63 | + /** |
|
64 | + * requested app |
|
65 | + */ |
|
66 | + public static string $REQUESTEDAPP = ''; |
|
67 | + |
|
68 | + /** |
|
69 | + * check if Nextcloud runs in cli mode |
|
70 | + */ |
|
71 | + public static bool $CLI = false; |
|
72 | + |
|
73 | + public static \Composer\Autoload\ClassLoader $composerAutoloader; |
|
74 | + |
|
75 | + public static \OC\Server $server; |
|
76 | + |
|
77 | + private static \OC\Config $config; |
|
78 | + |
|
79 | + /** |
|
80 | + * @throws \RuntimeException when the 3rdparty directory is missing or |
|
81 | + * the app path list is empty or contains an invalid path |
|
82 | + */ |
|
83 | + public static function initPaths(): void { |
|
84 | + if (defined('PHPUNIT_CONFIG_DIR')) { |
|
85 | + self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
86 | + } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
87 | + self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
88 | + } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
89 | + self::$configDir = rtrim($dir, '/') . '/'; |
|
90 | + } else { |
|
91 | + self::$configDir = OC::$SERVERROOT . '/config/'; |
|
92 | + } |
|
93 | + self::$config = new \OC\Config(self::$configDir); |
|
94 | + |
|
95 | + OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT))); |
|
96 | + /** |
|
97 | + * FIXME: The following lines are required because we can't yet instantiate |
|
98 | + * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist. |
|
99 | + */ |
|
100 | + $params = [ |
|
101 | + 'server' => [ |
|
102 | + 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null, |
|
103 | + 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null, |
|
104 | + ], |
|
105 | + ]; |
|
106 | + if (isset($_SERVER['REMOTE_ADDR'])) { |
|
107 | + $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; |
|
108 | + } |
|
109 | + $fakeRequest = new \OC\AppFramework\Http\Request( |
|
110 | + $params, |
|
111 | + new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()), |
|
112 | + new \OC\AllConfig(new \OC\SystemConfig(self::$config)) |
|
113 | + ); |
|
114 | + $scriptName = $fakeRequest->getScriptName(); |
|
115 | + if (substr($scriptName, -1) == '/') { |
|
116 | + $scriptName .= 'index.php'; |
|
117 | + //make sure suburi follows the same rules as scriptName |
|
118 | + if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
119 | + if (substr(OC::$SUBURI, -1) != '/') { |
|
120 | + OC::$SUBURI = OC::$SUBURI . '/'; |
|
121 | + } |
|
122 | + OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
123 | + } |
|
124 | + } |
|
125 | + |
|
126 | + if (OC::$CLI) { |
|
127 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
128 | + } else { |
|
129 | + if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
130 | + OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
131 | + |
|
132 | + if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
133 | + OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
134 | + } |
|
135 | + } else { |
|
136 | + // The scriptName is not ending with OC::$SUBURI |
|
137 | + // This most likely means that we are calling from CLI. |
|
138 | + // However some cron jobs still need to generate |
|
139 | + // a web URL, so we use overwritewebroot as a fallback. |
|
140 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
141 | + } |
|
142 | + |
|
143 | + // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
144 | + // slash which is required by URL generation. |
|
145 | + if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT |
|
146 | + && substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
147 | + header('Location: ' . \OC::$WEBROOT . '/'); |
|
148 | + exit(); |
|
149 | + } |
|
150 | + } |
|
151 | + |
|
152 | + // search the apps folder |
|
153 | + $config_paths = self::$config->getValue('apps_paths', []); |
|
154 | + if (!empty($config_paths)) { |
|
155 | + foreach ($config_paths as $paths) { |
|
156 | + if (isset($paths['url']) && isset($paths['path'])) { |
|
157 | + $paths['url'] = rtrim($paths['url'], '/'); |
|
158 | + $paths['path'] = rtrim($paths['path'], '/'); |
|
159 | + OC::$APPSROOTS[] = $paths; |
|
160 | + } |
|
161 | + } |
|
162 | + } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
163 | + OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
164 | + } |
|
165 | + |
|
166 | + if (empty(OC::$APPSROOTS)) { |
|
167 | + throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
168 | + . '. You can also configure the location in the config.php file.'); |
|
169 | + } |
|
170 | + $paths = []; |
|
171 | + foreach (OC::$APPSROOTS as $path) { |
|
172 | + $paths[] = $path['path']; |
|
173 | + if (!is_dir($path['path'])) { |
|
174 | + throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
175 | + . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
176 | + } |
|
177 | + } |
|
178 | + |
|
179 | + // set the right include path |
|
180 | + set_include_path( |
|
181 | + implode(PATH_SEPARATOR, $paths) |
|
182 | + ); |
|
183 | + } |
|
184 | + |
|
185 | + public static function checkConfig(): void { |
|
186 | + // Create config if it does not already exist |
|
187 | + $configFilePath = self::$configDir . '/config.php'; |
|
188 | + if (!file_exists($configFilePath)) { |
|
189 | + @touch($configFilePath); |
|
190 | + } |
|
191 | + |
|
192 | + // Check if config is writable |
|
193 | + $configFileWritable = is_writable($configFilePath); |
|
194 | + $configReadOnly = Server::get(IConfig::class)->getSystemValueBool('config_is_read_only'); |
|
195 | + if (!$configFileWritable && !$configReadOnly |
|
196 | + || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
197 | + $urlGenerator = Server::get(IURLGenerator::class); |
|
198 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
199 | + |
|
200 | + if (self::$CLI) { |
|
201 | + echo $l->t('Cannot write into "config" directory!') . "\n"; |
|
202 | + echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n"; |
|
203 | + echo "\n"; |
|
204 | + echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n"; |
|
205 | + echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n"; |
|
206 | + exit; |
|
207 | + } else { |
|
208 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
209 | + $l->t('Cannot write into "config" directory!'), |
|
210 | + $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' ' |
|
211 | + . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
212 | + . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
213 | + 503 |
|
214 | + ); |
|
215 | + } |
|
216 | + } |
|
217 | + } |
|
218 | + |
|
219 | + public static function checkInstalled(\OC\SystemConfig $systemConfig): void { |
|
220 | + if (defined('OC_CONSOLE')) { |
|
221 | + return; |
|
222 | + } |
|
223 | + // Redirect to installer if not installed |
|
224 | + if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
|
225 | + if (OC::$CLI) { |
|
226 | + throw new Exception('Not installed'); |
|
227 | + } else { |
|
228 | + $url = OC::$WEBROOT . '/index.php'; |
|
229 | + header('Location: ' . $url); |
|
230 | + } |
|
231 | + exit(); |
|
232 | + } |
|
233 | + } |
|
234 | + |
|
235 | + public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { |
|
236 | + // Allow ajax update script to execute without being stopped |
|
237 | + if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
238 | + // send http status 503 |
|
239 | + http_response_code(503); |
|
240 | + header('X-Nextcloud-Maintenance-Mode: 1'); |
|
241 | + header('Retry-After: 120'); |
|
242 | + |
|
243 | + // render error page |
|
244 | + $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest'); |
|
245 | + \OCP\Util::addScript('core', 'maintenance'); |
|
246 | + \OCP\Util::addStyle('core', 'guest'); |
|
247 | + $template->printPage(); |
|
248 | + die(); |
|
249 | + } |
|
250 | + } |
|
251 | + |
|
252 | + /** |
|
253 | + * Prints the upgrade page |
|
254 | + */ |
|
255 | + private static function printUpgradePage(\OC\SystemConfig $systemConfig): void { |
|
256 | + $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', ''); |
|
257 | + $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
258 | + $tooBig = false; |
|
259 | + if (!$disableWebUpdater) { |
|
260 | + $apps = Server::get(\OCP\App\IAppManager::class); |
|
261 | + if ($apps->isEnabledForAnyone('user_ldap')) { |
|
262 | + $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
263 | + |
|
264 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
265 | + ->from('ldap_user_mapping') |
|
266 | + ->executeQuery(); |
|
267 | + $row = $result->fetch(); |
|
268 | + $result->closeCursor(); |
|
269 | + |
|
270 | + $tooBig = ($row['user_count'] > 50); |
|
271 | + } |
|
272 | + if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) { |
|
273 | + $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
274 | + |
|
275 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
276 | + ->from('user_saml_users') |
|
277 | + ->executeQuery(); |
|
278 | + $row = $result->fetch(); |
|
279 | + $result->closeCursor(); |
|
280 | + |
|
281 | + $tooBig = ($row['user_count'] > 50); |
|
282 | + } |
|
283 | + if (!$tooBig) { |
|
284 | + // count users |
|
285 | + $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51); |
|
286 | + $tooBig = ($totalUsers > 50); |
|
287 | + } |
|
288 | + } |
|
289 | + $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) |
|
290 | + && $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
291 | + |
|
292 | + if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
293 | + // send http status 503 |
|
294 | + http_response_code(503); |
|
295 | + header('Retry-After: 120'); |
|
296 | + |
|
297 | + $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class); |
|
298 | + |
|
299 | + // render error page |
|
300 | + $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest'); |
|
301 | + $template->assign('productName', 'nextcloud'); // for now |
|
302 | + $template->assign('version', $serverVersion->getVersionString()); |
|
303 | + $template->assign('tooBig', $tooBig); |
|
304 | + $template->assign('cliUpgradeLink', $cliUpgradeLink); |
|
305 | + |
|
306 | + $template->printPage(); |
|
307 | + die(); |
|
308 | + } |
|
309 | + |
|
310 | + // check whether this is a core update or apps update |
|
311 | + $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
312 | + $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
313 | + |
|
314 | + // if not a core upgrade, then it's apps upgrade |
|
315 | + $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
316 | + |
|
317 | + $oldTheme = $systemConfig->getValue('theme'); |
|
318 | + $systemConfig->setValue('theme', ''); |
|
319 | + \OCP\Util::addScript('core', 'common'); |
|
320 | + \OCP\Util::addScript('core', 'main'); |
|
321 | + \OCP\Util::addTranslations('core'); |
|
322 | + \OCP\Util::addScript('core', 'update'); |
|
323 | + |
|
324 | + /** @var \OC\App\AppManager $appManager */ |
|
325 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
326 | + |
|
327 | + $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest'); |
|
328 | + $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString()); |
|
329 | + $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
330 | + |
|
331 | + // get third party apps |
|
332 | + $ocVersion = \OCP\Util::getVersion(); |
|
333 | + $ocVersion = implode('.', $ocVersion); |
|
334 | + $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
335 | + $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []); |
|
336 | + $incompatibleShippedApps = []; |
|
337 | + $incompatibleDisabledApps = []; |
|
338 | + foreach ($incompatibleApps as $appInfo) { |
|
339 | + if ($appManager->isShipped($appInfo['id'])) { |
|
340 | + $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
341 | + } |
|
342 | + if (!in_array($appInfo['id'], $incompatibleOverwrites)) { |
|
343 | + $incompatibleDisabledApps[] = $appInfo; |
|
344 | + } |
|
345 | + } |
|
346 | + |
|
347 | + if (!empty($incompatibleShippedApps)) { |
|
348 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('core'); |
|
349 | + $hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]); |
|
350 | + throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint); |
|
351 | + } |
|
352 | + |
|
353 | + $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
354 | + $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps); |
|
355 | + try { |
|
356 | + $defaults = new \OC_Defaults(); |
|
357 | + $tmpl->assign('productName', $defaults->getName()); |
|
358 | + } catch (Throwable $error) { |
|
359 | + $tmpl->assign('productName', 'Nextcloud'); |
|
360 | + } |
|
361 | + $tmpl->assign('oldTheme', $oldTheme); |
|
362 | + $tmpl->printPage(); |
|
363 | + } |
|
364 | + |
|
365 | + public static function initSession(): void { |
|
366 | + $request = Server::get(IRequest::class); |
|
367 | + |
|
368 | + // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies |
|
369 | + // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments |
|
370 | + // TODO: for further information. |
|
371 | + // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0; |
|
372 | + // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) { |
|
373 | + // setcookie('cookie_test', 'test', time() + 3600); |
|
374 | + // // Do not initialize the session if a request is authenticated directly |
|
375 | + // // unless there is a session cookie already sent along |
|
376 | + // return; |
|
377 | + // } |
|
378 | + |
|
379 | + if ($request->getServerProtocol() === 'https') { |
|
380 | + ini_set('session.cookie_secure', 'true'); |
|
381 | + } |
|
382 | + |
|
383 | + // prevents javascript from accessing php session cookies |
|
384 | + ini_set('session.cookie_httponly', 'true'); |
|
385 | + |
|
386 | + // Do not initialize sessions for 'status.php' requests |
|
387 | + // Monitoring endpoints can quickly flood session handlers |
|
388 | + // and 'status.php' doesn't require sessions anyway |
|
389 | + if (str_ends_with($request->getScriptName(), '/status.php')) { |
|
390 | + return; |
|
391 | + } |
|
392 | + |
|
393 | + // set the cookie path to the Nextcloud directory |
|
394 | + $cookie_path = OC::$WEBROOT ? : '/'; |
|
395 | + ini_set('session.cookie_path', $cookie_path); |
|
396 | + |
|
397 | + // set the cookie domain to the Nextcloud domain |
|
398 | + $cookie_domain = self::$config->getValue('cookie_domain', ''); |
|
399 | + if ($cookie_domain) { |
|
400 | + ini_set('session.cookie_domain', $cookie_domain); |
|
401 | + } |
|
402 | + |
|
403 | + // Let the session name be changed in the initSession Hook |
|
404 | + $sessionName = OC_Util::getInstanceId(); |
|
405 | + |
|
406 | + try { |
|
407 | + $logger = null; |
|
408 | + if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) { |
|
409 | + $logger = logger('core'); |
|
410 | + } |
|
411 | + |
|
412 | + // set the session name to the instance id - which is unique |
|
413 | + $session = new \OC\Session\Internal( |
|
414 | + $sessionName, |
|
415 | + $logger, |
|
416 | + ); |
|
417 | + |
|
418 | + $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class); |
|
419 | + $session = $cryptoWrapper->wrapSession($session); |
|
420 | + self::$server->setSession($session); |
|
421 | + |
|
422 | + // if session can't be started break with http 500 error |
|
423 | + } catch (Exception $e) { |
|
424 | + Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]); |
|
425 | + //show the user a detailed error page |
|
426 | + Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500); |
|
427 | + die(); |
|
428 | + } |
|
429 | + |
|
430 | + //try to set the session lifetime |
|
431 | + $sessionLifeTime = self::getSessionLifeTime(); |
|
432 | + |
|
433 | + // session timeout |
|
434 | + if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
435 | + if (isset($_COOKIE[session_name()])) { |
|
436 | + setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
437 | + } |
|
438 | + Server::get(IUserSession::class)->logout(); |
|
439 | + } |
|
440 | + |
|
441 | + if (!self::hasSessionRelaxedExpiry()) { |
|
442 | + $session->set('LAST_ACTIVITY', time()); |
|
443 | + } |
|
444 | + $session->close(); |
|
445 | + } |
|
446 | + |
|
447 | + private static function getSessionLifeTime(): int { |
|
448 | + return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24); |
|
449 | + } |
|
450 | + |
|
451 | + /** |
|
452 | + * @return bool true if the session expiry should only be done by gc instead of an explicit timeout |
|
453 | + */ |
|
454 | + public static function hasSessionRelaxedExpiry(): bool { |
|
455 | + return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false); |
|
456 | + } |
|
457 | + |
|
458 | + /** |
|
459 | + * Try to set some values to the required Nextcloud default |
|
460 | + */ |
|
461 | + public static function setRequiredIniValues(): void { |
|
462 | + // Don't display errors and log them |
|
463 | + @ini_set('display_errors', '0'); |
|
464 | + @ini_set('log_errors', '1'); |
|
465 | + |
|
466 | + // Try to configure php to enable big file uploads. |
|
467 | + // This doesn't work always depending on the webserver and php configuration. |
|
468 | + // Let's try to overwrite some defaults if they are smaller than 1 hour |
|
469 | + |
|
470 | + if (intval(@ini_get('max_execution_time') ?: 0) < 3600) { |
|
471 | + @ini_set('max_execution_time', strval(3600)); |
|
472 | + } |
|
473 | + |
|
474 | + if (intval(@ini_get('max_input_time') ?: 0) < 3600) { |
|
475 | + @ini_set('max_input_time', strval(3600)); |
|
476 | + } |
|
477 | + |
|
478 | + // Try to set the maximum execution time to the largest time limit we have |
|
479 | + if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
480 | + @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time')))); |
|
481 | + } |
|
482 | + |
|
483 | + @ini_set('default_charset', 'UTF-8'); |
|
484 | + @ini_set('gd.jpeg_ignore_warning', '1'); |
|
485 | + } |
|
486 | + |
|
487 | + /** |
|
488 | + * Send the same site cookies |
|
489 | + */ |
|
490 | + private static function sendSameSiteCookies(): void { |
|
491 | + $cookieParams = session_get_cookie_params(); |
|
492 | + $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
493 | + $policies = [ |
|
494 | + 'lax', |
|
495 | + 'strict', |
|
496 | + ]; |
|
497 | + |
|
498 | + // Append __Host to the cookie if it meets the requirements |
|
499 | + $cookiePrefix = ''; |
|
500 | + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
501 | + $cookiePrefix = '__Host-'; |
|
502 | + } |
|
503 | + |
|
504 | + foreach ($policies as $policy) { |
|
505 | + header( |
|
506 | + sprintf( |
|
507 | + 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
508 | + $cookiePrefix, |
|
509 | + $policy, |
|
510 | + $cookieParams['path'], |
|
511 | + $policy |
|
512 | + ), |
|
513 | + false |
|
514 | + ); |
|
515 | + } |
|
516 | + } |
|
517 | + |
|
518 | + /** |
|
519 | + * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
520 | + * be set in every request if cookies are sent to add a second level of |
|
521 | + * defense against CSRF. |
|
522 | + * |
|
523 | + * If the cookie is not sent this will set the cookie and reload the page. |
|
524 | + * We use an additional cookie since we want to protect logout CSRF and |
|
525 | + * also we can't directly interfere with PHP's session mechanism. |
|
526 | + */ |
|
527 | + private static function performSameSiteCookieProtection(IConfig $config): void { |
|
528 | + $request = Server::get(IRequest::class); |
|
529 | + |
|
530 | + // Some user agents are notorious and don't really properly follow HTTP |
|
531 | + // specifications. For those, have an automated opt-out. Since the protection |
|
532 | + // for remote.php is applied in base.php as starting point we need to opt out |
|
533 | + // here. |
|
534 | + $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
535 | + |
|
536 | + // Fallback, if csrf.optout is unset |
|
537 | + if (!is_array($incompatibleUserAgents)) { |
|
538 | + $incompatibleUserAgents = [ |
|
539 | + // OS X Finder |
|
540 | + '/^WebDAVFS/', |
|
541 | + // Windows webdav drive |
|
542 | + '/^Microsoft-WebDAV-MiniRedir/', |
|
543 | + ]; |
|
544 | + } |
|
545 | + |
|
546 | + if ($request->isUserAgent($incompatibleUserAgents)) { |
|
547 | + return; |
|
548 | + } |
|
549 | + |
|
550 | + if (count($_COOKIE) > 0) { |
|
551 | + $requestUri = $request->getScriptName(); |
|
552 | + $processingScript = explode('/', $requestUri); |
|
553 | + $processingScript = $processingScript[count($processingScript) - 1]; |
|
554 | + |
|
555 | + if ($processingScript === 'index.php' // index.php routes are handled in the middleware |
|
556 | + || $processingScript === 'cron.php' // and cron.php does not need any authentication at all |
|
557 | + || $processingScript === 'public.php' // For public.php, auth for password protected shares is done in the PublicAuth plugin |
|
558 | + ) { |
|
559 | + return; |
|
560 | + } |
|
561 | + |
|
562 | + // All other endpoints require the lax and the strict cookie |
|
563 | + if (!$request->passesStrictCookieCheck()) { |
|
564 | + logger('core')->warning('Request does not pass strict cookie check'); |
|
565 | + self::sendSameSiteCookies(); |
|
566 | + // Debug mode gets access to the resources without strict cookie |
|
567 | + // due to the fact that the SabreDAV browser also lives there. |
|
568 | + if (!$config->getSystemValueBool('debug', false)) { |
|
569 | + http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED); |
|
570 | + header('Content-Type: application/json'); |
|
571 | + echo json_encode(['error' => 'Strict Cookie has not been found in request']); |
|
572 | + exit(); |
|
573 | + } |
|
574 | + } |
|
575 | + } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
576 | + self::sendSameSiteCookies(); |
|
577 | + } |
|
578 | + } |
|
579 | + |
|
580 | + public static function init(): void { |
|
581 | + // First handle PHP configuration and copy auth headers to the expected |
|
582 | + // $_SERVER variable before doing anything Server object related |
|
583 | + self::setRequiredIniValues(); |
|
584 | + self::handleAuthHeaders(); |
|
585 | + |
|
586 | + // prevent any XML processing from loading external entities |
|
587 | + libxml_set_external_entity_loader(static function () { |
|
588 | + return null; |
|
589 | + }); |
|
590 | + |
|
591 | + // Set default timezone before the Server object is booted |
|
592 | + if (!date_default_timezone_set('UTC')) { |
|
593 | + throw new \RuntimeException('Could not set timezone to UTC'); |
|
594 | + } |
|
595 | + |
|
596 | + // calculate the root directories |
|
597 | + OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4)); |
|
598 | + |
|
599 | + // register autoloader |
|
600 | + $loaderStart = microtime(true); |
|
601 | + |
|
602 | + self::$CLI = (php_sapi_name() == 'cli'); |
|
603 | + |
|
604 | + // Add default composer PSR-4 autoloader, ensure apcu to be disabled |
|
605 | + self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
606 | + self::$composerAutoloader->setApcuPrefix(null); |
|
607 | + |
|
608 | + |
|
609 | + try { |
|
610 | + self::initPaths(); |
|
611 | + // setup 3rdparty autoloader |
|
612 | + $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php'; |
|
613 | + if (!file_exists($vendorAutoLoad)) { |
|
614 | + throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); |
|
615 | + } |
|
616 | + require_once $vendorAutoLoad; |
|
617 | + } catch (\RuntimeException $e) { |
|
618 | + if (!self::$CLI) { |
|
619 | + http_response_code(503); |
|
620 | + } |
|
621 | + // we can't use the template error page here, because this needs the |
|
622 | + // DI container which isn't available yet |
|
623 | + print($e->getMessage()); |
|
624 | + exit(); |
|
625 | + } |
|
626 | + $loaderEnd = microtime(true); |
|
627 | + |
|
628 | + // Enable lazy loading if activated |
|
629 | + \OC\AppFramework\Utility\SimpleContainer::$useLazyObjects = (bool)self::$config->getValue('enable_lazy_objects', true); |
|
630 | + |
|
631 | + // setup the basic server |
|
632 | + self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
633 | + self::$server->boot(); |
|
634 | + |
|
635 | + try { |
|
636 | + $profiler = new BuiltInProfiler( |
|
637 | + Server::get(IConfig::class), |
|
638 | + Server::get(IRequest::class), |
|
639 | + ); |
|
640 | + $profiler->start(); |
|
641 | + } catch (\Throwable $e) { |
|
642 | + logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']); |
|
643 | + } |
|
644 | + |
|
645 | + if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) { |
|
646 | + \OC\Core\Listener\BeforeMessageLoggedEventListener::setup(); |
|
647 | + } |
|
648 | + |
|
649 | + $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class); |
|
650 | + $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
651 | + $eventLogger->start('boot', 'Initialize'); |
|
652 | + |
|
653 | + // Override php.ini and log everything if we're troubleshooting |
|
654 | + if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
655 | + error_reporting(E_ALL); |
|
656 | + } |
|
657 | + |
|
658 | + // initialize intl fallback if necessary |
|
659 | + OC_Util::isSetLocaleWorking(); |
|
660 | + |
|
661 | + $config = Server::get(IConfig::class); |
|
662 | + if (!defined('PHPUNIT_RUN')) { |
|
663 | + $errorHandler = new OC\Log\ErrorHandler( |
|
664 | + \OCP\Server::get(\Psr\Log\LoggerInterface::class), |
|
665 | + ); |
|
666 | + $exceptionHandler = [$errorHandler, 'onException']; |
|
667 | + if ($config->getSystemValueBool('debug', false)) { |
|
668 | + set_error_handler([$errorHandler, 'onAll'], E_ALL); |
|
669 | + if (\OC::$CLI) { |
|
670 | + $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage']; |
|
671 | + } |
|
672 | + } else { |
|
673 | + set_error_handler([$errorHandler, 'onError']); |
|
674 | + } |
|
675 | + register_shutdown_function([$errorHandler, 'onShutdown']); |
|
676 | + set_exception_handler($exceptionHandler); |
|
677 | + } |
|
678 | + |
|
679 | + /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
680 | + $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
681 | + $bootstrapCoordinator->runInitialRegistration(); |
|
682 | + |
|
683 | + $eventLogger->start('init_session', 'Initialize session'); |
|
684 | + |
|
685 | + // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users |
|
686 | + // see https://github.com/nextcloud/server/pull/2619 |
|
687 | + if (!function_exists('simplexml_load_file')) { |
|
688 | + throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.'); |
|
689 | + } |
|
690 | + |
|
691 | + $systemConfig = Server::get(\OC\SystemConfig::class); |
|
692 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
693 | + if ($systemConfig->getValue('installed', false)) { |
|
694 | + $appManager->loadApps(['session']); |
|
695 | + } |
|
696 | + if (!self::$CLI) { |
|
697 | + self::initSession(); |
|
698 | + } |
|
699 | + $eventLogger->end('init_session'); |
|
700 | + self::checkConfig(); |
|
701 | + self::checkInstalled($systemConfig); |
|
702 | + |
|
703 | + OC_Response::addSecurityHeaders(); |
|
704 | + |
|
705 | + self::performSameSiteCookieProtection($config); |
|
706 | + |
|
707 | + if (!defined('OC_CONSOLE')) { |
|
708 | + $eventLogger->start('check_server', 'Run a few configuration checks'); |
|
709 | + $errors = OC_Util::checkServer($systemConfig); |
|
710 | + if (count($errors) > 0) { |
|
711 | + if (!self::$CLI) { |
|
712 | + http_response_code(503); |
|
713 | + Util::addStyle('guest'); |
|
714 | + try { |
|
715 | + Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]); |
|
716 | + exit; |
|
717 | + } catch (\Exception $e) { |
|
718 | + // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
719 | + // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
720 | + } |
|
721 | + } |
|
722 | + |
|
723 | + // Convert l10n string into regular string for usage in database |
|
724 | + $staticErrors = []; |
|
725 | + foreach ($errors as $error) { |
|
726 | + echo $error['error'] . "\n"; |
|
727 | + echo $error['hint'] . "\n\n"; |
|
728 | + $staticErrors[] = [ |
|
729 | + 'error' => (string)$error['error'], |
|
730 | + 'hint' => (string)$error['hint'], |
|
731 | + ]; |
|
732 | + } |
|
733 | + |
|
734 | + try { |
|
735 | + $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
736 | + } catch (\Exception $e) { |
|
737 | + echo('Writing to database failed'); |
|
738 | + } |
|
739 | + exit(1); |
|
740 | + } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) { |
|
741 | + $config->deleteAppValue('core', 'cronErrors'); |
|
742 | + } |
|
743 | + $eventLogger->end('check_server'); |
|
744 | + } |
|
745 | + |
|
746 | + // User and Groups |
|
747 | + if (!$systemConfig->getValue('installed', false)) { |
|
748 | + self::$server->getSession()->set('user_id', ''); |
|
749 | + } |
|
750 | + |
|
751 | + $eventLogger->start('setup_backends', 'Setup group and user backends'); |
|
752 | + Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
753 | + Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database()); |
|
754 | + |
|
755 | + // Subscribe to the hook |
|
756 | + \OCP\Util::connectHook( |
|
757 | + '\OCA\Files_Sharing\API\Server2Server', |
|
758 | + 'preLoginNameUsedAsUserName', |
|
759 | + '\OC\User\Database', |
|
760 | + 'preLoginNameUsedAsUserName' |
|
761 | + ); |
|
762 | + |
|
763 | + //setup extra user backends |
|
764 | + if (!\OCP\Util::needUpgrade()) { |
|
765 | + OC_User::setupBackends(); |
|
766 | + } else { |
|
767 | + // Run upgrades in incognito mode |
|
768 | + OC_User::setIncognitoMode(true); |
|
769 | + } |
|
770 | + $eventLogger->end('setup_backends'); |
|
771 | + |
|
772 | + self::registerCleanupHooks($systemConfig); |
|
773 | + self::registerShareHooks($systemConfig); |
|
774 | + self::registerEncryptionWrapperAndHooks(); |
|
775 | + self::registerAccountHooks(); |
|
776 | + self::registerResourceCollectionHooks(); |
|
777 | + self::registerFileReferenceEventListener(); |
|
778 | + self::registerRenderReferenceEventListener(); |
|
779 | + self::registerAppRestrictionsHooks(); |
|
780 | + |
|
781 | + // Make sure that the application class is not loaded before the database is setup |
|
782 | + if ($systemConfig->getValue('installed', false)) { |
|
783 | + $appManager->loadApp('settings'); |
|
784 | + /* Run core application registration */ |
|
785 | + $bootstrapCoordinator->runLazyRegistration('core'); |
|
786 | + } |
|
787 | + |
|
788 | + //make sure temporary files are cleaned up |
|
789 | + $tmpManager = Server::get(\OCP\ITempManager::class); |
|
790 | + register_shutdown_function([$tmpManager, 'clean']); |
|
791 | + $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class); |
|
792 | + register_shutdown_function([$lockProvider, 'releaseAll']); |
|
793 | + |
|
794 | + // Check whether the sample configuration has been copied |
|
795 | + if ($systemConfig->getValue('copied_sample_config', false)) { |
|
796 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
797 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
798 | + $l->t('Sample configuration detected'), |
|
799 | + $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'), |
|
800 | + 503 |
|
801 | + ); |
|
802 | + return; |
|
803 | + } |
|
804 | + |
|
805 | + $request = Server::get(IRequest::class); |
|
806 | + $host = $request->getInsecureServerHost(); |
|
807 | + /** |
|
808 | + * if the host passed in headers isn't trusted |
|
809 | + * FIXME: Should not be in here at all :see_no_evil: |
|
810 | + */ |
|
811 | + if (!OC::$CLI |
|
812 | + && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host) |
|
813 | + && $config->getSystemValueBool('installed', false) |
|
814 | + ) { |
|
815 | + // Allow access to CSS resources |
|
816 | + $isScssRequest = false; |
|
817 | + if (strpos($request->getPathInfo() ?: '', '/css/') === 0) { |
|
818 | + $isScssRequest = true; |
|
819 | + } |
|
820 | + |
|
821 | + if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
822 | + http_response_code(400); |
|
823 | + header('Content-Type: application/json'); |
|
824 | + echo '{"error": "Trusted domain error.", "code": 15}'; |
|
825 | + exit(); |
|
826 | + } |
|
827 | + |
|
828 | + if (!$isScssRequest) { |
|
829 | + http_response_code(400); |
|
830 | + Server::get(LoggerInterface::class)->info( |
|
831 | + 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
832 | + [ |
|
833 | + 'app' => 'core', |
|
834 | + 'remoteAddress' => $request->getRemoteAddress(), |
|
835 | + 'host' => $host, |
|
836 | + ] |
|
837 | + ); |
|
838 | + |
|
839 | + $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest'); |
|
840 | + $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains')); |
|
841 | + $tmpl->printPage(); |
|
842 | + |
|
843 | + exit(); |
|
844 | + } |
|
845 | + } |
|
846 | + $eventLogger->end('boot'); |
|
847 | + $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true)); |
|
848 | + $eventLogger->start('runtime', 'Runtime'); |
|
849 | + $eventLogger->start('request', 'Full request after boot'); |
|
850 | + register_shutdown_function(function () use ($eventLogger) { |
|
851 | + $eventLogger->end('request'); |
|
852 | + }); |
|
853 | + |
|
854 | + register_shutdown_function(function () { |
|
855 | + $memoryPeak = memory_get_peak_usage(); |
|
856 | + $logLevel = match (true) { |
|
857 | + $memoryPeak > 500_000_000 => ILogger::FATAL, |
|
858 | + $memoryPeak > 400_000_000 => ILogger::ERROR, |
|
859 | + $memoryPeak > 300_000_000 => ILogger::WARN, |
|
860 | + default => null, |
|
861 | + }; |
|
862 | + if ($logLevel !== null) { |
|
863 | + $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak); |
|
864 | + $logger = Server::get(LoggerInterface::class); |
|
865 | + $logger->log($logLevel, $message, ['app' => 'core']); |
|
866 | + } |
|
867 | + }); |
|
868 | + } |
|
869 | + |
|
870 | + /** |
|
871 | + * register hooks for the cleanup of cache and bruteforce protection |
|
872 | + */ |
|
873 | + public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { |
|
874 | + //don't try to do this before we are properly setup |
|
875 | + if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
876 | + // NOTE: This will be replaced to use OCP |
|
877 | + $userSession = Server::get(\OC\User\Session::class); |
|
878 | + $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
879 | + if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
880 | + // reset brute force delay for this IP address and username |
|
881 | + $uid = $userSession->getUser()->getUID(); |
|
882 | + $request = Server::get(IRequest::class); |
|
883 | + $throttler = Server::get(IThrottler::class); |
|
884 | + $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
885 | + } |
|
886 | + |
|
887 | + try { |
|
888 | + $cache = new \OC\Cache\File(); |
|
889 | + $cache->gc(); |
|
890 | + } catch (\OC\ServerNotAvailableException $e) { |
|
891 | + // not a GC exception, pass it on |
|
892 | + throw $e; |
|
893 | + } catch (\OC\ForbiddenException $e) { |
|
894 | + // filesystem blocked for this request, ignore |
|
895 | + } catch (\Exception $e) { |
|
896 | + // a GC exception should not prevent users from using OC, |
|
897 | + // so log the exception |
|
898 | + Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [ |
|
899 | + 'app' => 'core', |
|
900 | + 'exception' => $e, |
|
901 | + ]); |
|
902 | + } |
|
903 | + }); |
|
904 | + } |
|
905 | + } |
|
906 | + |
|
907 | + private static function registerEncryptionWrapperAndHooks(): void { |
|
908 | + /** @var \OC\Encryption\Manager */ |
|
909 | + $manager = Server::get(\OCP\Encryption\IManager::class); |
|
910 | + Server::get(IEventDispatcher::class)->addListener( |
|
911 | + BeforeFileSystemSetupEvent::class, |
|
912 | + $manager->setupStorage(...), |
|
913 | + ); |
|
914 | + |
|
915 | + $enabled = $manager->isEnabled(); |
|
916 | + if ($enabled) { |
|
917 | + \OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class)); |
|
918 | + } |
|
919 | + } |
|
920 | + |
|
921 | + private static function registerAccountHooks(): void { |
|
922 | + /** @var IEventDispatcher $dispatcher */ |
|
923 | + $dispatcher = Server::get(IEventDispatcher::class); |
|
924 | + $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
925 | + } |
|
926 | + |
|
927 | + private static function registerAppRestrictionsHooks(): void { |
|
928 | + /** @var \OC\Group\Manager $groupManager */ |
|
929 | + $groupManager = Server::get(\OCP\IGroupManager::class); |
|
930 | + $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
931 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
932 | + $apps = $appManager->getEnabledAppsForGroup($group); |
|
933 | + foreach ($apps as $appId) { |
|
934 | + $restrictions = $appManager->getAppRestriction($appId); |
|
935 | + if (empty($restrictions)) { |
|
936 | + continue; |
|
937 | + } |
|
938 | + $key = array_search($group->getGID(), $restrictions); |
|
939 | + unset($restrictions[$key]); |
|
940 | + $restrictions = array_values($restrictions); |
|
941 | + if (empty($restrictions)) { |
|
942 | + $appManager->disableApp($appId); |
|
943 | + } else { |
|
944 | + $appManager->enableAppForGroups($appId, $restrictions); |
|
945 | + } |
|
946 | + } |
|
947 | + }); |
|
948 | + } |
|
949 | + |
|
950 | + private static function registerResourceCollectionHooks(): void { |
|
951 | + \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class)); |
|
952 | + } |
|
953 | + |
|
954 | + private static function registerFileReferenceEventListener(): void { |
|
955 | + \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
956 | + } |
|
957 | + |
|
958 | + private static function registerRenderReferenceEventListener() { |
|
959 | + \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
960 | + } |
|
961 | + |
|
962 | + /** |
|
963 | + * register hooks for sharing |
|
964 | + */ |
|
965 | + public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { |
|
966 | + if ($systemConfig->getValue('installed')) { |
|
967 | + |
|
968 | + $dispatcher = Server::get(IEventDispatcher::class); |
|
969 | + $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class); |
|
970 | + $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class); |
|
971 | + $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class); |
|
972 | + } |
|
973 | + } |
|
974 | + |
|
975 | + /** |
|
976 | + * Handle the request |
|
977 | + */ |
|
978 | + public static function handleRequest(): void { |
|
979 | + Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request'); |
|
980 | + $systemConfig = Server::get(\OC\SystemConfig::class); |
|
981 | + |
|
982 | + // Check if Nextcloud is installed or in maintenance (update) mode |
|
983 | + if (!$systemConfig->getValue('installed', false)) { |
|
984 | + \OC::$server->getSession()->clear(); |
|
985 | + $controller = Server::get(\OC\Core\Controller\SetupController::class); |
|
986 | + $controller->run($_POST); |
|
987 | + exit(); |
|
988 | + } |
|
989 | + |
|
990 | + $request = Server::get(IRequest::class); |
|
991 | + $request->throwDecodingExceptionIfAny(); |
|
992 | + $requestPath = $request->getRawPathInfo(); |
|
993 | + if ($requestPath === '/heartbeat') { |
|
994 | + return; |
|
995 | + } |
|
996 | + if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
997 | + self::checkMaintenanceMode($systemConfig); |
|
998 | + |
|
999 | + if (\OCP\Util::needUpgrade()) { |
|
1000 | + if (function_exists('opcache_reset')) { |
|
1001 | + opcache_reset(); |
|
1002 | + } |
|
1003 | + if (!((bool)$systemConfig->getValue('maintenance', false))) { |
|
1004 | + self::printUpgradePage($systemConfig); |
|
1005 | + exit(); |
|
1006 | + } |
|
1007 | + } |
|
1008 | + } |
|
1009 | + |
|
1010 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
1011 | + |
|
1012 | + // Always load authentication apps |
|
1013 | + $appManager->loadApps(['authentication']); |
|
1014 | + $appManager->loadApps(['extended_authentication']); |
|
1015 | + |
|
1016 | + // Load minimum set of apps |
|
1017 | + if (!\OCP\Util::needUpgrade() |
|
1018 | + && !((bool)$systemConfig->getValue('maintenance', false))) { |
|
1019 | + // For logged-in users: Load everything |
|
1020 | + if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1021 | + $appManager->loadApps(); |
|
1022 | + } else { |
|
1023 | + // For guests: Load only filesystem and logging |
|
1024 | + $appManager->loadApps(['filesystem', 'logging']); |
|
1025 | + |
|
1026 | + // Don't try to login when a client is trying to get a OAuth token. |
|
1027 | + // OAuth needs to support basic auth too, so the login is not valid |
|
1028 | + // inside Nextcloud and the Login exception would ruin it. |
|
1029 | + if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') { |
|
1030 | + try { |
|
1031 | + self::handleLogin($request); |
|
1032 | + } catch (DisabledUserException $e) { |
|
1033 | + // Disabled users would not be seen as logged in and |
|
1034 | + // trying to log them in would fail, so the login |
|
1035 | + // exception is ignored for the themed stylesheets and |
|
1036 | + // images. |
|
1037 | + if ($request->getRawPathInfo() !== '/apps/theming/theme/default.css' |
|
1038 | + && $request->getRawPathInfo() !== '/apps/theming/theme/light.css' |
|
1039 | + && $request->getRawPathInfo() !== '/apps/theming/theme/dark.css' |
|
1040 | + && $request->getRawPathInfo() !== '/apps/theming/theme/light-highcontrast.css' |
|
1041 | + && $request->getRawPathInfo() !== '/apps/theming/theme/dark-highcontrast.css' |
|
1042 | + && $request->getRawPathInfo() !== '/apps/theming/theme/opendyslexic.css' |
|
1043 | + && $request->getRawPathInfo() !== '/apps/theming/image/background' |
|
1044 | + && $request->getRawPathInfo() !== '/apps/theming/image/logo' |
|
1045 | + && $request->getRawPathInfo() !== '/apps/theming/image/logoheader' |
|
1046 | + && !str_starts_with($request->getRawPathInfo(), '/apps/theming/favicon') |
|
1047 | + && !str_starts_with($request->getRawPathInfo(), '/apps/theming/icon')) { |
|
1048 | + throw $e; |
|
1049 | + } |
|
1050 | + } |
|
1051 | + } |
|
1052 | + } |
|
1053 | + } |
|
1054 | + |
|
1055 | + if (!self::$CLI) { |
|
1056 | + try { |
|
1057 | + if (!\OCP\Util::needUpgrade()) { |
|
1058 | + $appManager->loadApps(['filesystem', 'logging']); |
|
1059 | + $appManager->loadApps(); |
|
1060 | + } |
|
1061 | + Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
1062 | + return; |
|
1063 | + } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
1064 | + //header('HTTP/1.0 404 Not Found'); |
|
1065 | + } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
1066 | + http_response_code(405); |
|
1067 | + return; |
|
1068 | + } |
|
1069 | + } |
|
1070 | + |
|
1071 | + // Handle WebDAV |
|
1072 | + if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
1073 | + // not allowed any more to prevent people |
|
1074 | + // mounting this root directly. |
|
1075 | + // Users need to mount remote.php/webdav instead. |
|
1076 | + http_response_code(405); |
|
1077 | + return; |
|
1078 | + } |
|
1079 | + |
|
1080 | + // Handle requests for JSON or XML |
|
1081 | + $acceptHeader = $request->getHeader('Accept'); |
|
1082 | + if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) { |
|
1083 | + http_response_code(404); |
|
1084 | + return; |
|
1085 | + } |
|
1086 | + |
|
1087 | + // Handle resources that can't be found |
|
1088 | + // This prevents browsers from redirecting to the default page and then |
|
1089 | + // attempting to parse HTML as CSS and similar. |
|
1090 | + $destinationHeader = $request->getHeader('Sec-Fetch-Dest'); |
|
1091 | + if (in_array($destinationHeader, ['font', 'script', 'style'])) { |
|
1092 | + http_response_code(404); |
|
1093 | + return; |
|
1094 | + } |
|
1095 | + |
|
1096 | + // Redirect to the default app or login only as an entry point |
|
1097 | + if ($requestPath === '') { |
|
1098 | + // Someone is logged in |
|
1099 | + if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1100 | + header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl()); |
|
1101 | + } else { |
|
1102 | + // Not handled and not logged in |
|
1103 | + header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm')); |
|
1104 | + } |
|
1105 | + return; |
|
1106 | + } |
|
1107 | + |
|
1108 | + try { |
|
1109 | + Server::get(\OC\Route\Router::class)->match('/error/404'); |
|
1110 | + } catch (\Exception $e) { |
|
1111 | + if (!$e instanceof MethodNotAllowedException) { |
|
1112 | + logger('core')->emergency($e->getMessage(), ['exception' => $e]); |
|
1113 | + } |
|
1114 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
1115 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
1116 | + '404', |
|
1117 | + $l->t('The page could not be found on the server.'), |
|
1118 | + 404 |
|
1119 | + ); |
|
1120 | + } |
|
1121 | + } |
|
1122 | + |
|
1123 | + /** |
|
1124 | + * Check login: apache auth, auth token, basic auth |
|
1125 | + */ |
|
1126 | + public static function handleLogin(OCP\IRequest $request): bool { |
|
1127 | + if ($request->getHeader('X-Nextcloud-Federation')) { |
|
1128 | + return false; |
|
1129 | + } |
|
1130 | + $userSession = Server::get(\OC\User\Session::class); |
|
1131 | + if (OC_User::handleApacheAuth()) { |
|
1132 | + return true; |
|
1133 | + } |
|
1134 | + if (self::tryAppAPILogin($request)) { |
|
1135 | + return true; |
|
1136 | + } |
|
1137 | + if ($userSession->tryTokenLogin($request)) { |
|
1138 | + return true; |
|
1139 | + } |
|
1140 | + if (isset($_COOKIE['nc_username']) |
|
1141 | + && isset($_COOKIE['nc_token']) |
|
1142 | + && isset($_COOKIE['nc_session_id']) |
|
1143 | + && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
1144 | + return true; |
|
1145 | + } |
|
1146 | + if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) { |
|
1147 | + return true; |
|
1148 | + } |
|
1149 | + return false; |
|
1150 | + } |
|
1151 | + |
|
1152 | + protected static function handleAuthHeaders(): void { |
|
1153 | + //copy http auth headers for apache+php-fcgid work around |
|
1154 | + if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
1155 | + $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
1156 | + } |
|
1157 | + |
|
1158 | + // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
1159 | + $vars = [ |
|
1160 | + 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
1161 | + 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
1162 | + ]; |
|
1163 | + foreach ($vars as $var) { |
|
1164 | + if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
1165 | + $credentials = explode(':', base64_decode($matches[1]), 2); |
|
1166 | + if (count($credentials) === 2) { |
|
1167 | + $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
1168 | + $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
1169 | + break; |
|
1170 | + } |
|
1171 | + } |
|
1172 | + } |
|
1173 | + } |
|
1174 | + |
|
1175 | + protected static function tryAppAPILogin(OCP\IRequest $request): bool { |
|
1176 | + if (!$request->getHeader('AUTHORIZATION-APP-API')) { |
|
1177 | + return false; |
|
1178 | + } |
|
1179 | + $appManager = Server::get(OCP\App\IAppManager::class); |
|
1180 | + if (!$appManager->isEnabledForAnyone('app_api')) { |
|
1181 | + return false; |
|
1182 | + } |
|
1183 | + try { |
|
1184 | + $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class); |
|
1185 | + return $appAPIService->validateExAppRequestToNC($request); |
|
1186 | + } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) { |
|
1187 | + return false; |
|
1188 | + } |
|
1189 | + } |
|
1190 | 1190 | } |
1191 | 1191 | |
1192 | 1192 | OC::init(); |