Passed
Push — master ( a0bf65...7f6e22 )
by John
14:18 queued 14s
created
lib/private/User/Session.php 1 patch
Indentation   +940 added lines, -940 removed lines patch added patch discarded remove patch
@@ -89,944 +89,944 @@
 block discarded – undo
89 89
  * @package OC\User
90 90
  */
91 91
 class Session implements IUserSession, Emitter {
92
-	/** @var Manager $manager */
93
-	private $manager;
94
-
95
-	/** @var ISession $session */
96
-	private $session;
97
-
98
-	/** @var ITimeFactory */
99
-	private $timeFactory;
100
-
101
-	/** @var IProvider */
102
-	private $tokenProvider;
103
-
104
-	/** @var IConfig */
105
-	private $config;
106
-
107
-	/** @var User $activeUser */
108
-	protected $activeUser;
109
-
110
-	/** @var ISecureRandom */
111
-	private $random;
112
-
113
-	/** @var ILockdownManager  */
114
-	private $lockdownManager;
115
-
116
-	private LoggerInterface $logger;
117
-	/** @var IEventDispatcher */
118
-	private $dispatcher;
119
-
120
-	public function __construct(Manager $manager,
121
-								ISession $session,
122
-								ITimeFactory $timeFactory,
123
-								?IProvider $tokenProvider,
124
-								IConfig $config,
125
-								ISecureRandom $random,
126
-								ILockdownManager $lockdownManager,
127
-								LoggerInterface $logger,
128
-								IEventDispatcher $dispatcher
129
-	) {
130
-		$this->manager = $manager;
131
-		$this->session = $session;
132
-		$this->timeFactory = $timeFactory;
133
-		$this->tokenProvider = $tokenProvider;
134
-		$this->config = $config;
135
-		$this->random = $random;
136
-		$this->lockdownManager = $lockdownManager;
137
-		$this->logger = $logger;
138
-		$this->dispatcher = $dispatcher;
139
-	}
140
-
141
-	/**
142
-	 * @param IProvider $provider
143
-	 */
144
-	public function setTokenProvider(IProvider $provider) {
145
-		$this->tokenProvider = $provider;
146
-	}
147
-
148
-	/**
149
-	 * @param string $scope
150
-	 * @param string $method
151
-	 * @param callable $callback
152
-	 */
153
-	public function listen($scope, $method, callable $callback) {
154
-		$this->manager->listen($scope, $method, $callback);
155
-	}
156
-
157
-	/**
158
-	 * @param string $scope optional
159
-	 * @param string $method optional
160
-	 * @param callable $callback optional
161
-	 */
162
-	public function removeListener($scope = null, $method = null, callable $callback = null) {
163
-		$this->manager->removeListener($scope, $method, $callback);
164
-	}
165
-
166
-	/**
167
-	 * get the manager object
168
-	 *
169
-	 * @return Manager|PublicEmitter
170
-	 */
171
-	public function getManager() {
172
-		return $this->manager;
173
-	}
174
-
175
-	/**
176
-	 * get the session object
177
-	 *
178
-	 * @return ISession
179
-	 */
180
-	public function getSession() {
181
-		return $this->session;
182
-	}
183
-
184
-	/**
185
-	 * set the session object
186
-	 *
187
-	 * @param ISession $session
188
-	 */
189
-	public function setSession(ISession $session) {
190
-		if ($this->session instanceof ISession) {
191
-			$this->session->close();
192
-		}
193
-		$this->session = $session;
194
-		$this->activeUser = null;
195
-	}
196
-
197
-	/**
198
-	 * set the currently active user
199
-	 *
200
-	 * @param IUser|null $user
201
-	 */
202
-	public function setUser($user) {
203
-		if (is_null($user)) {
204
-			$this->session->remove('user_id');
205
-		} else {
206
-			$this->session->set('user_id', $user->getUID());
207
-		}
208
-		$this->activeUser = $user;
209
-	}
210
-
211
-	/**
212
-	 * get the current active user
213
-	 *
214
-	 * @return IUser|null Current user, otherwise null
215
-	 */
216
-	public function getUser() {
217
-		// FIXME: This is a quick'n dirty work-around for the incognito mode as
218
-		// described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
219
-		if (OC_User::isIncognitoMode()) {
220
-			return null;
221
-		}
222
-		if (is_null($this->activeUser)) {
223
-			$uid = $this->session->get('user_id');
224
-			if (is_null($uid)) {
225
-				return null;
226
-			}
227
-			$this->activeUser = $this->manager->get($uid);
228
-			if (is_null($this->activeUser)) {
229
-				return null;
230
-			}
231
-			$this->validateSession();
232
-		}
233
-		return $this->activeUser;
234
-	}
235
-
236
-	/**
237
-	 * Validate whether the current session is valid
238
-	 *
239
-	 * - For token-authenticated clients, the token validity is checked
240
-	 * - For browsers, the session token validity is checked
241
-	 */
242
-	protected function validateSession() {
243
-		$token = null;
244
-		$appPassword = $this->session->get('app_password');
245
-
246
-		if (is_null($appPassword)) {
247
-			try {
248
-				$token = $this->session->getId();
249
-			} catch (SessionNotAvailableException $ex) {
250
-				return;
251
-			}
252
-		} else {
253
-			$token = $appPassword;
254
-		}
255
-
256
-		if (!$this->validateToken($token)) {
257
-			// Session was invalidated
258
-			$this->logout();
259
-		}
260
-	}
261
-
262
-	/**
263
-	 * Checks whether the user is logged in
264
-	 *
265
-	 * @return bool if logged in
266
-	 */
267
-	public function isLoggedIn() {
268
-		$user = $this->getUser();
269
-		if (is_null($user)) {
270
-			return false;
271
-		}
272
-
273
-		return $user->isEnabled();
274
-	}
275
-
276
-	/**
277
-	 * set the login name
278
-	 *
279
-	 * @param string|null $loginName for the logged in user
280
-	 */
281
-	public function setLoginName($loginName) {
282
-		if (is_null($loginName)) {
283
-			$this->session->remove('loginname');
284
-		} else {
285
-			$this->session->set('loginname', $loginName);
286
-		}
287
-	}
288
-
289
-	/**
290
-	 * Get the login name of the current user
291
-	 *
292
-	 * @return ?string
293
-	 */
294
-	public function getLoginName() {
295
-		if ($this->activeUser) {
296
-			return $this->session->get('loginname');
297
-		}
298
-
299
-		$uid = $this->session->get('user_id');
300
-		if ($uid) {
301
-			$this->activeUser = $this->manager->get($uid);
302
-			return $this->session->get('loginname');
303
-		}
304
-
305
-		return null;
306
-	}
307
-
308
-	/**
309
-	 * @return null|string
310
-	 */
311
-	public function getImpersonatingUserID(): ?string {
312
-		return $this->session->get('oldUserId');
313
-	}
314
-
315
-	public function setImpersonatingUserID(bool $useCurrentUser = true): void {
316
-		if ($useCurrentUser === false) {
317
-			$this->session->remove('oldUserId');
318
-			return;
319
-		}
320
-
321
-		$currentUser = $this->getUser();
322
-
323
-		if ($currentUser === null) {
324
-			throw new \OC\User\NoUserException();
325
-		}
326
-		$this->session->set('oldUserId', $currentUser->getUID());
327
-	}
328
-	/**
329
-	 * set the token id
330
-	 *
331
-	 * @param int|null $token that was used to log in
332
-	 */
333
-	protected function setToken($token) {
334
-		if ($token === null) {
335
-			$this->session->remove('token-id');
336
-		} else {
337
-			$this->session->set('token-id', $token);
338
-		}
339
-	}
340
-
341
-	/**
342
-	 * try to log in with the provided credentials
343
-	 *
344
-	 * @param string $uid
345
-	 * @param string $password
346
-	 * @return boolean|null
347
-	 * @throws LoginException
348
-	 */
349
-	public function login($uid, $password) {
350
-		$this->session->regenerateId();
351
-		if ($this->validateToken($password, $uid)) {
352
-			return $this->loginWithToken($password);
353
-		}
354
-		return $this->loginWithPassword($uid, $password);
355
-	}
356
-
357
-	/**
358
-	 * @param IUser $user
359
-	 * @param array $loginDetails
360
-	 * @param bool $regenerateSessionId
361
-	 * @return true returns true if login successful or an exception otherwise
362
-	 * @throws LoginException
363
-	 */
364
-	public function completeLogin(IUser $user, array $loginDetails, $regenerateSessionId = true) {
365
-		if (!$user->isEnabled()) {
366
-			// disabled users can not log in
367
-			// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
368
-			$message = \OC::$server->getL10N('lib')->t('User disabled');
369
-			throw new LoginException($message);
370
-		}
371
-
372
-		if ($regenerateSessionId) {
373
-			$this->session->regenerateId();
374
-			$this->session->remove(Auth::DAV_AUTHENTICATED);
375
-		}
376
-
377
-		$this->setUser($user);
378
-		$this->setLoginName($loginDetails['loginName']);
379
-
380
-		$isToken = isset($loginDetails['token']) && $loginDetails['token'] instanceof IToken;
381
-		if ($isToken) {
382
-			$this->setToken($loginDetails['token']->getId());
383
-			$this->lockdownManager->setToken($loginDetails['token']);
384
-			$firstTimeLogin = false;
385
-		} else {
386
-			$this->setToken(null);
387
-			$firstTimeLogin = $user->updateLastLoginTimestamp();
388
-		}
389
-
390
-		$this->dispatcher->dispatchTyped(new PostLoginEvent(
391
-			$user,
392
-			$loginDetails['loginName'],
393
-			$loginDetails['password'],
394
-			$isToken
395
-		));
396
-		$this->manager->emit('\OC\User', 'postLogin', [
397
-			$user,
398
-			$loginDetails['loginName'],
399
-			$loginDetails['password'],
400
-			$isToken,
401
-		]);
402
-		if ($this->isLoggedIn()) {
403
-			$this->prepareUserLogin($firstTimeLogin, $regenerateSessionId);
404
-			return true;
405
-		}
406
-
407
-		$message = \OC::$server->getL10N('lib')->t('Login canceled by app');
408
-		throw new LoginException($message);
409
-	}
410
-
411
-	/**
412
-	 * Tries to log in a client
413
-	 *
414
-	 * Checks token auth enforced
415
-	 * Checks 2FA enabled
416
-	 *
417
-	 * @param string $user
418
-	 * @param string $password
419
-	 * @param IRequest $request
420
-	 * @param OC\Security\Bruteforce\Throttler $throttler
421
-	 * @throws LoginException
422
-	 * @throws PasswordLoginForbiddenException
423
-	 * @return boolean
424
-	 */
425
-	public function logClientIn($user,
426
-								$password,
427
-								IRequest $request,
428
-								OC\Security\Bruteforce\Throttler $throttler) {
429
-		$currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
430
-
431
-		if ($this->manager instanceof PublicEmitter) {
432
-			$this->manager->emit('\OC\User', 'preLogin', [$user, $password]);
433
-		}
434
-
435
-		try {
436
-			$isTokenPassword = $this->isTokenPassword($password);
437
-		} catch (ExpiredTokenException $e) {
438
-			// Just return on an expired token no need to check further or record a failed login
439
-			return false;
440
-		}
441
-
442
-		if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
443
-			throw new PasswordLoginForbiddenException();
444
-		}
445
-		if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
446
-			throw new PasswordLoginForbiddenException();
447
-		}
448
-
449
-		// Try to login with this username and password
450
-		if (!$this->login($user, $password)) {
451
-			// Failed, maybe the user used their email address
452
-			if (!filter_var($user, FILTER_VALIDATE_EMAIL)) {
453
-				return false;
454
-			}
455
-			$users = $this->manager->getByEmail($user);
456
-			if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) {
457
-				$this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']);
458
-
459
-				$throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]);
460
-
461
-				$this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user));
462
-
463
-				if ($currentDelay === 0) {
464
-					$throttler->sleepDelay($request->getRemoteAddress(), 'login');
465
-				}
466
-				return false;
467
-			}
468
-		}
469
-
470
-		if ($isTokenPassword) {
471
-			$this->session->set('app_password', $password);
472
-		} elseif ($this->supportsCookies($request)) {
473
-			// Password login, but cookies supported -> create (browser) session token
474
-			$this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
475
-		}
476
-
477
-		return true;
478
-	}
479
-
480
-	protected function supportsCookies(IRequest $request) {
481
-		if (!is_null($request->getCookie('cookie_test'))) {
482
-			return true;
483
-		}
484
-		setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600);
485
-		return false;
486
-	}
487
-
488
-	private function isTokenAuthEnforced() {
489
-		return $this->config->getSystemValue('token_auth_enforced', false);
490
-	}
491
-
492
-	protected function isTwoFactorEnforced($username) {
493
-		Util::emitHook(
494
-			'\OCA\Files_Sharing\API\Server2Server',
495
-			'preLoginNameUsedAsUserName',
496
-			['uid' => &$username]
497
-		);
498
-		$user = $this->manager->get($username);
499
-		if (is_null($user)) {
500
-			$users = $this->manager->getByEmail($username);
501
-			if (empty($users)) {
502
-				return false;
503
-			}
504
-			if (count($users) !== 1) {
505
-				return true;
506
-			}
507
-			$user = $users[0];
508
-		}
509
-		// DI not possible due to cyclic dependencies :'-/
510
-		return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
511
-	}
512
-
513
-	/**
514
-	 * Check if the given 'password' is actually a device token
515
-	 *
516
-	 * @param string $password
517
-	 * @return boolean
518
-	 * @throws ExpiredTokenException
519
-	 */
520
-	public function isTokenPassword($password) {
521
-		try {
522
-			$this->tokenProvider->getToken($password);
523
-			return true;
524
-		} catch (ExpiredTokenException $e) {
525
-			throw $e;
526
-		} catch (InvalidTokenException $ex) {
527
-			$this->logger->debug('Token is not valid: ' . $ex->getMessage(), [
528
-				'exception' => $ex,
529
-			]);
530
-			return false;
531
-		}
532
-	}
533
-
534
-	protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) {
535
-		if ($refreshCsrfToken) {
536
-			// TODO: mock/inject/use non-static
537
-			// Refresh the token
538
-			\OC::$server->getCsrfTokenManager()->refreshToken();
539
-		}
540
-
541
-		if ($firstTimeLogin) {
542
-			//we need to pass the user name, which may differ from login name
543
-			$user = $this->getUser()->getUID();
544
-			OC_Util::setupFS($user);
545
-
546
-			// TODO: lock necessary?
547
-			//trigger creation of user home and /files folder
548
-			$userFolder = \OC::$server->getUserFolder($user);
549
-
550
-			try {
551
-				// copy skeleton
552
-				\OC_Util::copySkeleton($user, $userFolder);
553
-			} catch (NotPermittedException $ex) {
554
-				// read only uses
555
-			}
556
-
557
-			// trigger any other initialization
558
-			\OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
559
-		}
560
-	}
561
-
562
-	/**
563
-	 * Tries to login the user with HTTP Basic Authentication
564
-	 *
565
-	 * @todo do not allow basic auth if the user is 2FA enforced
566
-	 * @param IRequest $request
567
-	 * @param OC\Security\Bruteforce\Throttler $throttler
568
-	 * @return boolean if the login was successful
569
-	 */
570
-	public function tryBasicAuthLogin(IRequest $request,
571
-									  OC\Security\Bruteforce\Throttler $throttler) {
572
-		if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
573
-			try {
574
-				if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
575
-					/**
576
-					 * Add DAV authenticated. This should in an ideal world not be
577
-					 * necessary but the iOS App reads cookies from anywhere instead
578
-					 * only the DAV endpoint.
579
-					 * This makes sure that the cookies will be valid for the whole scope
580
-					 * @see https://github.com/owncloud/core/issues/22893
581
-					 */
582
-					$this->session->set(
583
-						Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
584
-					);
585
-
586
-					// Set the last-password-confirm session to make the sudo mode work
587
-					$this->session->set('last-password-confirm', $this->timeFactory->getTime());
588
-
589
-					return true;
590
-				}
591
-				// If credentials were provided, they need to be valid, otherwise we do boom
592
-				throw new LoginException();
593
-			} catch (PasswordLoginForbiddenException $ex) {
594
-				// Nothing to do
595
-			}
596
-		}
597
-		return false;
598
-	}
599
-
600
-	/**
601
-	 * Log an user in via login name and password
602
-	 *
603
-	 * @param string $uid
604
-	 * @param string $password
605
-	 * @return boolean
606
-	 * @throws LoginException if an app canceld the login process or the user is not enabled
607
-	 */
608
-	private function loginWithPassword($uid, $password) {
609
-		$user = $this->manager->checkPasswordNoLogging($uid, $password);
610
-		if ($user === false) {
611
-			// Password check failed
612
-			return false;
613
-		}
614
-
615
-		return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false);
616
-	}
617
-
618
-	/**
619
-	 * Log an user in with a given token (id)
620
-	 *
621
-	 * @param string $token
622
-	 * @return boolean
623
-	 * @throws LoginException if an app canceled the login process or the user is not enabled
624
-	 */
625
-	private function loginWithToken($token) {
626
-		try {
627
-			$dbToken = $this->tokenProvider->getToken($token);
628
-		} catch (InvalidTokenException $ex) {
629
-			return false;
630
-		}
631
-		$uid = $dbToken->getUID();
632
-
633
-		// When logging in with token, the password must be decrypted first before passing to login hook
634
-		$password = '';
635
-		try {
636
-			$password = $this->tokenProvider->getPassword($dbToken, $token);
637
-		} catch (PasswordlessTokenException $ex) {
638
-			// Ignore and use empty string instead
639
-		}
640
-
641
-		$this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]);
642
-
643
-		$user = $this->manager->get($uid);
644
-		if (is_null($user)) {
645
-			// user does not exist
646
-			return false;
647
-		}
648
-
649
-		return $this->completeLogin(
650
-			$user,
651
-			[
652
-				'loginName' => $dbToken->getLoginName(),
653
-				'password' => $password,
654
-				'token' => $dbToken
655
-			],
656
-			false);
657
-	}
658
-
659
-	/**
660
-	 * Create a new session token for the given user credentials
661
-	 *
662
-	 * @param IRequest $request
663
-	 * @param string $uid user UID
664
-	 * @param string $loginName login name
665
-	 * @param string $password
666
-	 * @param int $remember
667
-	 * @return boolean
668
-	 */
669
-	public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
670
-		if (is_null($this->manager->get($uid))) {
671
-			// User does not exist
672
-			return false;
673
-		}
674
-		$name = isset($request->server['HTTP_USER_AGENT']) ? mb_convert_encoding($request->server['HTTP_USER_AGENT'], 'UTF-8', 'ISO-8859-1') : 'unknown browser';
675
-		try {
676
-			$sessionId = $this->session->getId();
677
-			$pwd = $this->getPassword($password);
678
-			// Make sure the current sessionId has no leftover tokens
679
-			$this->tokenProvider->invalidateToken($sessionId);
680
-			$this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
681
-			return true;
682
-		} catch (SessionNotAvailableException $ex) {
683
-			// This can happen with OCC, where a memory session is used
684
-			// if a memory session is used, we shouldn't create a session token anyway
685
-			return false;
686
-		}
687
-	}
688
-
689
-	/**
690
-	 * Checks if the given password is a token.
691
-	 * If yes, the password is extracted from the token.
692
-	 * If no, the same password is returned.
693
-	 *
694
-	 * @param string $password either the login password or a device token
695
-	 * @return string|null the password or null if none was set in the token
696
-	 */
697
-	private function getPassword($password) {
698
-		if (is_null($password)) {
699
-			// This is surely no token ;-)
700
-			return null;
701
-		}
702
-		try {
703
-			$token = $this->tokenProvider->getToken($password);
704
-			try {
705
-				return $this->tokenProvider->getPassword($token, $password);
706
-			} catch (PasswordlessTokenException $ex) {
707
-				return null;
708
-			}
709
-		} catch (InvalidTokenException $ex) {
710
-			return $password;
711
-		}
712
-	}
713
-
714
-	/**
715
-	 * @param IToken $dbToken
716
-	 * @param string $token
717
-	 * @return boolean
718
-	 */
719
-	private function checkTokenCredentials(IToken $dbToken, $token) {
720
-		// Check whether login credentials are still valid and the user was not disabled
721
-		// This check is performed each 5 minutes
722
-		$lastCheck = $dbToken->getLastCheck() ? : 0;
723
-		$now = $this->timeFactory->getTime();
724
-		if ($lastCheck > ($now - 60 * 5)) {
725
-			// Checked performed recently, nothing to do now
726
-			return true;
727
-		}
728
-
729
-		try {
730
-			$pwd = $this->tokenProvider->getPassword($dbToken, $token);
731
-		} catch (InvalidTokenException $ex) {
732
-			// An invalid token password was used -> log user out
733
-			return false;
734
-		} catch (PasswordlessTokenException $ex) {
735
-			// Token has no password
736
-
737
-			if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
738
-				$this->tokenProvider->invalidateToken($token);
739
-				return false;
740
-			}
741
-
742
-			$dbToken->setLastCheck($now);
743
-			$this->tokenProvider->updateToken($dbToken);
744
-			return true;
745
-		}
746
-
747
-		// Invalidate token if the user is no longer active
748
-		if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
749
-			$this->tokenProvider->invalidateToken($token);
750
-			return false;
751
-		}
752
-
753
-		// If the token password is no longer valid mark it as such
754
-		if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) {
755
-			$this->tokenProvider->markPasswordInvalid($dbToken, $token);
756
-			// User is logged out
757
-			return false;
758
-		}
759
-
760
-		$dbToken->setLastCheck($now);
761
-		$this->tokenProvider->updateToken($dbToken);
762
-		return true;
763
-	}
764
-
765
-	/**
766
-	 * Check if the given token exists and performs password/user-enabled checks
767
-	 *
768
-	 * Invalidates the token if checks fail
769
-	 *
770
-	 * @param string $token
771
-	 * @param string $user login name
772
-	 * @return boolean
773
-	 */
774
-	private function validateToken($token, $user = null) {
775
-		try {
776
-			$dbToken = $this->tokenProvider->getToken($token);
777
-		} catch (InvalidTokenException $ex) {
778
-			return false;
779
-		}
780
-
781
-		// Check if login names match
782
-		if (!is_null($user) && $dbToken->getLoginName() !== $user) {
783
-			// TODO: this makes it impossible to use different login names on browser and client
784
-			// e.g. login by e-mail '[email protected]' on browser for generating the token will not
785
-			//      allow to use the client token with the login name 'user'.
786
-			$this->logger->error('App token login name does not match', [
787
-				'tokenLoginName' => $dbToken->getLoginName(),
788
-				'sessionLoginName' => $user,
789
-			]);
790
-
791
-			return false;
792
-		}
793
-
794
-		if (!$this->checkTokenCredentials($dbToken, $token)) {
795
-			return false;
796
-		}
797
-
798
-		// Update token scope
799
-		$this->lockdownManager->setToken($dbToken);
800
-
801
-		$this->tokenProvider->updateTokenActivity($dbToken);
802
-
803
-		return true;
804
-	}
805
-
806
-	/**
807
-	 * Tries to login the user with auth token header
808
-	 *
809
-	 * @param IRequest $request
810
-	 * @todo check remember me cookie
811
-	 * @return boolean
812
-	 */
813
-	public function tryTokenLogin(IRequest $request) {
814
-		$authHeader = $request->getHeader('Authorization');
815
-		if (strpos($authHeader, 'Bearer ') === 0) {
816
-			$token = substr($authHeader, 7);
817
-		} else {
818
-			// No auth header, let's try session id
819
-			try {
820
-				$token = $this->session->getId();
821
-			} catch (SessionNotAvailableException $ex) {
822
-				return false;
823
-			}
824
-		}
825
-
826
-		if (!$this->loginWithToken($token)) {
827
-			return false;
828
-		}
829
-		if (!$this->validateToken($token)) {
830
-			return false;
831
-		}
832
-
833
-		try {
834
-			$dbToken = $this->tokenProvider->getToken($token);
835
-		} catch (InvalidTokenException $e) {
836
-			// Can't really happen but better save than sorry
837
-			return true;
838
-		}
839
-
840
-		// Remember me tokens are not app_passwords
841
-		if ($dbToken->getRemember() === IToken::DO_NOT_REMEMBER) {
842
-			// Set the session variable so we know this is an app password
843
-			$this->session->set('app_password', $token);
844
-		}
845
-
846
-		return true;
847
-	}
848
-
849
-	/**
850
-	 * perform login using the magic cookie (remember login)
851
-	 *
852
-	 * @param string $uid the username
853
-	 * @param string $currentToken
854
-	 * @param string $oldSessionId
855
-	 * @return bool
856
-	 */
857
-	public function loginWithCookie($uid, $currentToken, $oldSessionId) {
858
-		$this->session->regenerateId();
859
-		$this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]);
860
-		$user = $this->manager->get($uid);
861
-		if (is_null($user)) {
862
-			// user does not exist
863
-			return false;
864
-		}
865
-
866
-		// get stored tokens
867
-		$tokens = $this->config->getUserKeys($uid, 'login_token');
868
-		// test cookies token against stored tokens
869
-		if (!in_array($currentToken, $tokens, true)) {
870
-			$this->logger->info('Tried to log in {uid} but could not verify token', [
871
-				'app' => 'core',
872
-				'uid' => $uid,
873
-			]);
874
-			return false;
875
-		}
876
-		// replace successfully used token with a new one
877
-		$this->config->deleteUserValue($uid, 'login_token', $currentToken);
878
-		$newToken = $this->random->generate(32);
879
-		$this->config->setUserValue($uid, 'login_token', $newToken, (string)$this->timeFactory->getTime());
880
-
881
-		try {
882
-			$sessionId = $this->session->getId();
883
-			$token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
884
-		} catch (SessionNotAvailableException $ex) {
885
-			$this->logger->warning('Could not renew session token for {uid} because the session is unavailable', [
886
-				'app' => 'core',
887
-				'uid' => $uid,
888
-			]);
889
-			return false;
890
-		} catch (InvalidTokenException $ex) {
891
-			$this->logger->warning('Renewing session token failed', ['app' => 'core']);
892
-			return false;
893
-		}
894
-
895
-		$this->setMagicInCookie($user->getUID(), $newToken);
896
-
897
-		//login
898
-		$this->setUser($user);
899
-		$this->setLoginName($token->getLoginName());
900
-		$this->setToken($token->getId());
901
-		$this->lockdownManager->setToken($token);
902
-		$user->updateLastLoginTimestamp();
903
-		$password = null;
904
-		try {
905
-			$password = $this->tokenProvider->getPassword($token, $sessionId);
906
-		} catch (PasswordlessTokenException $ex) {
907
-			// Ignore
908
-		}
909
-		$this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]);
910
-		return true;
911
-	}
912
-
913
-	/**
914
-	 * @param IUser $user
915
-	 */
916
-	public function createRememberMeToken(IUser $user) {
917
-		$token = $this->random->generate(32);
918
-		$this->config->setUserValue($user->getUID(), 'login_token', $token, (string)$this->timeFactory->getTime());
919
-		$this->setMagicInCookie($user->getUID(), $token);
920
-	}
921
-
922
-	/**
923
-	 * logout the user from the session
924
-	 */
925
-	public function logout() {
926
-		$user = $this->getUser();
927
-		$this->manager->emit('\OC\User', 'logout', [$user]);
928
-		if ($user !== null) {
929
-			try {
930
-				$this->tokenProvider->invalidateToken($this->session->getId());
931
-			} catch (SessionNotAvailableException $ex) {
932
-			}
933
-		}
934
-		$this->setUser(null);
935
-		$this->setLoginName(null);
936
-		$this->setToken(null);
937
-		$this->unsetMagicInCookie();
938
-		$this->session->clear();
939
-		$this->manager->emit('\OC\User', 'postLogout', [$user]);
940
-	}
941
-
942
-	/**
943
-	 * Set cookie value to use in next page load
944
-	 *
945
-	 * @param string $username username to be set
946
-	 * @param string $token
947
-	 */
948
-	public function setMagicInCookie($username, $token) {
949
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
950
-		$webRoot = \OC::$WEBROOT;
951
-		if ($webRoot === '') {
952
-			$webRoot = '/';
953
-		}
954
-
955
-		$maxAge = $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
956
-		\OC\Http\CookieHelper::setCookie(
957
-			'nc_username',
958
-			$username,
959
-			$maxAge,
960
-			$webRoot,
961
-			'',
962
-			$secureCookie,
963
-			true,
964
-			\OC\Http\CookieHelper::SAMESITE_LAX
965
-		);
966
-		\OC\Http\CookieHelper::setCookie(
967
-			'nc_token',
968
-			$token,
969
-			$maxAge,
970
-			$webRoot,
971
-			'',
972
-			$secureCookie,
973
-			true,
974
-			\OC\Http\CookieHelper::SAMESITE_LAX
975
-		);
976
-		try {
977
-			\OC\Http\CookieHelper::setCookie(
978
-				'nc_session_id',
979
-				$this->session->getId(),
980
-				$maxAge,
981
-				$webRoot,
982
-				'',
983
-				$secureCookie,
984
-				true,
985
-				\OC\Http\CookieHelper::SAMESITE_LAX
986
-			);
987
-		} catch (SessionNotAvailableException $ex) {
988
-			// ignore
989
-		}
990
-	}
991
-
992
-	/**
993
-	 * Remove cookie for "remember username"
994
-	 */
995
-	public function unsetMagicInCookie() {
996
-		//TODO: DI for cookies and IRequest
997
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
998
-
999
-		unset($_COOKIE['nc_username']); //TODO: DI
1000
-		unset($_COOKIE['nc_token']);
1001
-		unset($_COOKIE['nc_session_id']);
1002
-		setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1003
-		setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1004
-		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1005
-		// old cookies might be stored under /webroot/ instead of /webroot
1006
-		// and Firefox doesn't like it!
1007
-		setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1008
-		setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1009
-		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1010
-	}
1011
-
1012
-	/**
1013
-	 * Update password of the browser session token if there is one
1014
-	 *
1015
-	 * @param string $password
1016
-	 */
1017
-	public function updateSessionTokenPassword($password) {
1018
-		try {
1019
-			$sessionId = $this->session->getId();
1020
-			$token = $this->tokenProvider->getToken($sessionId);
1021
-			$this->tokenProvider->setPassword($token, $sessionId, $password);
1022
-		} catch (SessionNotAvailableException $ex) {
1023
-			// Nothing to do
1024
-		} catch (InvalidTokenException $ex) {
1025
-			// Nothing to do
1026
-		}
1027
-	}
1028
-
1029
-	public function updateTokens(string $uid, string $password) {
1030
-		$this->tokenProvider->updatePasswords($uid, $password);
1031
-	}
92
+    /** @var Manager $manager */
93
+    private $manager;
94
+
95
+    /** @var ISession $session */
96
+    private $session;
97
+
98
+    /** @var ITimeFactory */
99
+    private $timeFactory;
100
+
101
+    /** @var IProvider */
102
+    private $tokenProvider;
103
+
104
+    /** @var IConfig */
105
+    private $config;
106
+
107
+    /** @var User $activeUser */
108
+    protected $activeUser;
109
+
110
+    /** @var ISecureRandom */
111
+    private $random;
112
+
113
+    /** @var ILockdownManager  */
114
+    private $lockdownManager;
115
+
116
+    private LoggerInterface $logger;
117
+    /** @var IEventDispatcher */
118
+    private $dispatcher;
119
+
120
+    public function __construct(Manager $manager,
121
+                                ISession $session,
122
+                                ITimeFactory $timeFactory,
123
+                                ?IProvider $tokenProvider,
124
+                                IConfig $config,
125
+                                ISecureRandom $random,
126
+                                ILockdownManager $lockdownManager,
127
+                                LoggerInterface $logger,
128
+                                IEventDispatcher $dispatcher
129
+    ) {
130
+        $this->manager = $manager;
131
+        $this->session = $session;
132
+        $this->timeFactory = $timeFactory;
133
+        $this->tokenProvider = $tokenProvider;
134
+        $this->config = $config;
135
+        $this->random = $random;
136
+        $this->lockdownManager = $lockdownManager;
137
+        $this->logger = $logger;
138
+        $this->dispatcher = $dispatcher;
139
+    }
140
+
141
+    /**
142
+     * @param IProvider $provider
143
+     */
144
+    public function setTokenProvider(IProvider $provider) {
145
+        $this->tokenProvider = $provider;
146
+    }
147
+
148
+    /**
149
+     * @param string $scope
150
+     * @param string $method
151
+     * @param callable $callback
152
+     */
153
+    public function listen($scope, $method, callable $callback) {
154
+        $this->manager->listen($scope, $method, $callback);
155
+    }
156
+
157
+    /**
158
+     * @param string $scope optional
159
+     * @param string $method optional
160
+     * @param callable $callback optional
161
+     */
162
+    public function removeListener($scope = null, $method = null, callable $callback = null) {
163
+        $this->manager->removeListener($scope, $method, $callback);
164
+    }
165
+
166
+    /**
167
+     * get the manager object
168
+     *
169
+     * @return Manager|PublicEmitter
170
+     */
171
+    public function getManager() {
172
+        return $this->manager;
173
+    }
174
+
175
+    /**
176
+     * get the session object
177
+     *
178
+     * @return ISession
179
+     */
180
+    public function getSession() {
181
+        return $this->session;
182
+    }
183
+
184
+    /**
185
+     * set the session object
186
+     *
187
+     * @param ISession $session
188
+     */
189
+    public function setSession(ISession $session) {
190
+        if ($this->session instanceof ISession) {
191
+            $this->session->close();
192
+        }
193
+        $this->session = $session;
194
+        $this->activeUser = null;
195
+    }
196
+
197
+    /**
198
+     * set the currently active user
199
+     *
200
+     * @param IUser|null $user
201
+     */
202
+    public function setUser($user) {
203
+        if (is_null($user)) {
204
+            $this->session->remove('user_id');
205
+        } else {
206
+            $this->session->set('user_id', $user->getUID());
207
+        }
208
+        $this->activeUser = $user;
209
+    }
210
+
211
+    /**
212
+     * get the current active user
213
+     *
214
+     * @return IUser|null Current user, otherwise null
215
+     */
216
+    public function getUser() {
217
+        // FIXME: This is a quick'n dirty work-around for the incognito mode as
218
+        // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
219
+        if (OC_User::isIncognitoMode()) {
220
+            return null;
221
+        }
222
+        if (is_null($this->activeUser)) {
223
+            $uid = $this->session->get('user_id');
224
+            if (is_null($uid)) {
225
+                return null;
226
+            }
227
+            $this->activeUser = $this->manager->get($uid);
228
+            if (is_null($this->activeUser)) {
229
+                return null;
230
+            }
231
+            $this->validateSession();
232
+        }
233
+        return $this->activeUser;
234
+    }
235
+
236
+    /**
237
+     * Validate whether the current session is valid
238
+     *
239
+     * - For token-authenticated clients, the token validity is checked
240
+     * - For browsers, the session token validity is checked
241
+     */
242
+    protected function validateSession() {
243
+        $token = null;
244
+        $appPassword = $this->session->get('app_password');
245
+
246
+        if (is_null($appPassword)) {
247
+            try {
248
+                $token = $this->session->getId();
249
+            } catch (SessionNotAvailableException $ex) {
250
+                return;
251
+            }
252
+        } else {
253
+            $token = $appPassword;
254
+        }
255
+
256
+        if (!$this->validateToken($token)) {
257
+            // Session was invalidated
258
+            $this->logout();
259
+        }
260
+    }
261
+
262
+    /**
263
+     * Checks whether the user is logged in
264
+     *
265
+     * @return bool if logged in
266
+     */
267
+    public function isLoggedIn() {
268
+        $user = $this->getUser();
269
+        if (is_null($user)) {
270
+            return false;
271
+        }
272
+
273
+        return $user->isEnabled();
274
+    }
275
+
276
+    /**
277
+     * set the login name
278
+     *
279
+     * @param string|null $loginName for the logged in user
280
+     */
281
+    public function setLoginName($loginName) {
282
+        if (is_null($loginName)) {
283
+            $this->session->remove('loginname');
284
+        } else {
285
+            $this->session->set('loginname', $loginName);
286
+        }
287
+    }
288
+
289
+    /**
290
+     * Get the login name of the current user
291
+     *
292
+     * @return ?string
293
+     */
294
+    public function getLoginName() {
295
+        if ($this->activeUser) {
296
+            return $this->session->get('loginname');
297
+        }
298
+
299
+        $uid = $this->session->get('user_id');
300
+        if ($uid) {
301
+            $this->activeUser = $this->manager->get($uid);
302
+            return $this->session->get('loginname');
303
+        }
304
+
305
+        return null;
306
+    }
307
+
308
+    /**
309
+     * @return null|string
310
+     */
311
+    public function getImpersonatingUserID(): ?string {
312
+        return $this->session->get('oldUserId');
313
+    }
314
+
315
+    public function setImpersonatingUserID(bool $useCurrentUser = true): void {
316
+        if ($useCurrentUser === false) {
317
+            $this->session->remove('oldUserId');
318
+            return;
319
+        }
320
+
321
+        $currentUser = $this->getUser();
322
+
323
+        if ($currentUser === null) {
324
+            throw new \OC\User\NoUserException();
325
+        }
326
+        $this->session->set('oldUserId', $currentUser->getUID());
327
+    }
328
+    /**
329
+     * set the token id
330
+     *
331
+     * @param int|null $token that was used to log in
332
+     */
333
+    protected function setToken($token) {
334
+        if ($token === null) {
335
+            $this->session->remove('token-id');
336
+        } else {
337
+            $this->session->set('token-id', $token);
338
+        }
339
+    }
340
+
341
+    /**
342
+     * try to log in with the provided credentials
343
+     *
344
+     * @param string $uid
345
+     * @param string $password
346
+     * @return boolean|null
347
+     * @throws LoginException
348
+     */
349
+    public function login($uid, $password) {
350
+        $this->session->regenerateId();
351
+        if ($this->validateToken($password, $uid)) {
352
+            return $this->loginWithToken($password);
353
+        }
354
+        return $this->loginWithPassword($uid, $password);
355
+    }
356
+
357
+    /**
358
+     * @param IUser $user
359
+     * @param array $loginDetails
360
+     * @param bool $regenerateSessionId
361
+     * @return true returns true if login successful or an exception otherwise
362
+     * @throws LoginException
363
+     */
364
+    public function completeLogin(IUser $user, array $loginDetails, $regenerateSessionId = true) {
365
+        if (!$user->isEnabled()) {
366
+            // disabled users can not log in
367
+            // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
368
+            $message = \OC::$server->getL10N('lib')->t('User disabled');
369
+            throw new LoginException($message);
370
+        }
371
+
372
+        if ($regenerateSessionId) {
373
+            $this->session->regenerateId();
374
+            $this->session->remove(Auth::DAV_AUTHENTICATED);
375
+        }
376
+
377
+        $this->setUser($user);
378
+        $this->setLoginName($loginDetails['loginName']);
379
+
380
+        $isToken = isset($loginDetails['token']) && $loginDetails['token'] instanceof IToken;
381
+        if ($isToken) {
382
+            $this->setToken($loginDetails['token']->getId());
383
+            $this->lockdownManager->setToken($loginDetails['token']);
384
+            $firstTimeLogin = false;
385
+        } else {
386
+            $this->setToken(null);
387
+            $firstTimeLogin = $user->updateLastLoginTimestamp();
388
+        }
389
+
390
+        $this->dispatcher->dispatchTyped(new PostLoginEvent(
391
+            $user,
392
+            $loginDetails['loginName'],
393
+            $loginDetails['password'],
394
+            $isToken
395
+        ));
396
+        $this->manager->emit('\OC\User', 'postLogin', [
397
+            $user,
398
+            $loginDetails['loginName'],
399
+            $loginDetails['password'],
400
+            $isToken,
401
+        ]);
402
+        if ($this->isLoggedIn()) {
403
+            $this->prepareUserLogin($firstTimeLogin, $regenerateSessionId);
404
+            return true;
405
+        }
406
+
407
+        $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
408
+        throw new LoginException($message);
409
+    }
410
+
411
+    /**
412
+     * Tries to log in a client
413
+     *
414
+     * Checks token auth enforced
415
+     * Checks 2FA enabled
416
+     *
417
+     * @param string $user
418
+     * @param string $password
419
+     * @param IRequest $request
420
+     * @param OC\Security\Bruteforce\Throttler $throttler
421
+     * @throws LoginException
422
+     * @throws PasswordLoginForbiddenException
423
+     * @return boolean
424
+     */
425
+    public function logClientIn($user,
426
+                                $password,
427
+                                IRequest $request,
428
+                                OC\Security\Bruteforce\Throttler $throttler) {
429
+        $currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
430
+
431
+        if ($this->manager instanceof PublicEmitter) {
432
+            $this->manager->emit('\OC\User', 'preLogin', [$user, $password]);
433
+        }
434
+
435
+        try {
436
+            $isTokenPassword = $this->isTokenPassword($password);
437
+        } catch (ExpiredTokenException $e) {
438
+            // Just return on an expired token no need to check further or record a failed login
439
+            return false;
440
+        }
441
+
442
+        if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
443
+            throw new PasswordLoginForbiddenException();
444
+        }
445
+        if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
446
+            throw new PasswordLoginForbiddenException();
447
+        }
448
+
449
+        // Try to login with this username and password
450
+        if (!$this->login($user, $password)) {
451
+            // Failed, maybe the user used their email address
452
+            if (!filter_var($user, FILTER_VALIDATE_EMAIL)) {
453
+                return false;
454
+            }
455
+            $users = $this->manager->getByEmail($user);
456
+            if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) {
457
+                $this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']);
458
+
459
+                $throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]);
460
+
461
+                $this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user));
462
+
463
+                if ($currentDelay === 0) {
464
+                    $throttler->sleepDelay($request->getRemoteAddress(), 'login');
465
+                }
466
+                return false;
467
+            }
468
+        }
469
+
470
+        if ($isTokenPassword) {
471
+            $this->session->set('app_password', $password);
472
+        } elseif ($this->supportsCookies($request)) {
473
+            // Password login, but cookies supported -> create (browser) session token
474
+            $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
475
+        }
476
+
477
+        return true;
478
+    }
479
+
480
+    protected function supportsCookies(IRequest $request) {
481
+        if (!is_null($request->getCookie('cookie_test'))) {
482
+            return true;
483
+        }
484
+        setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600);
485
+        return false;
486
+    }
487
+
488
+    private function isTokenAuthEnforced() {
489
+        return $this->config->getSystemValue('token_auth_enforced', false);
490
+    }
491
+
492
+    protected function isTwoFactorEnforced($username) {
493
+        Util::emitHook(
494
+            '\OCA\Files_Sharing\API\Server2Server',
495
+            'preLoginNameUsedAsUserName',
496
+            ['uid' => &$username]
497
+        );
498
+        $user = $this->manager->get($username);
499
+        if (is_null($user)) {
500
+            $users = $this->manager->getByEmail($username);
501
+            if (empty($users)) {
502
+                return false;
503
+            }
504
+            if (count($users) !== 1) {
505
+                return true;
506
+            }
507
+            $user = $users[0];
508
+        }
509
+        // DI not possible due to cyclic dependencies :'-/
510
+        return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
511
+    }
512
+
513
+    /**
514
+     * Check if the given 'password' is actually a device token
515
+     *
516
+     * @param string $password
517
+     * @return boolean
518
+     * @throws ExpiredTokenException
519
+     */
520
+    public function isTokenPassword($password) {
521
+        try {
522
+            $this->tokenProvider->getToken($password);
523
+            return true;
524
+        } catch (ExpiredTokenException $e) {
525
+            throw $e;
526
+        } catch (InvalidTokenException $ex) {
527
+            $this->logger->debug('Token is not valid: ' . $ex->getMessage(), [
528
+                'exception' => $ex,
529
+            ]);
530
+            return false;
531
+        }
532
+    }
533
+
534
+    protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) {
535
+        if ($refreshCsrfToken) {
536
+            // TODO: mock/inject/use non-static
537
+            // Refresh the token
538
+            \OC::$server->getCsrfTokenManager()->refreshToken();
539
+        }
540
+
541
+        if ($firstTimeLogin) {
542
+            //we need to pass the user name, which may differ from login name
543
+            $user = $this->getUser()->getUID();
544
+            OC_Util::setupFS($user);
545
+
546
+            // TODO: lock necessary?
547
+            //trigger creation of user home and /files folder
548
+            $userFolder = \OC::$server->getUserFolder($user);
549
+
550
+            try {
551
+                // copy skeleton
552
+                \OC_Util::copySkeleton($user, $userFolder);
553
+            } catch (NotPermittedException $ex) {
554
+                // read only uses
555
+            }
556
+
557
+            // trigger any other initialization
558
+            \OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
559
+        }
560
+    }
561
+
562
+    /**
563
+     * Tries to login the user with HTTP Basic Authentication
564
+     *
565
+     * @todo do not allow basic auth if the user is 2FA enforced
566
+     * @param IRequest $request
567
+     * @param OC\Security\Bruteforce\Throttler $throttler
568
+     * @return boolean if the login was successful
569
+     */
570
+    public function tryBasicAuthLogin(IRequest $request,
571
+                                        OC\Security\Bruteforce\Throttler $throttler) {
572
+        if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
573
+            try {
574
+                if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
575
+                    /**
576
+                     * Add DAV authenticated. This should in an ideal world not be
577
+                     * necessary but the iOS App reads cookies from anywhere instead
578
+                     * only the DAV endpoint.
579
+                     * This makes sure that the cookies will be valid for the whole scope
580
+                     * @see https://github.com/owncloud/core/issues/22893
581
+                     */
582
+                    $this->session->set(
583
+                        Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
584
+                    );
585
+
586
+                    // Set the last-password-confirm session to make the sudo mode work
587
+                    $this->session->set('last-password-confirm', $this->timeFactory->getTime());
588
+
589
+                    return true;
590
+                }
591
+                // If credentials were provided, they need to be valid, otherwise we do boom
592
+                throw new LoginException();
593
+            } catch (PasswordLoginForbiddenException $ex) {
594
+                // Nothing to do
595
+            }
596
+        }
597
+        return false;
598
+    }
599
+
600
+    /**
601
+     * Log an user in via login name and password
602
+     *
603
+     * @param string $uid
604
+     * @param string $password
605
+     * @return boolean
606
+     * @throws LoginException if an app canceld the login process or the user is not enabled
607
+     */
608
+    private function loginWithPassword($uid, $password) {
609
+        $user = $this->manager->checkPasswordNoLogging($uid, $password);
610
+        if ($user === false) {
611
+            // Password check failed
612
+            return false;
613
+        }
614
+
615
+        return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false);
616
+    }
617
+
618
+    /**
619
+     * Log an user in with a given token (id)
620
+     *
621
+     * @param string $token
622
+     * @return boolean
623
+     * @throws LoginException if an app canceled the login process or the user is not enabled
624
+     */
625
+    private function loginWithToken($token) {
626
+        try {
627
+            $dbToken = $this->tokenProvider->getToken($token);
628
+        } catch (InvalidTokenException $ex) {
629
+            return false;
630
+        }
631
+        $uid = $dbToken->getUID();
632
+
633
+        // When logging in with token, the password must be decrypted first before passing to login hook
634
+        $password = '';
635
+        try {
636
+            $password = $this->tokenProvider->getPassword($dbToken, $token);
637
+        } catch (PasswordlessTokenException $ex) {
638
+            // Ignore and use empty string instead
639
+        }
640
+
641
+        $this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]);
642
+
643
+        $user = $this->manager->get($uid);
644
+        if (is_null($user)) {
645
+            // user does not exist
646
+            return false;
647
+        }
648
+
649
+        return $this->completeLogin(
650
+            $user,
651
+            [
652
+                'loginName' => $dbToken->getLoginName(),
653
+                'password' => $password,
654
+                'token' => $dbToken
655
+            ],
656
+            false);
657
+    }
658
+
659
+    /**
660
+     * Create a new session token for the given user credentials
661
+     *
662
+     * @param IRequest $request
663
+     * @param string $uid user UID
664
+     * @param string $loginName login name
665
+     * @param string $password
666
+     * @param int $remember
667
+     * @return boolean
668
+     */
669
+    public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
670
+        if (is_null($this->manager->get($uid))) {
671
+            // User does not exist
672
+            return false;
673
+        }
674
+        $name = isset($request->server['HTTP_USER_AGENT']) ? mb_convert_encoding($request->server['HTTP_USER_AGENT'], 'UTF-8', 'ISO-8859-1') : 'unknown browser';
675
+        try {
676
+            $sessionId = $this->session->getId();
677
+            $pwd = $this->getPassword($password);
678
+            // Make sure the current sessionId has no leftover tokens
679
+            $this->tokenProvider->invalidateToken($sessionId);
680
+            $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
681
+            return true;
682
+        } catch (SessionNotAvailableException $ex) {
683
+            // This can happen with OCC, where a memory session is used
684
+            // if a memory session is used, we shouldn't create a session token anyway
685
+            return false;
686
+        }
687
+    }
688
+
689
+    /**
690
+     * Checks if the given password is a token.
691
+     * If yes, the password is extracted from the token.
692
+     * If no, the same password is returned.
693
+     *
694
+     * @param string $password either the login password or a device token
695
+     * @return string|null the password or null if none was set in the token
696
+     */
697
+    private function getPassword($password) {
698
+        if (is_null($password)) {
699
+            // This is surely no token ;-)
700
+            return null;
701
+        }
702
+        try {
703
+            $token = $this->tokenProvider->getToken($password);
704
+            try {
705
+                return $this->tokenProvider->getPassword($token, $password);
706
+            } catch (PasswordlessTokenException $ex) {
707
+                return null;
708
+            }
709
+        } catch (InvalidTokenException $ex) {
710
+            return $password;
711
+        }
712
+    }
713
+
714
+    /**
715
+     * @param IToken $dbToken
716
+     * @param string $token
717
+     * @return boolean
718
+     */
719
+    private function checkTokenCredentials(IToken $dbToken, $token) {
720
+        // Check whether login credentials are still valid and the user was not disabled
721
+        // This check is performed each 5 minutes
722
+        $lastCheck = $dbToken->getLastCheck() ? : 0;
723
+        $now = $this->timeFactory->getTime();
724
+        if ($lastCheck > ($now - 60 * 5)) {
725
+            // Checked performed recently, nothing to do now
726
+            return true;
727
+        }
728
+
729
+        try {
730
+            $pwd = $this->tokenProvider->getPassword($dbToken, $token);
731
+        } catch (InvalidTokenException $ex) {
732
+            // An invalid token password was used -> log user out
733
+            return false;
734
+        } catch (PasswordlessTokenException $ex) {
735
+            // Token has no password
736
+
737
+            if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
738
+                $this->tokenProvider->invalidateToken($token);
739
+                return false;
740
+            }
741
+
742
+            $dbToken->setLastCheck($now);
743
+            $this->tokenProvider->updateToken($dbToken);
744
+            return true;
745
+        }
746
+
747
+        // Invalidate token if the user is no longer active
748
+        if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
749
+            $this->tokenProvider->invalidateToken($token);
750
+            return false;
751
+        }
752
+
753
+        // If the token password is no longer valid mark it as such
754
+        if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) {
755
+            $this->tokenProvider->markPasswordInvalid($dbToken, $token);
756
+            // User is logged out
757
+            return false;
758
+        }
759
+
760
+        $dbToken->setLastCheck($now);
761
+        $this->tokenProvider->updateToken($dbToken);
762
+        return true;
763
+    }
764
+
765
+    /**
766
+     * Check if the given token exists and performs password/user-enabled checks
767
+     *
768
+     * Invalidates the token if checks fail
769
+     *
770
+     * @param string $token
771
+     * @param string $user login name
772
+     * @return boolean
773
+     */
774
+    private function validateToken($token, $user = null) {
775
+        try {
776
+            $dbToken = $this->tokenProvider->getToken($token);
777
+        } catch (InvalidTokenException $ex) {
778
+            return false;
779
+        }
780
+
781
+        // Check if login names match
782
+        if (!is_null($user) && $dbToken->getLoginName() !== $user) {
783
+            // TODO: this makes it impossible to use different login names on browser and client
784
+            // e.g. login by e-mail '[email protected]' on browser for generating the token will not
785
+            //      allow to use the client token with the login name 'user'.
786
+            $this->logger->error('App token login name does not match', [
787
+                'tokenLoginName' => $dbToken->getLoginName(),
788
+                'sessionLoginName' => $user,
789
+            ]);
790
+
791
+            return false;
792
+        }
793
+
794
+        if (!$this->checkTokenCredentials($dbToken, $token)) {
795
+            return false;
796
+        }
797
+
798
+        // Update token scope
799
+        $this->lockdownManager->setToken($dbToken);
800
+
801
+        $this->tokenProvider->updateTokenActivity($dbToken);
802
+
803
+        return true;
804
+    }
805
+
806
+    /**
807
+     * Tries to login the user with auth token header
808
+     *
809
+     * @param IRequest $request
810
+     * @todo check remember me cookie
811
+     * @return boolean
812
+     */
813
+    public function tryTokenLogin(IRequest $request) {
814
+        $authHeader = $request->getHeader('Authorization');
815
+        if (strpos($authHeader, 'Bearer ') === 0) {
816
+            $token = substr($authHeader, 7);
817
+        } else {
818
+            // No auth header, let's try session id
819
+            try {
820
+                $token = $this->session->getId();
821
+            } catch (SessionNotAvailableException $ex) {
822
+                return false;
823
+            }
824
+        }
825
+
826
+        if (!$this->loginWithToken($token)) {
827
+            return false;
828
+        }
829
+        if (!$this->validateToken($token)) {
830
+            return false;
831
+        }
832
+
833
+        try {
834
+            $dbToken = $this->tokenProvider->getToken($token);
835
+        } catch (InvalidTokenException $e) {
836
+            // Can't really happen but better save than sorry
837
+            return true;
838
+        }
839
+
840
+        // Remember me tokens are not app_passwords
841
+        if ($dbToken->getRemember() === IToken::DO_NOT_REMEMBER) {
842
+            // Set the session variable so we know this is an app password
843
+            $this->session->set('app_password', $token);
844
+        }
845
+
846
+        return true;
847
+    }
848
+
849
+    /**
850
+     * perform login using the magic cookie (remember login)
851
+     *
852
+     * @param string $uid the username
853
+     * @param string $currentToken
854
+     * @param string $oldSessionId
855
+     * @return bool
856
+     */
857
+    public function loginWithCookie($uid, $currentToken, $oldSessionId) {
858
+        $this->session->regenerateId();
859
+        $this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]);
860
+        $user = $this->manager->get($uid);
861
+        if (is_null($user)) {
862
+            // user does not exist
863
+            return false;
864
+        }
865
+
866
+        // get stored tokens
867
+        $tokens = $this->config->getUserKeys($uid, 'login_token');
868
+        // test cookies token against stored tokens
869
+        if (!in_array($currentToken, $tokens, true)) {
870
+            $this->logger->info('Tried to log in {uid} but could not verify token', [
871
+                'app' => 'core',
872
+                'uid' => $uid,
873
+            ]);
874
+            return false;
875
+        }
876
+        // replace successfully used token with a new one
877
+        $this->config->deleteUserValue($uid, 'login_token', $currentToken);
878
+        $newToken = $this->random->generate(32);
879
+        $this->config->setUserValue($uid, 'login_token', $newToken, (string)$this->timeFactory->getTime());
880
+
881
+        try {
882
+            $sessionId = $this->session->getId();
883
+            $token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
884
+        } catch (SessionNotAvailableException $ex) {
885
+            $this->logger->warning('Could not renew session token for {uid} because the session is unavailable', [
886
+                'app' => 'core',
887
+                'uid' => $uid,
888
+            ]);
889
+            return false;
890
+        } catch (InvalidTokenException $ex) {
891
+            $this->logger->warning('Renewing session token failed', ['app' => 'core']);
892
+            return false;
893
+        }
894
+
895
+        $this->setMagicInCookie($user->getUID(), $newToken);
896
+
897
+        //login
898
+        $this->setUser($user);
899
+        $this->setLoginName($token->getLoginName());
900
+        $this->setToken($token->getId());
901
+        $this->lockdownManager->setToken($token);
902
+        $user->updateLastLoginTimestamp();
903
+        $password = null;
904
+        try {
905
+            $password = $this->tokenProvider->getPassword($token, $sessionId);
906
+        } catch (PasswordlessTokenException $ex) {
907
+            // Ignore
908
+        }
909
+        $this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]);
910
+        return true;
911
+    }
912
+
913
+    /**
914
+     * @param IUser $user
915
+     */
916
+    public function createRememberMeToken(IUser $user) {
917
+        $token = $this->random->generate(32);
918
+        $this->config->setUserValue($user->getUID(), 'login_token', $token, (string)$this->timeFactory->getTime());
919
+        $this->setMagicInCookie($user->getUID(), $token);
920
+    }
921
+
922
+    /**
923
+     * logout the user from the session
924
+     */
925
+    public function logout() {
926
+        $user = $this->getUser();
927
+        $this->manager->emit('\OC\User', 'logout', [$user]);
928
+        if ($user !== null) {
929
+            try {
930
+                $this->tokenProvider->invalidateToken($this->session->getId());
931
+            } catch (SessionNotAvailableException $ex) {
932
+            }
933
+        }
934
+        $this->setUser(null);
935
+        $this->setLoginName(null);
936
+        $this->setToken(null);
937
+        $this->unsetMagicInCookie();
938
+        $this->session->clear();
939
+        $this->manager->emit('\OC\User', 'postLogout', [$user]);
940
+    }
941
+
942
+    /**
943
+     * Set cookie value to use in next page load
944
+     *
945
+     * @param string $username username to be set
946
+     * @param string $token
947
+     */
948
+    public function setMagicInCookie($username, $token) {
949
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
950
+        $webRoot = \OC::$WEBROOT;
951
+        if ($webRoot === '') {
952
+            $webRoot = '/';
953
+        }
954
+
955
+        $maxAge = $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
956
+        \OC\Http\CookieHelper::setCookie(
957
+            'nc_username',
958
+            $username,
959
+            $maxAge,
960
+            $webRoot,
961
+            '',
962
+            $secureCookie,
963
+            true,
964
+            \OC\Http\CookieHelper::SAMESITE_LAX
965
+        );
966
+        \OC\Http\CookieHelper::setCookie(
967
+            'nc_token',
968
+            $token,
969
+            $maxAge,
970
+            $webRoot,
971
+            '',
972
+            $secureCookie,
973
+            true,
974
+            \OC\Http\CookieHelper::SAMESITE_LAX
975
+        );
976
+        try {
977
+            \OC\Http\CookieHelper::setCookie(
978
+                'nc_session_id',
979
+                $this->session->getId(),
980
+                $maxAge,
981
+                $webRoot,
982
+                '',
983
+                $secureCookie,
984
+                true,
985
+                \OC\Http\CookieHelper::SAMESITE_LAX
986
+            );
987
+        } catch (SessionNotAvailableException $ex) {
988
+            // ignore
989
+        }
990
+    }
991
+
992
+    /**
993
+     * Remove cookie for "remember username"
994
+     */
995
+    public function unsetMagicInCookie() {
996
+        //TODO: DI for cookies and IRequest
997
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
998
+
999
+        unset($_COOKIE['nc_username']); //TODO: DI
1000
+        unset($_COOKIE['nc_token']);
1001
+        unset($_COOKIE['nc_session_id']);
1002
+        setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1003
+        setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1004
+        setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1005
+        // old cookies might be stored under /webroot/ instead of /webroot
1006
+        // and Firefox doesn't like it!
1007
+        setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1008
+        setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1009
+        setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1010
+    }
1011
+
1012
+    /**
1013
+     * Update password of the browser session token if there is one
1014
+     *
1015
+     * @param string $password
1016
+     */
1017
+    public function updateSessionTokenPassword($password) {
1018
+        try {
1019
+            $sessionId = $this->session->getId();
1020
+            $token = $this->tokenProvider->getToken($sessionId);
1021
+            $this->tokenProvider->setPassword($token, $sessionId, $password);
1022
+        } catch (SessionNotAvailableException $ex) {
1023
+            // Nothing to do
1024
+        } catch (InvalidTokenException $ex) {
1025
+            // Nothing to do
1026
+        }
1027
+    }
1028
+
1029
+    public function updateTokens(string $uid, string $password) {
1030
+        $this->tokenProvider->updatePasswords($uid, $password);
1031
+    }
1032 1032
 }
Please login to merge, or discard this patch.