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