Passed
Push — master ( bf1c87...c52a02 )
by Joas
16:33 queued 11s
created
lib/private/User/Session.php 1 patch
Indentation   +934 added lines, -934 removed lines patch added patch discarded remove patch
@@ -91,938 +91,938 @@
 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
-				// If credentials were provided, they need to be valid, otherwise we do boom
603
-				throw new LoginException();
604
-			} catch (PasswordLoginForbiddenException $ex) {
605
-				// Nothing to do
606
-			}
607
-		}
608
-		return false;
609
-	}
610
-
611
-	/**
612
-	 * Log an user in via login name and password
613
-	 *
614
-	 * @param string $uid
615
-	 * @param string $password
616
-	 * @return boolean
617
-	 * @throws LoginException if an app canceld the login process or the user is not enabled
618
-	 */
619
-	private function loginWithPassword($uid, $password) {
620
-		$user = $this->manager->checkPasswordNoLogging($uid, $password);
621
-		if ($user === false) {
622
-			// Password check failed
623
-			return false;
624
-		}
625
-
626
-		return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false);
627
-	}
628
-
629
-	/**
630
-	 * Log an user in with a given token (id)
631
-	 *
632
-	 * @param string $token
633
-	 * @return boolean
634
-	 * @throws LoginException if an app canceled the login process or the user is not enabled
635
-	 */
636
-	private function loginWithToken($token) {
637
-		try {
638
-			$dbToken = $this->tokenProvider->getToken($token);
639
-		} catch (InvalidTokenException $ex) {
640
-			return false;
641
-		}
642
-		$uid = $dbToken->getUID();
643
-
644
-		// When logging in with token, the password must be decrypted first before passing to login hook
645
-		$password = '';
646
-		try {
647
-			$password = $this->tokenProvider->getPassword($dbToken, $token);
648
-		} catch (PasswordlessTokenException $ex) {
649
-			// Ignore and use empty string instead
650
-		}
651
-
652
-		$this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]);
653
-
654
-		$user = $this->manager->get($uid);
655
-		if (is_null($user)) {
656
-			// user does not exist
657
-			return false;
658
-		}
659
-
660
-		return $this->completeLogin(
661
-			$user,
662
-			[
663
-				'loginName' => $dbToken->getLoginName(),
664
-				'password' => $password,
665
-				'token' => $dbToken
666
-			],
667
-			false);
668
-	}
669
-
670
-	/**
671
-	 * Create a new session token for the given user credentials
672
-	 *
673
-	 * @param IRequest $request
674
-	 * @param string $uid user UID
675
-	 * @param string $loginName login name
676
-	 * @param string $password
677
-	 * @param int $remember
678
-	 * @return boolean
679
-	 */
680
-	public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
681
-		if (is_null($this->manager->get($uid))) {
682
-			// User does not exist
683
-			return false;
684
-		}
685
-		$name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
686
-		try {
687
-			$sessionId = $this->session->getId();
688
-			$pwd = $this->getPassword($password);
689
-			// Make sure the current sessionId has no leftover tokens
690
-			$this->tokenProvider->invalidateToken($sessionId);
691
-			$this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
692
-			return true;
693
-		} catch (SessionNotAvailableException $ex) {
694
-			// This can happen with OCC, where a memory session is used
695
-			// if a memory session is used, we shouldn't create a session token anyway
696
-			return false;
697
-		}
698
-	}
699
-
700
-	/**
701
-	 * Checks if the given password is a token.
702
-	 * If yes, the password is extracted from the token.
703
-	 * If no, the same password is returned.
704
-	 *
705
-	 * @param string $password either the login password or a device token
706
-	 * @return string|null the password or null if none was set in the token
707
-	 */
708
-	private function getPassword($password) {
709
-		if (is_null($password)) {
710
-			// This is surely no token ;-)
711
-			return null;
712
-		}
713
-		try {
714
-			$token = $this->tokenProvider->getToken($password);
715
-			try {
716
-				return $this->tokenProvider->getPassword($token, $password);
717
-			} catch (PasswordlessTokenException $ex) {
718
-				return null;
719
-			}
720
-		} catch (InvalidTokenException $ex) {
721
-			return $password;
722
-		}
723
-	}
724
-
725
-	/**
726
-	 * @param IToken $dbToken
727
-	 * @param string $token
728
-	 * @return boolean
729
-	 */
730
-	private function checkTokenCredentials(IToken $dbToken, $token) {
731
-		// Check whether login credentials are still valid and the user was not disabled
732
-		// This check is performed each 5 minutes
733
-		$lastCheck = $dbToken->getLastCheck() ? : 0;
734
-		$now = $this->timeFactory->getTime();
735
-		if ($lastCheck > ($now - 60 * 5)) {
736
-			// Checked performed recently, nothing to do now
737
-			return true;
738
-		}
739
-
740
-		try {
741
-			$pwd = $this->tokenProvider->getPassword($dbToken, $token);
742
-		} catch (InvalidTokenException $ex) {
743
-			// An invalid token password was used -> log user out
744
-			return false;
745
-		} catch (PasswordlessTokenException $ex) {
746
-			// Token has no password
747
-
748
-			if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
749
-				$this->tokenProvider->invalidateToken($token);
750
-				return false;
751
-			}
752
-
753
-			$dbToken->setLastCheck($now);
754
-			return true;
755
-		}
756
-
757
-		// Invalidate token if the user is no longer active
758
-		if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
759
-			$this->tokenProvider->invalidateToken($token);
760
-			return false;
761
-		}
762
-
763
-		// If the token password is no longer valid mark it as such
764
-		if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) {
765
-			$this->tokenProvider->markPasswordInvalid($dbToken, $token);
766
-			// User is logged out
767
-			return false;
768
-		}
769
-
770
-		$dbToken->setLastCheck($now);
771
-		return true;
772
-	}
773
-
774
-	/**
775
-	 * Check if the given token exists and performs password/user-enabled checks
776
-	 *
777
-	 * Invalidates the token if checks fail
778
-	 *
779
-	 * @param string $token
780
-	 * @param string $user login name
781
-	 * @return boolean
782
-	 */
783
-	private function validateToken($token, $user = null) {
784
-		try {
785
-			$dbToken = $this->tokenProvider->getToken($token);
786
-		} catch (InvalidTokenException $ex) {
787
-			return false;
788
-		}
789
-
790
-		// Check if login names match
791
-		if (!is_null($user) && $dbToken->getLoginName() !== $user) {
792
-			// TODO: this makes it imposssible to use different login names on browser and client
793
-			// e.g. login by e-mail '[email protected]' on browser for generating the token will not
794
-			//      allow to use the client token with the login name 'user'.
795
-			return false;
796
-		}
797
-
798
-		if (!$this->checkTokenCredentials($dbToken, $token)) {
799
-			return false;
800
-		}
801
-
802
-		// Update token scope
803
-		$this->lockdownManager->setToken($dbToken);
804
-
805
-		$this->tokenProvider->updateTokenActivity($dbToken);
806
-
807
-		return true;
808
-	}
809
-
810
-	/**
811
-	 * Tries to login the user with auth token header
812
-	 *
813
-	 * @param IRequest $request
814
-	 * @todo check remember me cookie
815
-	 * @return boolean
816
-	 */
817
-	public function tryTokenLogin(IRequest $request) {
818
-		$authHeader = $request->getHeader('Authorization');
819
-		if (strpos($authHeader, 'Bearer ') === 0) {
820
-			$token = substr($authHeader, 7);
821
-		} else {
822
-			// No auth header, let's try session id
823
-			try {
824
-				$token = $this->session->getId();
825
-			} catch (SessionNotAvailableException $ex) {
826
-				return false;
827
-			}
828
-		}
829
-
830
-		if (!$this->loginWithToken($token)) {
831
-			return false;
832
-		}
833
-		if (!$this->validateToken($token)) {
834
-			return false;
835
-		}
836
-
837
-		try {
838
-			$dbToken = $this->tokenProvider->getToken($token);
839
-		} catch (InvalidTokenException $e) {
840
-			// Can't really happen but better save than sorry
841
-			return true;
842
-		}
843
-
844
-		// Remember me tokens are not app_passwords
845
-		if ($dbToken->getRemember() === IToken::DO_NOT_REMEMBER) {
846
-			// Set the session variable so we know this is an app password
847
-			$this->session->set('app_password', $token);
848
-		}
849
-
850
-		return true;
851
-	}
852
-
853
-	/**
854
-	 * perform login using the magic cookie (remember login)
855
-	 *
856
-	 * @param string $uid the username
857
-	 * @param string $currentToken
858
-	 * @param string $oldSessionId
859
-	 * @return bool
860
-	 */
861
-	public function loginWithCookie($uid, $currentToken, $oldSessionId) {
862
-		$this->session->regenerateId();
863
-		$this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]);
864
-		$user = $this->manager->get($uid);
865
-		if (is_null($user)) {
866
-			// user does not exist
867
-			return false;
868
-		}
869
-
870
-		// get stored tokens
871
-		$tokens = $this->config->getUserKeys($uid, 'login_token');
872
-		// test cookies token against stored tokens
873
-		if (!in_array($currentToken, $tokens, true)) {
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, $this->timeFactory->getTime());
880
-
881
-		try {
882
-			$sessionId = $this->session->getId();
883
-			$token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
884
-		} catch (SessionNotAvailableException $ex) {
885
-			return false;
886
-		} catch (InvalidTokenException $ex) {
887
-			\OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
888
-			return false;
889
-		}
890
-
891
-		$this->setMagicInCookie($user->getUID(), $newToken);
892
-
893
-		//login
894
-		$this->setUser($user);
895
-		$this->setLoginName($token->getLoginName());
896
-		$this->setToken($token->getId());
897
-		$this->lockdownManager->setToken($token);
898
-		$user->updateLastLoginTimestamp();
899
-		$password = null;
900
-		try {
901
-			$password = $this->tokenProvider->getPassword($token, $sessionId);
902
-		} catch (PasswordlessTokenException $ex) {
903
-			// Ignore
904
-		}
905
-		$this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]);
906
-		return true;
907
-	}
908
-
909
-	/**
910
-	 * @param IUser $user
911
-	 */
912
-	public function createRememberMeToken(IUser $user) {
913
-		$token = $this->random->generate(32);
914
-		$this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFactory->getTime());
915
-		$this->setMagicInCookie($user->getUID(), $token);
916
-	}
917
-
918
-	/**
919
-	 * logout the user from the session
920
-	 */
921
-	public function logout() {
922
-		$user = $this->getUser();
923
-		$this->manager->emit('\OC\User', 'logout', [$user]);
924
-		if ($user !== null) {
925
-			try {
926
-				$this->tokenProvider->invalidateToken($this->session->getId());
927
-			} catch (SessionNotAvailableException $ex) {
928
-			}
929
-		}
930
-		$this->setUser(null);
931
-		$this->setLoginName(null);
932
-		$this->setToken(null);
933
-		$this->unsetMagicInCookie();
934
-		$this->session->clear();
935
-		$this->manager->emit('\OC\User', 'postLogout', [$user]);
936
-	}
937
-
938
-	/**
939
-	 * Set cookie value to use in next page load
940
-	 *
941
-	 * @param string $username username to be set
942
-	 * @param string $token
943
-	 */
944
-	public function setMagicInCookie($username, $token) {
945
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
946
-		$webRoot = \OC::$WEBROOT;
947
-		if ($webRoot === '') {
948
-			$webRoot = '/';
949
-		}
950
-
951
-		$maxAge = $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
952
-		\OC\Http\CookieHelper::setCookie(
953
-			'nc_username',
954
-			$username,
955
-			$maxAge,
956
-			$webRoot,
957
-			'',
958
-			$secureCookie,
959
-			true,
960
-			\OC\Http\CookieHelper::SAMESITE_LAX
961
-		);
962
-		\OC\Http\CookieHelper::setCookie(
963
-			'nc_token',
964
-			$token,
965
-			$maxAge,
966
-			$webRoot,
967
-			'',
968
-			$secureCookie,
969
-			true,
970
-			\OC\Http\CookieHelper::SAMESITE_LAX
971
-		);
972
-		try {
973
-			\OC\Http\CookieHelper::setCookie(
974
-				'nc_session_id',
975
-				$this->session->getId(),
976
-				$maxAge,
977
-				$webRoot,
978
-				'',
979
-				$secureCookie,
980
-				true,
981
-				\OC\Http\CookieHelper::SAMESITE_LAX
982
-			);
983
-		} catch (SessionNotAvailableException $ex) {
984
-			// ignore
985
-		}
986
-	}
987
-
988
-	/**
989
-	 * Remove cookie for "remember username"
990
-	 */
991
-	public function unsetMagicInCookie() {
992
-		//TODO: DI for cookies and IRequest
993
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
994
-
995
-		unset($_COOKIE['nc_username']); //TODO: DI
996
-		unset($_COOKIE['nc_token']);
997
-		unset($_COOKIE['nc_session_id']);
998
-		setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
999
-		setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1000
-		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1001
-		// old cookies might be stored under /webroot/ instead of /webroot
1002
-		// and Firefox doesn't like it!
1003
-		setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1004
-		setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1005
-		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1006
-	}
1007
-
1008
-	/**
1009
-	 * Update password of the browser session token if there is one
1010
-	 *
1011
-	 * @param string $password
1012
-	 */
1013
-	public function updateSessionTokenPassword($password) {
1014
-		try {
1015
-			$sessionId = $this->session->getId();
1016
-			$token = $this->tokenProvider->getToken($sessionId);
1017
-			$this->tokenProvider->setPassword($token, $sessionId, $password);
1018
-		} catch (SessionNotAvailableException $ex) {
1019
-			// Nothing to do
1020
-		} catch (InvalidTokenException $ex) {
1021
-			// Nothing to do
1022
-		}
1023
-	}
1024
-
1025
-	public function updateTokens(string $uid, string $password) {
1026
-		$this->tokenProvider->updatePasswords($uid, $password);
1027
-	}
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
+                // If credentials were provided, they need to be valid, otherwise we do boom
603
+                throw new LoginException();
604
+            } catch (PasswordLoginForbiddenException $ex) {
605
+                // Nothing to do
606
+            }
607
+        }
608
+        return false;
609
+    }
610
+
611
+    /**
612
+     * Log an user in via login name and password
613
+     *
614
+     * @param string $uid
615
+     * @param string $password
616
+     * @return boolean
617
+     * @throws LoginException if an app canceld the login process or the user is not enabled
618
+     */
619
+    private function loginWithPassword($uid, $password) {
620
+        $user = $this->manager->checkPasswordNoLogging($uid, $password);
621
+        if ($user === false) {
622
+            // Password check failed
623
+            return false;
624
+        }
625
+
626
+        return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false);
627
+    }
628
+
629
+    /**
630
+     * Log an user in with a given token (id)
631
+     *
632
+     * @param string $token
633
+     * @return boolean
634
+     * @throws LoginException if an app canceled the login process or the user is not enabled
635
+     */
636
+    private function loginWithToken($token) {
637
+        try {
638
+            $dbToken = $this->tokenProvider->getToken($token);
639
+        } catch (InvalidTokenException $ex) {
640
+            return false;
641
+        }
642
+        $uid = $dbToken->getUID();
643
+
644
+        // When logging in with token, the password must be decrypted first before passing to login hook
645
+        $password = '';
646
+        try {
647
+            $password = $this->tokenProvider->getPassword($dbToken, $token);
648
+        } catch (PasswordlessTokenException $ex) {
649
+            // Ignore and use empty string instead
650
+        }
651
+
652
+        $this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]);
653
+
654
+        $user = $this->manager->get($uid);
655
+        if (is_null($user)) {
656
+            // user does not exist
657
+            return false;
658
+        }
659
+
660
+        return $this->completeLogin(
661
+            $user,
662
+            [
663
+                'loginName' => $dbToken->getLoginName(),
664
+                'password' => $password,
665
+                'token' => $dbToken
666
+            ],
667
+            false);
668
+    }
669
+
670
+    /**
671
+     * Create a new session token for the given user credentials
672
+     *
673
+     * @param IRequest $request
674
+     * @param string $uid user UID
675
+     * @param string $loginName login name
676
+     * @param string $password
677
+     * @param int $remember
678
+     * @return boolean
679
+     */
680
+    public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
681
+        if (is_null($this->manager->get($uid))) {
682
+            // User does not exist
683
+            return false;
684
+        }
685
+        $name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
686
+        try {
687
+            $sessionId = $this->session->getId();
688
+            $pwd = $this->getPassword($password);
689
+            // Make sure the current sessionId has no leftover tokens
690
+            $this->tokenProvider->invalidateToken($sessionId);
691
+            $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
692
+            return true;
693
+        } catch (SessionNotAvailableException $ex) {
694
+            // This can happen with OCC, where a memory session is used
695
+            // if a memory session is used, we shouldn't create a session token anyway
696
+            return false;
697
+        }
698
+    }
699
+
700
+    /**
701
+     * Checks if the given password is a token.
702
+     * If yes, the password is extracted from the token.
703
+     * If no, the same password is returned.
704
+     *
705
+     * @param string $password either the login password or a device token
706
+     * @return string|null the password or null if none was set in the token
707
+     */
708
+    private function getPassword($password) {
709
+        if (is_null($password)) {
710
+            // This is surely no token ;-)
711
+            return null;
712
+        }
713
+        try {
714
+            $token = $this->tokenProvider->getToken($password);
715
+            try {
716
+                return $this->tokenProvider->getPassword($token, $password);
717
+            } catch (PasswordlessTokenException $ex) {
718
+                return null;
719
+            }
720
+        } catch (InvalidTokenException $ex) {
721
+            return $password;
722
+        }
723
+    }
724
+
725
+    /**
726
+     * @param IToken $dbToken
727
+     * @param string $token
728
+     * @return boolean
729
+     */
730
+    private function checkTokenCredentials(IToken $dbToken, $token) {
731
+        // Check whether login credentials are still valid and the user was not disabled
732
+        // This check is performed each 5 minutes
733
+        $lastCheck = $dbToken->getLastCheck() ? : 0;
734
+        $now = $this->timeFactory->getTime();
735
+        if ($lastCheck > ($now - 60 * 5)) {
736
+            // Checked performed recently, nothing to do now
737
+            return true;
738
+        }
739
+
740
+        try {
741
+            $pwd = $this->tokenProvider->getPassword($dbToken, $token);
742
+        } catch (InvalidTokenException $ex) {
743
+            // An invalid token password was used -> log user out
744
+            return false;
745
+        } catch (PasswordlessTokenException $ex) {
746
+            // Token has no password
747
+
748
+            if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
749
+                $this->tokenProvider->invalidateToken($token);
750
+                return false;
751
+            }
752
+
753
+            $dbToken->setLastCheck($now);
754
+            return true;
755
+        }
756
+
757
+        // Invalidate token if the user is no longer active
758
+        if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
759
+            $this->tokenProvider->invalidateToken($token);
760
+            return false;
761
+        }
762
+
763
+        // If the token password is no longer valid mark it as such
764
+        if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) {
765
+            $this->tokenProvider->markPasswordInvalid($dbToken, $token);
766
+            // User is logged out
767
+            return false;
768
+        }
769
+
770
+        $dbToken->setLastCheck($now);
771
+        return true;
772
+    }
773
+
774
+    /**
775
+     * Check if the given token exists and performs password/user-enabled checks
776
+     *
777
+     * Invalidates the token if checks fail
778
+     *
779
+     * @param string $token
780
+     * @param string $user login name
781
+     * @return boolean
782
+     */
783
+    private function validateToken($token, $user = null) {
784
+        try {
785
+            $dbToken = $this->tokenProvider->getToken($token);
786
+        } catch (InvalidTokenException $ex) {
787
+            return false;
788
+        }
789
+
790
+        // Check if login names match
791
+        if (!is_null($user) && $dbToken->getLoginName() !== $user) {
792
+            // TODO: this makes it imposssible to use different login names on browser and client
793
+            // e.g. login by e-mail '[email protected]' on browser for generating the token will not
794
+            //      allow to use the client token with the login name 'user'.
795
+            return false;
796
+        }
797
+
798
+        if (!$this->checkTokenCredentials($dbToken, $token)) {
799
+            return false;
800
+        }
801
+
802
+        // Update token scope
803
+        $this->lockdownManager->setToken($dbToken);
804
+
805
+        $this->tokenProvider->updateTokenActivity($dbToken);
806
+
807
+        return true;
808
+    }
809
+
810
+    /**
811
+     * Tries to login the user with auth token header
812
+     *
813
+     * @param IRequest $request
814
+     * @todo check remember me cookie
815
+     * @return boolean
816
+     */
817
+    public function tryTokenLogin(IRequest $request) {
818
+        $authHeader = $request->getHeader('Authorization');
819
+        if (strpos($authHeader, 'Bearer ') === 0) {
820
+            $token = substr($authHeader, 7);
821
+        } else {
822
+            // No auth header, let's try session id
823
+            try {
824
+                $token = $this->session->getId();
825
+            } catch (SessionNotAvailableException $ex) {
826
+                return false;
827
+            }
828
+        }
829
+
830
+        if (!$this->loginWithToken($token)) {
831
+            return false;
832
+        }
833
+        if (!$this->validateToken($token)) {
834
+            return false;
835
+        }
836
+
837
+        try {
838
+            $dbToken = $this->tokenProvider->getToken($token);
839
+        } catch (InvalidTokenException $e) {
840
+            // Can't really happen but better save than sorry
841
+            return true;
842
+        }
843
+
844
+        // Remember me tokens are not app_passwords
845
+        if ($dbToken->getRemember() === IToken::DO_NOT_REMEMBER) {
846
+            // Set the session variable so we know this is an app password
847
+            $this->session->set('app_password', $token);
848
+        }
849
+
850
+        return true;
851
+    }
852
+
853
+    /**
854
+     * perform login using the magic cookie (remember login)
855
+     *
856
+     * @param string $uid the username
857
+     * @param string $currentToken
858
+     * @param string $oldSessionId
859
+     * @return bool
860
+     */
861
+    public function loginWithCookie($uid, $currentToken, $oldSessionId) {
862
+        $this->session->regenerateId();
863
+        $this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]);
864
+        $user = $this->manager->get($uid);
865
+        if (is_null($user)) {
866
+            // user does not exist
867
+            return false;
868
+        }
869
+
870
+        // get stored tokens
871
+        $tokens = $this->config->getUserKeys($uid, 'login_token');
872
+        // test cookies token against stored tokens
873
+        if (!in_array($currentToken, $tokens, true)) {
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, $this->timeFactory->getTime());
880
+
881
+        try {
882
+            $sessionId = $this->session->getId();
883
+            $token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
884
+        } catch (SessionNotAvailableException $ex) {
885
+            return false;
886
+        } catch (InvalidTokenException $ex) {
887
+            \OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
888
+            return false;
889
+        }
890
+
891
+        $this->setMagicInCookie($user->getUID(), $newToken);
892
+
893
+        //login
894
+        $this->setUser($user);
895
+        $this->setLoginName($token->getLoginName());
896
+        $this->setToken($token->getId());
897
+        $this->lockdownManager->setToken($token);
898
+        $user->updateLastLoginTimestamp();
899
+        $password = null;
900
+        try {
901
+            $password = $this->tokenProvider->getPassword($token, $sessionId);
902
+        } catch (PasswordlessTokenException $ex) {
903
+            // Ignore
904
+        }
905
+        $this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]);
906
+        return true;
907
+    }
908
+
909
+    /**
910
+     * @param IUser $user
911
+     */
912
+    public function createRememberMeToken(IUser $user) {
913
+        $token = $this->random->generate(32);
914
+        $this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFactory->getTime());
915
+        $this->setMagicInCookie($user->getUID(), $token);
916
+    }
917
+
918
+    /**
919
+     * logout the user from the session
920
+     */
921
+    public function logout() {
922
+        $user = $this->getUser();
923
+        $this->manager->emit('\OC\User', 'logout', [$user]);
924
+        if ($user !== null) {
925
+            try {
926
+                $this->tokenProvider->invalidateToken($this->session->getId());
927
+            } catch (SessionNotAvailableException $ex) {
928
+            }
929
+        }
930
+        $this->setUser(null);
931
+        $this->setLoginName(null);
932
+        $this->setToken(null);
933
+        $this->unsetMagicInCookie();
934
+        $this->session->clear();
935
+        $this->manager->emit('\OC\User', 'postLogout', [$user]);
936
+    }
937
+
938
+    /**
939
+     * Set cookie value to use in next page load
940
+     *
941
+     * @param string $username username to be set
942
+     * @param string $token
943
+     */
944
+    public function setMagicInCookie($username, $token) {
945
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
946
+        $webRoot = \OC::$WEBROOT;
947
+        if ($webRoot === '') {
948
+            $webRoot = '/';
949
+        }
950
+
951
+        $maxAge = $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
952
+        \OC\Http\CookieHelper::setCookie(
953
+            'nc_username',
954
+            $username,
955
+            $maxAge,
956
+            $webRoot,
957
+            '',
958
+            $secureCookie,
959
+            true,
960
+            \OC\Http\CookieHelper::SAMESITE_LAX
961
+        );
962
+        \OC\Http\CookieHelper::setCookie(
963
+            'nc_token',
964
+            $token,
965
+            $maxAge,
966
+            $webRoot,
967
+            '',
968
+            $secureCookie,
969
+            true,
970
+            \OC\Http\CookieHelper::SAMESITE_LAX
971
+        );
972
+        try {
973
+            \OC\Http\CookieHelper::setCookie(
974
+                'nc_session_id',
975
+                $this->session->getId(),
976
+                $maxAge,
977
+                $webRoot,
978
+                '',
979
+                $secureCookie,
980
+                true,
981
+                \OC\Http\CookieHelper::SAMESITE_LAX
982
+            );
983
+        } catch (SessionNotAvailableException $ex) {
984
+            // ignore
985
+        }
986
+    }
987
+
988
+    /**
989
+     * Remove cookie for "remember username"
990
+     */
991
+    public function unsetMagicInCookie() {
992
+        //TODO: DI for cookies and IRequest
993
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
994
+
995
+        unset($_COOKIE['nc_username']); //TODO: DI
996
+        unset($_COOKIE['nc_token']);
997
+        unset($_COOKIE['nc_session_id']);
998
+        setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
999
+        setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1000
+        setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
1001
+        // old cookies might be stored under /webroot/ instead of /webroot
1002
+        // and Firefox doesn't like it!
1003
+        setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1004
+        setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1005
+        setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
1006
+    }
1007
+
1008
+    /**
1009
+     * Update password of the browser session token if there is one
1010
+     *
1011
+     * @param string $password
1012
+     */
1013
+    public function updateSessionTokenPassword($password) {
1014
+        try {
1015
+            $sessionId = $this->session->getId();
1016
+            $token = $this->tokenProvider->getToken($sessionId);
1017
+            $this->tokenProvider->setPassword($token, $sessionId, $password);
1018
+        } catch (SessionNotAvailableException $ex) {
1019
+            // Nothing to do
1020
+        } catch (InvalidTokenException $ex) {
1021
+            // Nothing to do
1022
+        }
1023
+    }
1024
+
1025
+    public function updateTokens(string $uid, string $password) {
1026
+        $this->tokenProvider->updatePasswords($uid, $password);
1027
+    }
1028 1028
 }
Please login to merge, or discard this patch.