From 02810c118a40bf8f746f7164efe9722464cd4672 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Fri, 6 Mar 2026 13:49:13 +0100 Subject: [PATCH 1/2] refactor(user): Replace all usage of OC_User::setPassword And deprecated OC_User::setPassword Signed-off-by: Carl Schwan --- apps/user_ldap/tests/User_LDAPTest.php | 24 +++++++++++++++--------- lib/private/legacy/OC_User.php | 1 + 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/apps/user_ldap/tests/User_LDAPTest.php b/apps/user_ldap/tests/User_LDAPTest.php index 4720b0a570935..eacf634618989 100644 --- a/apps/user_ldap/tests/User_LDAPTest.php +++ b/apps/user_ldap/tests/User_LDAPTest.php @@ -1238,9 +1238,11 @@ public function testSetPasswordInvalid(): void { ->method('get') ->willReturn($this->createMock(User::class)); $backend = new User_LDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); - Server::get(IUserManager::class)->registerBackend($backend); - - $this->assertTrue(\OC_User::setPassword('roland', 'dt')); + $userManager = Server::get(IUserManager::class); + $userManager->registerBackend($backend); + $user = $userManager->get('roland'); + $this->assertNotNull($user); + $this->assertTrue($user->setPassword('dt')); } public function testSetPasswordValid(): void { @@ -1255,9 +1257,11 @@ public function testSetPasswordValid(): void { ->method('get') ->willReturn($this->createMock(User::class)); - Server::get(IUserManager::class)->registerBackend($backend); - - $this->assertTrue(\OC_User::setPassword('roland', 'dt12234$')); + $userManager = Server::get(IUserManager::class); + $userManager->registerBackend($backend); + $user = $userManager->get('roland'); + $this->assertNotNull($user); + $this->assertTrue($user->setPassword('dt12234$')); } public function testSetPasswordValidDisabled(): void { @@ -1267,9 +1271,11 @@ public function testSetPasswordValidDisabled(): void { $this->prepareAccessForSetPassword(false); $backend = new User_LDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); - Server::get(IUserManager::class)->registerBackend($backend); - - $this->assertFalse(\OC_User::setPassword('roland', 'dt12234$')); + $userManager = Server::get(IUserManager::class); + $userManager->registerBackend($backend); + $user = $userManager->get('roland'); + $this->assertNotNull($user); + $this->assertFalse($user->setPassword('dt12234$')); } diff --git a/lib/private/legacy/OC_User.php b/lib/private/legacy/OC_User.php index ddd426da942e4..df0740ef5d808 100644 --- a/lib/private/legacy/OC_User.php +++ b/lib/private/legacy/OC_User.php @@ -330,6 +330,7 @@ public static function getUser(): string|false { * @param string $recoveryPassword for the encryption app to reset encryption keys * * Change the password of a user + * @deprecated 34.0.0 Use IUserManager::setPassword instead */ public static function setPassword(string $uid, string $password, ?string $recoveryPassword = null): bool { $user = Server::get(IUserManager::class)->get($uid); From d89fdb454d72d4bacedfb0cef12ac3a40a1c70d8 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Fri, 6 Mar 2026 15:27:14 +0100 Subject: [PATCH 2/2] refactor: Deprecate and remove large part of OC_User And replace most usages in Server with the newer APIs Signed-off-by: Carl Schwan --- apps/dav/appinfo/v1/publicwebdav.php | 3 +- apps/dav/appinfo/v2/publicremote.php | 1 + apps/dav/lib/Connector/LegacyPublicAuth.php | 12 +- apps/dav/lib/Connector/Sabre/PublicAuth.php | 18 +- .../unit/Connector/LegacyPublicAuthTest.php | 19 +- .../unit/Connector/Sabre/PublicAuthTest.php | 18 +- apps/federatedfilesharing/tests/TestCase.php | 18 +- apps/files/tests/Service/TagServiceTest.php | 4 +- apps/files_external/lib/Lib/Storage/SFTP.php | 8 +- .../lib/Migration/DummyUserSession.php | 10 + .../lib/Controller/ShareController.php | 6 +- apps/files_sharing/lib/Updater.php | 14 +- .../tests/Controller/ShareControllerTest.php | 8 +- apps/files_sharing/tests/TestCase.php | 5 +- apps/files_trashbin/lib/Trashbin.php | 69 ++--- apps/files_trashbin/tests/TrashbinTest.php | 4 +- apps/files_versions/lib/Storage.php | 10 +- apps/files_versions/tests/VersioningTest.php | 4 +- .../lib/Settings/Personal/PersonalInfo.php | 23 +- .../AdminSettingsControllerTest.php | 4 +- .../Controller/RenewPasswordController.php | 29 +- build/psalm-baseline.xml | 53 ++-- core/ajax/update.php | 3 +- lib/base.php | 2 +- .../DependencyInjection/DIContainer.php | 9 - lib/private/DirectEditing/Manager.php | 12 +- lib/private/Files/View.php | 2 + lib/private/User/Session.php | 19 +- lib/private/legacy/OC_User.php | 249 ++++++++---------- lib/private/legacy/OC_Util.php | 6 +- lib/public/IUserSession.php | 12 + public.php | 4 +- .../DependencyInjection/DIContainerTest.php | 8 +- tests/lib/AppTest.php | 8 +- tests/lib/Cache/FileCacheTest.php | 4 +- tests/lib/Files/ViewTest.php | 2 +- tests/lib/HelperStorageTest.php | 4 +- tests/lib/Security/CertificateManagerTest.php | 2 +- tests/lib/TagsTest.php | 2 +- tests/lib/TestCase.php | 14 +- tests/lib/Traits/EncryptionTrait.php | 17 +- tests/lib/User/SessionTest.php | 2 +- 42 files changed, 399 insertions(+), 322 deletions(-) diff --git a/apps/dav/appinfo/v1/publicwebdav.php b/apps/dav/appinfo/v1/publicwebdav.php index 2eaf05ca2d9b6..0d57b978dc70f 100644 --- a/apps/dav/appinfo/v1/publicwebdav.php +++ b/apps/dav/appinfo/v1/publicwebdav.php @@ -47,7 +47,8 @@ Server::get(IRequest::class), Server::get(\OCP\Share\IManager::class), Server::get(ISession::class), - Server::get(IThrottler::class) + Server::get(IThrottler::class), + Server::get(IUserSession::class), ); $authPlugin = new \Sabre\DAV\Auth\Plugin($authBackend); diff --git a/apps/dav/appinfo/v2/publicremote.php b/apps/dav/appinfo/v2/publicremote.php index facc4041bccde..7d43fef21b1f1 100644 --- a/apps/dav/appinfo/v2/publicremote.php +++ b/apps/dav/appinfo/v2/publicremote.php @@ -64,6 +64,7 @@ Server::get(IThrottler::class), Server::get(LoggerInterface::class), Server::get(IURLGenerator::class), + Server::get(IUserSession::class), ); $authPlugin = new \Sabre\DAV\Auth\Plugin($authBackend); diff --git a/apps/dav/lib/Connector/LegacyPublicAuth.php b/apps/dav/lib/Connector/LegacyPublicAuth.php index 03d18853de0c6..378bff6f17f7d 100644 --- a/apps/dav/lib/Connector/LegacyPublicAuth.php +++ b/apps/dav/lib/Connector/LegacyPublicAuth.php @@ -11,6 +11,7 @@ use OCP\Defaults; use OCP\IRequest; use OCP\ISession; +use OCP\IUserSession; use OCP\Security\Bruteforce\IThrottler; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; @@ -28,10 +29,11 @@ class LegacyPublicAuth extends AbstractBasic { private ?IShare $share = null; public function __construct( - private IRequest $request, - private IManager $shareManager, - private ISession $session, - private IThrottler $throttler, + private readonly IRequest $request, + private readonly IManager $shareManager, + private readonly ISession $session, + private readonly IThrottler $throttler, + private readonly IUserSession $userSession, ) { // setup realm $defaults = new Defaults(); @@ -62,7 +64,7 @@ protected function validateUserPass($username, $password) { $this->share = $share; - \OC_User::setIncognitoMode(true); + $this->userSession->setIncognitoMode(true); // check if the share is password protected if ($share->getPassword() !== null) { diff --git a/apps/dav/lib/Connector/Sabre/PublicAuth.php b/apps/dav/lib/Connector/Sabre/PublicAuth.php index f8b19b36d6f63..ae6dd66e4d849 100644 --- a/apps/dav/lib/Connector/Sabre/PublicAuth.php +++ b/apps/dav/lib/Connector/Sabre/PublicAuth.php @@ -15,6 +15,7 @@ use OCP\IRequest; use OCP\ISession; use OCP\IURLGenerator; +use OCP\IUserSession; use OCP\Security\Bruteforce\IThrottler; use OCP\Security\Bruteforce\MaxDelayReached; use OCP\Share\Exceptions\ShareNotFound; @@ -42,12 +43,13 @@ class PublicAuth extends AbstractBasic { private ?IShare $share = null; public function __construct( - private IRequest $request, - private IManager $shareManager, - private ISession $session, - private IThrottler $throttler, - private LoggerInterface $logger, - private IURLGenerator $urlGenerator, + private readonly IRequest $request, + private readonly IManager $shareManager, + private readonly ISession $session, + private readonly IThrottler $throttler, + private readonly LoggerInterface $logger, + private readonly IURLGenerator $urlGenerator, + private readonly IUserSession $userSession, ) { // setup realm $defaults = new Defaults(); @@ -134,7 +136,7 @@ private function checkToken(): array { } $this->share = $share; - \OC_User::setIncognitoMode(true); + $this->userSession->setIncognitoMode(true); // If already authenticated if ($this->isShareInSession($share)) { @@ -172,7 +174,7 @@ protected function validateUserPass($username, $password) { return false; } - \OC_User::setIncognitoMode(true); + $this->userSession->setIncognitoMode(true); // check if the share is password protected if ($share->getPassword() !== null) { diff --git a/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php b/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php index 8fc54de645a2e..3f9d7dac831ec 100644 --- a/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php +++ b/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php @@ -9,9 +9,13 @@ namespace OCA\DAV\Tests\unit\Connector; use OCA\DAV\Connector\LegacyPublicAuth; +use OCP\Files\ISetupManager; use OCP\IRequest; use OCP\ISession; +use OCP\IUser; +use OCP\IUserSession; use OCP\Security\Bruteforce\IThrottler; +use OCP\Server; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; use OCP\Share\IShare; @@ -26,7 +30,7 @@ class LegacyPublicAuthTest extends TestCase { private IManager&MockObject $shareManager; private IThrottler&MockObject $throttler; private LegacyPublicAuth $auth; - private string|false $oldUser; + private ?IUser $oldUser; protected function setUp(): void { parent::setUp(); @@ -40,20 +44,21 @@ protected function setUp(): void { $this->request, $this->shareManager, $this->session, - $this->throttler + $this->throttler, + $this->createMock(IUserSession::class), ); // Store current user - $this->oldUser = \OC_User::getUser(); + $this->oldUser = Server::get(IUserSession::class)->getUser() ?? null; } protected function tearDown(): void { - \OC_User::setIncognitoMode(false); + Server::get(IUserSession::class)->setIncognitoMode(false); // Set old user - \OC_User::setUserId($this->oldUser ?: null); - if ($this->oldUser !== false) { - \OC_Util::setupFS($this->oldUser); + self::setUserId($this->oldUser?->getUID()); + if ($this->oldUser !== null) { + Server::get(ISetupManager::class)->setupForUser($this->oldUser); } parent::tearDown(); diff --git a/apps/dav/tests/unit/Connector/Sabre/PublicAuthTest.php b/apps/dav/tests/unit/Connector/Sabre/PublicAuthTest.php index 2f18b4305087e..136a6fb584aa0 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PublicAuthTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PublicAuthTest.php @@ -9,10 +9,14 @@ namespace OCA\DAV\Tests\unit\Connector; use OCA\DAV\Connector\Sabre\PublicAuth; +use OCP\Files\ISetupManager; use OCP\IRequest; use OCP\ISession; use OCP\IURLGenerator; +use OCP\IUser; +use OCP\IUserSession; use OCP\Security\Bruteforce\IThrottler; +use OCP\Server; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; use OCP\Share\IShare; @@ -35,8 +39,7 @@ class PublicAuthTest extends \Test\TestCase { private LoggerInterface&MockObject $logger; private IURLGenerator&MockObject $urlGenerator; private PublicAuth $auth; - - private bool|string $oldUser; + private ?IUser $oldUser; protected function setUp(): void { parent::setUp(); @@ -55,19 +58,20 @@ protected function setUp(): void { $this->throttler, $this->logger, $this->urlGenerator, + $this->createMock(IUserSession::class), ); // Store current user - $this->oldUser = \OC_User::getUser(); + $this->oldUser = Server::get(IUserSession::class)->getUser() ?? null; } protected function tearDown(): void { - \OC_User::setIncognitoMode(false); + Server::get(IUserSession::class)->setIncognitoMode(false); // Set old user - \OC_User::setUserId($this->oldUser); - if ($this->oldUser !== false) { - \OC_Util::setupFS($this->oldUser); + self::setUserId($this->oldUser?->getUID()); + if ($this->oldUser !== null) { + Server::get(ISetupManager::class)->setupForUser($this->oldUser); } parent::tearDown(); diff --git a/apps/federatedfilesharing/tests/TestCase.php b/apps/federatedfilesharing/tests/TestCase.php index 5132a2c8fd0d6..5c0718e640687 100644 --- a/apps/federatedfilesharing/tests/TestCase.php +++ b/apps/federatedfilesharing/tests/TestCase.php @@ -11,6 +11,7 @@ use OC\Files\Filesystem; use OC\Group\Database; use OCP\Files\IRootFolder; +use OCP\Files\ISetupManager; use OCP\IGroupManager; use OCP\IUserManager; use OCP\IUserSession; @@ -56,8 +57,9 @@ public static function tearDownAfterClass(): void { $user->delete(); } - \OC_Util::tearDownFS(); - \OC_User::setUserId(''); + $setupManager = Server::get(ISetupManager::class); + $setupManager->tearDown(); + self::setUserId(''); Filesystem::tearDown(); // reset backend @@ -69,13 +71,13 @@ public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); } - protected static function loginHelper(string $user, bool $create = false, bool $password = false) { + protected static function loginHelper(string $user, bool $create = false, bool $password = false): void { if ($password === false) { $password = $user; } + $userManager = Server::get(IUserManager::class); if ($create) { - $userManager = Server::get(IUserManager::class); $groupManager = Server::get(IGroupManager::class); $userObject = $userManager->createUser($user, $password); @@ -84,14 +86,16 @@ protected static function loginHelper(string $user, bool $create = false, bool $ if ($group && $userObject) { $group->addUser($userObject); } + } else { + $userObject = $userManager->get($user); } - \OC_Util::tearDownFS(); + $setupManager = Server::get(ISetupManager::class); + $setupManager->tearDown(); Server::get(IUserSession::class)->setUser(null); Filesystem::tearDown(); Server::get(IUserSession::class)->login($user, $password); Server::get(IRootFolder::class)->getUserFolder($user); - - \OC_Util::setupFS($user); + $setupManager->setupForUser($userObject); } } diff --git a/apps/files/tests/Service/TagServiceTest.php b/apps/files/tests/Service/TagServiceTest.php index 1b3e0898b334a..a31c80e242a84 100644 --- a/apps/files/tests/Service/TagServiceTest.php +++ b/apps/files/tests/Service/TagServiceTest.php @@ -41,7 +41,7 @@ protected function setUp(): void { $this->user = static::getUniqueID('user'); $this->activityManager = $this->createMock(IManager::class); Server::get(IUserManager::class)->createUser($this->user, 'test'); - \OC_User::setUserId($this->user); + self::setUserId($this->user); \OC_Util::setupFS($this->user); $user = $this->createMock(IUser::class); $this->userSession = $this->createMock(IUserSession::class); @@ -69,7 +69,7 @@ protected function getTagService(array $methods = []): TagService&MockObject { } protected function tearDown(): void { - \OC_User::setUserId(''); + self::setUserId(''); $user = Server::get(IUserManager::class)->get($this->user); if ($user !== null) { $user->delete(); diff --git a/apps/files_external/lib/Lib/Storage/SFTP.php b/apps/files_external/lib/Lib/Storage/SFTP.php index 6504ea610f345..059e1e5d42b30 100644 --- a/apps/files_external/lib/Lib/Storage/SFTP.php +++ b/apps/files_external/lib/Lib/Storage/SFTP.php @@ -17,6 +17,7 @@ use OCP\Constants; use OCP\Files\FileInfo; use OCP\Files\IMimeTypeDetector; +use OCP\IUserSession; use OCP\Server; use phpseclib\Net\SFTP\Stream; @@ -182,13 +183,12 @@ private function absPath(string $path): string { private function hostKeysPath(): string|false { try { - $userId = \OC_User::getUser(); - if ($userId === false) { + $user = Server::get(IUserSession::class)->getUser(); + if ($user === null) { return false; } - $view = new View('/' . $userId . '/files_external'); - + $view = new View('/' . $user->getUID() . '/files_external'); return $view->getLocalFile('ssh_hostKeys'); } catch (\Exception $e) { } diff --git a/apps/files_external/lib/Migration/DummyUserSession.php b/apps/files_external/lib/Migration/DummyUserSession.php index 1ebf0e1ec4f85..bd69a98ea5937 100644 --- a/apps/files_external/lib/Migration/DummyUserSession.php +++ b/apps/files_external/lib/Migration/DummyUserSession.php @@ -9,6 +9,7 @@ use OCP\IUser; use OCP\IUserSession; +use Override; class DummyUserSession implements IUserSession { @@ -54,4 +55,13 @@ public function getImpersonatingUserID() : ?string { public function setImpersonatingUserID(bool $useCurrentUser = true): void { //no OP } + + #[Override] + public function setIncognitoMode(bool $incognitoMode): void { + } + + #[Override] + public function isIncognitoMode(): bool { + return false; + } } diff --git a/apps/files_sharing/lib/Controller/ShareController.php b/apps/files_sharing/lib/Controller/ShareController.php index 0e0e98ef2d5ab..12681f16020b6 100644 --- a/apps/files_sharing/lib/Controller/ShareController.php +++ b/apps/files_sharing/lib/Controller/ShareController.php @@ -40,6 +40,7 @@ use OCP\ISession; use OCP\IURLGenerator; use OCP\IUserManager; +use OCP\IUserSession; use OCP\Security\Events\GenerateSecurePasswordEvent; use OCP\Security\ISecureRandom; use OCP\Security\PasswordContext; @@ -78,6 +79,7 @@ public function __construct( protected ISecureRandom $secureRandom, protected Defaults $defaults, private IPublicShareTemplateFactory $publicShareTemplateFactory, + private IUserSession $userSession, ) { parent::__construct($appName, $request, $session, $urlGenerator); } @@ -299,7 +301,7 @@ private function validateShare(IShare $share) { #[PublicPage] #[NoCSRFRequired] public function showShare($path = ''): TemplateResponse { - \OC_User::setIncognitoMode(true); + $this->userSession->setIncognitoMode(true); // Check whether share exists try { @@ -353,7 +355,7 @@ public function showShare($path = ''): TemplateResponse { #[NoCSRFRequired] #[NoSameSiteCookieRequired] public function downloadShare(string $token, ?string $files = null, string $path = ''): NotFoundResponse|RedirectResponse|DataResponse { - \OC_User::setIncognitoMode(true); + $this->userSession->setIncognitoMode(true); $share = $this->shareManager->getShareByToken($token); diff --git a/apps/files_sharing/lib/Updater.php b/apps/files_sharing/lib/Updater.php index 019542fa6bf9a..3d17d1ab61f87 100644 --- a/apps/files_sharing/lib/Updater.php +++ b/apps/files_sharing/lib/Updater.php @@ -14,8 +14,10 @@ use OCP\Files\Folder; use OCP\Files\Mount\IMountManager; use OCP\Files\NotFoundException; +use OCP\IUserSession; use OCP\Server; use OCP\Share\IShare; +use RuntimeException; class Updater { @@ -139,14 +141,18 @@ private static function moveShareInOrOutOfShare($path): void { * @param string $newPath new path relative to data/user/files */ private static function renameChildren($oldPath, $newPath) { - $absNewPath = Filesystem::normalizePath('/' . \OC_User::getUser() . '/files/' . $newPath); - $absOldPath = Filesystem::normalizePath('/' . \OC_User::getUser() . '/files/' . $oldPath); + $user = Server::get(IUserSession::class)->getUser(); + if ($user === null) { + throw new RuntimeException('Unable to find current user'); + } + $absNewPath = Filesystem::normalizePath('/' . $user->getUID() . '/files/' . $newPath); + $absOldPath = Filesystem::normalizePath('/' . $user->getUID() . '/files/' . $oldPath); $mountManager = Filesystem::getMountManager(); - $mountedShares = $mountManager->findIn('/' . \OC_User::getUser() . '/files/' . $oldPath); + $mountedShares = $mountManager->findIn('/' . $user->getUID() . '/files/' . $oldPath); foreach ($mountedShares as $mount) { /** @var MountPoint $mount */ - if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) { + if ($mount->getStorage()->instanceOfStorage(\OCP\Files\Storage\ISharedStorage::class)) { $mountPoint = $mount->getMountPoint(); $target = str_replace($absOldPath, $absNewPath, $mountPoint); $mount->moveMount($target); diff --git a/apps/files_sharing/tests/Controller/ShareControllerTest.php b/apps/files_sharing/tests/Controller/ShareControllerTest.php index 4e724a45a90f3..53d554f6e5598 100644 --- a/apps/files_sharing/tests/Controller/ShareControllerTest.php +++ b/apps/files_sharing/tests/Controller/ShareControllerTest.php @@ -42,6 +42,7 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; +use OCP\IUserSession; use OCP\Security\ISecureRandom; use OCP\Server; use OCP\Share\Exceptions\ShareNotFound; @@ -64,6 +65,7 @@ class ShareControllerTest extends \Test\TestCase { private IL10N&MockObject $l10n; private IConfig&MockObject $config; private ISession&MockObject $session; + private IUserSession&MockObject $userSession; private Defaults&MockObject $defaults; private IAppConfig&MockObject $appConfig; private Manager&MockObject $shareManager; @@ -85,6 +87,7 @@ protected function setUp(): void { $this->shareManager = $this->createMock(Manager::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->session = $this->createMock(ISession::class); + $this->userSession = $this->createMock(IUserSession::class); $this->previewManager = $this->createMock(IPreview::class); $this->config = $this->createMock(IConfig::class); $this->appConfig = $this->createMock(IAppConfig::class); @@ -141,6 +144,7 @@ protected function setUp(): void { $this->secureRandom, $this->defaults, $this->publicShareTemplateFactory, + $this->userSession, ); @@ -157,7 +161,7 @@ protected function setUp(): void { protected function tearDown(): void { \OC_Util::tearDownFS(); - \OC_User::setUserId(''); + self::setUserId(''); Filesystem::tearDown(); $user = Server::get(IUserManager::class)->get($this->user); if ($user !== null) { @@ -168,7 +172,7 @@ protected function tearDown(): void { Server::get(ISession::class)->set('public_link_authenticated', ''); // Set old user - \OC_User::setUserId($this->oldUser); + self::setUserId($this->oldUser); \OC_Util::setupFS($this->oldUser); parent::tearDown(); } diff --git a/apps/files_sharing/tests/TestCase.php b/apps/files_sharing/tests/TestCase.php index 6b72ecb259cab..d6d1d7a890780 100644 --- a/apps/files_sharing/tests/TestCase.php +++ b/apps/files_sharing/tests/TestCase.php @@ -18,6 +18,7 @@ use OCA\Files_Sharing\MountProvider; use OCP\Files\Config\IMountProviderCollection; use OCP\Files\IRootFolder; +use OCP\Files\ISetupManager; use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IUserManager; @@ -153,8 +154,8 @@ public static function tearDownAfterClass(): void { $group->delete(); } - \OC_Util::tearDownFS(); - \OC_User::setUserId(''); + Server::get(ISetupManager::class)->tearDown(); + self::setUserId(''); Filesystem::tearDown(); // reset backend diff --git a/apps/files_trashbin/lib/Trashbin.php b/apps/files_trashbin/lib/Trashbin.php index d578e14238672..46830ce7328ac 100644 --- a/apps/files_trashbin/lib/Trashbin.php +++ b/apps/files_trashbin/lib/Trashbin.php @@ -15,7 +15,6 @@ use OC\Files\Node\NonExistingFolder; use OC\Files\View; use OC\User\NoUserException; -use OC_User; use OCA\FederatedFileSharing\FederatedShareProvider; use OCA\Files_Trashbin\Command\Expire; use OCA\Files_Trashbin\Events\BeforeNodeRestoredEvent; @@ -47,6 +46,7 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; +use OCP\IUserSession; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; use OCP\Server; @@ -78,24 +78,27 @@ public static function ensureFileScannedHook(Node $node): void { * owners files folder * * @param string $filename - * @return array + * @return array{?string, ?string} * @throws NoUserException */ - public static function getUidAndFilename($filename) { + public static function getUidAndFilename(string $filename): array { $uid = Filesystem::getOwner($filename); $userManager = Server::get(IUserManager::class); - // if the user with the UID doesn't exists, e.g. because the UID points + // if the user with the UID doesn't exist, e.g. because the UID points // to a remote user with a federated cloud ID we use the current logged-in // user. We need a valid local user to move the file to the right trash bin + $user = Server::get(IUserSession::class)->getUser(); if (!$userManager->userExists($uid)) { - $uid = OC_User::getUser(); - } - if (!$uid) { - // no owner, usually because of share link from ext storage - return [null, null]; + if ($user === null) { + // no owner, usually because of share link from ext storage + return [null, null]; + } + $uid = $user->getUID(); } + $sessionUid = $user?->getUID(); + Filesystem::initMountPoints($uid); - if ($uid !== OC_User::getUser()) { + if ($uid !== $sessionUid) { $info = Filesystem::getFileInfo($filename); $ownerView = new View('/' . $uid . '/files'); try { @@ -396,20 +399,20 @@ private static function getConfiguredTrashbinSize(string $user): int|float { */ private static function retainVersions($filename, $owner, $ownerPath, $timestamp) { if (Server::get(IAppManager::class)->isEnabledForUser('files_versions') && !empty($ownerPath)) { - $user = OC_User::getUser(); + $user = Server::get(IUserSession::class)->getUser(); $rootView = new View('/'); if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) { - if ($owner !== $user) { + if ($owner !== $user->getUID()) { self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . static::getTrashFilename(basename($ownerPath), $timestamp), $rootView); } - self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . static::getTrashFilename($filename, $timestamp)); + self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user->getUID() . '/files_trashbin/versions/' . static::getTrashFilename($filename, $timestamp)); } elseif ($versions = Storage::getVersions($owner, $ownerPath)) { foreach ($versions as $v) { - if ($owner !== $user) { + if ($owner !== $user->getUID()) { self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . static::getTrashFilename($v['name'] . '.v' . $v['version'], $timestamp)); } - self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v['version'], $timestamp)); + self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user->getUID() . '/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v['version'], $timestamp)); } } } @@ -470,17 +473,17 @@ private static function copy(View $view, $source, $target) { * @return bool true on success, false otherwise */ public static function restore($file, $filename, $timestamp) { - $user = OC_User::getUser(); - if (!$user) { + $user = Server::get(IUserSession::class)->getUser(); + if ($user === null) { throw new \Exception('Tried to restore a file while not logged in'); } - $view = new View('/' . $user); + $view = new View('/' . $user->getUID()); $location = ''; if ($timestamp) { - $location = self::getLocation($user, $filename, $timestamp); + $location = self::getLocation($user->getUID(), $filename, $timestamp); if ($location === false) { - Server::get(LoggerInterface::class)->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']); + Server::get(LoggerInterface::class)->error('trash bin database inconsistent! ($user: ' . $user->getUID() . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']); } else { // if location no longer exists, restore file in the root directory if ($location !== '/' @@ -510,8 +513,8 @@ public static function restore($file, $filename, $timestamp) { $sourcePath = Filesystem::normalizePath($file); $targetPath = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename); - $sourceNode = self::getNodeForPath($user, $sourcePath); - $targetNode = self::getNodeForPath($user, $targetPath, 'files'); + $sourceNode = self::getNodeForPath($user->getUID(), $sourcePath); + $targetNode = self::getNodeForPath($user->getUID(), $targetPath, 'files'); $run = true; $event = new BeforeNodeRestoredEvent($sourceNode, $targetNode, $run); $dispatcher = Server::get(IEventDispatcher::class); @@ -526,13 +529,13 @@ public static function restore($file, $filename, $timestamp) { // handle the restore result if ($restoreResult) { $fakeRoot = $view->getRoot(); - $view->chroot('/' . $user . '/files'); + $view->chroot('/' . $user->getUID() . '/files'); $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); $view->chroot($fakeRoot); Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => $targetPath, 'trashPath' => $sourcePath]); - $sourceNode = self::getNodeForPath($user, $sourcePath); - $targetNode = self::getNodeForPath($user, $targetPath, 'files'); + $sourceNode = self::getNodeForPath($user->getUID(), $sourcePath); + $targetNode = self::getNodeForPath($user->getUID(), $targetPath, 'files'); $event = new NodeRestoredEvent($sourceNode, $targetNode); $dispatcher = Server::get(IEventDispatcher::class); $dispatcher->dispatchTyped($event); @@ -542,7 +545,7 @@ public static function restore($file, $filename, $timestamp) { if ($timestamp) { $query = Server::get(IDBConnection::class)->getQueryBuilder(); $query->delete('files_trash') - ->where($query->expr()->eq('user', $query->createNamedParameter($user))) + ->where($query->expr()->eq('user', $query->createNamedParameter($user->getUID()))) ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename))) ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp))); $query->executeStatement(); @@ -567,7 +570,7 @@ public static function restore($file, $filename, $timestamp) { */ private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) { if (Server::get(IAppManager::class)->isEnabledForUser('files_versions')) { - $user = OC_User::getUser(); + $user = Server::get(IUserSession::class)->getUser()->getUID(); $rootView = new View('/'); $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename); @@ -603,9 +606,9 @@ private static function restoreVersions(View $view, $file, $filename, $uniqueFil * delete all files from the trash */ public static function deleteAll() { - $user = OC_User::getUser(); - $userRoot = \OC::$server->getUserFolder($user)->getParent(); - $view = new View('/' . $user); + $user = Server::get(IUserSession::class)->getUser(); + $userRoot = Server::get(IRootFolder::class)->getUserFolder($user->getUID())->getParent(); + $view = new View('/' . $user->getUID()); $fileInfos = $view->getDirectoryContent('files_trashbin/files'); try { @@ -634,7 +637,7 @@ public static function deleteAll() { $query = Server::get(IDBConnection::class)->getQueryBuilder(); $query->delete('files_trash') - ->where($query->expr()->eq('user', $query->createNamedParameter($user))); + ->where($query->expr()->eq('user', $query->createNamedParameter($user->getUID()))); $query->executeStatement(); // Bulk PostDelete-Hook @@ -751,8 +754,8 @@ private static function deleteVersions(View $view, $file, $filename, $timestamp, * @return bool true if file exists, otherwise false */ public static function file_exists($filename, $timestamp = null) { - $user = OC_User::getUser(); - $view = new View('/' . $user); + $user = Server::get(IUserSession::class)->getUser(); + $view = new View('/' . $user->getUID()); if ($timestamp) { $filename = static::getTrashFilename($filename, $timestamp); diff --git a/apps/files_trashbin/tests/TrashbinTest.php b/apps/files_trashbin/tests/TrashbinTest.php index e34897330edd6..f7c6237cf1e5f 100644 --- a/apps/files_trashbin/tests/TrashbinTest.php +++ b/apps/files_trashbin/tests/TrashbinTest.php @@ -701,9 +701,9 @@ public static function loginHelper($user, $create = false) { } \OC_Util::tearDownFS(); - \OC_User::setUserId(''); + self::setUserId(''); Filesystem::tearDown(); - \OC_User::setUserId($user); + self::setUserId($user); \OC_Util::setupFS($user); Server::get(IRootFolder::class)->getUserFolder($user); } diff --git a/apps/files_versions/lib/Storage.php b/apps/files_versions/lib/Storage.php index fe9f91534fa01..70a19327b98db 100644 --- a/apps/files_versions/lib/Storage.php +++ b/apps/files_versions/lib/Storage.php @@ -15,7 +15,6 @@ use OC\Files\Search\SearchQuery; use OC\Files\View; use OC\User\NoUserException; -use OC_User; use OCA\Files_Sharing\SharedMount; use OCA\Files_Versions\AppInfo\Application; use OCA\Files_Versions\Command\Expire; @@ -25,11 +24,11 @@ use OCP\AppFramework\Db\DoesNotExistException; use OCP\Command\IBus; use OCP\EventDispatcher\IEventDispatcher; -use OCP\Files; use OCP\Files\FileInfo; use OCP\Files\Folder; use OCP\Files\IMimeTypeDetector; use OCP\Files\IRootFolder; +use OCP\Files\ISetupManager; use OCP\Files\Node; use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; @@ -41,6 +40,7 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; +use OCP\IUserSession; use OCP\Lock\ILockingProvider; use OCP\Server; use OCP\Util; @@ -93,10 +93,10 @@ public static function getUidAndFilename($filename) { // to a remote user with a federated cloud ID we use the current logged-in // user. We need a valid local user to create the versions if (!$userManager->userExists($uid)) { - $uid = OC_User::getUser(); + $uid = Server::get(IUserSession::class)->getUser()->getUID(); } Filesystem::initMountPoints($uid); - if ($uid !== OC_User::getUser()) { + if ($uid !== Server::get(IUserSession::class)->getUser()->getUID()) { $info = Filesystem::getFileInfo($filename); $ownerView = new View('/' . $uid . '/files'); try { @@ -853,7 +853,7 @@ public static function expire($filename, $uid) { throw new NoUserException('Backends provided no user object for ' . $uid); } - \OC_Util::setupFS($uid); + Server::get(ISetupManager::class)->setupForUser($user); try { if (!Filesystem::file_exists($filename)) { diff --git a/apps/files_versions/tests/VersioningTest.php b/apps/files_versions/tests/VersioningTest.php index fdc37016b5573..3022d5d1a173a 100644 --- a/apps/files_versions/tests/VersioningTest.php +++ b/apps/files_versions/tests/VersioningTest.php @@ -973,9 +973,9 @@ public static function loginHelper(string $user, bool $create = false) { } \OC_Util::tearDownFS(); - \OC_User::setUserId(''); + self::setUserId(''); Filesystem::tearDown(); - \OC_User::setUserId($user); + self::setUserId($user); \OC_Util::setupFS($user); \OC::$server->getUserFolder($user); } diff --git a/apps/settings/lib/Settings/Personal/PersonalInfo.php b/apps/settings/lib/Settings/Personal/PersonalInfo.php index 4f51b3a328367..1645f37760316 100644 --- a/apps/settings/lib/Settings/Personal/PersonalInfo.php +++ b/apps/settings/lib/Settings/Personal/PersonalInfo.php @@ -18,7 +18,9 @@ use OCP\App\IAppManager; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Services\IInitialState; +use OCP\Config\IUserConfig; use OCP\Files\FileInfo; +use OCP\Files\ISetupManager; use OCP\IConfig; use OCP\IGroup; use OCP\IGroupManager; @@ -36,7 +38,9 @@ class PersonalInfo implements ISettings { public function __construct( + private ?string $userId, private IConfig $config, + private IUserConfig $userConfig, private IUserManager $userManager, private IGroupManager $groupManager, private ITeamManager $teamManager, @@ -47,6 +51,7 @@ public function __construct( private IL10N $l, private IInitialState $initialStateService, private IManager $manager, + private ISetupManager $setupManager, ) { } @@ -60,12 +65,12 @@ public function getForm(): TemplateResponse { $lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled(); } - $uid = \OC_User::getUser(); - $user = $this->userManager->get($uid); + + $user = $this->userManager->get($this->userId); $account = $this->accountManager->getAccount($user); // make sure FS is setup before querying storage related stuff... - \OC_Util::setupFS($user->getUID()); + $this->setupManager->setupForUser($user); $storageInfo = \OC_Helper::getStorageInfo('/'); if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) { @@ -83,7 +88,7 @@ public function getForm(): TemplateResponse { ] + $messageParameters; $personalInfoParameters = [ - 'userId' => $uid, + 'userId' => $this->userId, 'avatar' => $this->getProperty($account, IAccountManager::PROPERTY_AVATAR), 'groups' => $this->getGroups($user), 'teams' => $this->getTeamMemberships($user), @@ -109,8 +114,8 @@ public function getForm(): TemplateResponse { 'headline' => $this->getProperty($account, IAccountManager::PROPERTY_HEADLINE), 'biography' => $this->getProperty($account, IAccountManager::PROPERTY_BIOGRAPHY), 'birthdate' => $this->getProperty($account, IAccountManager::PROPERTY_BIRTHDATE), - 'firstDayOfWeek' => $this->config->getUserValue($uid, 'core', AUserDataOCSController::USER_FIELD_FIRST_DAY_OF_WEEK), - 'timezone' => $this->config->getUserValue($uid, 'core', 'timezone', ''), + 'firstDayOfWeek' => $this->userConfig->getValueString($this->userId, 'core', AUserDataOCSController::USER_FIELD_FIRST_DAY_OF_WEEK), + 'timezone' => $this->userConfig->getValueString($this->userId, 'core', 'timezone'), 'pronouns' => $this->getProperty($account, IAccountManager::PROPERTY_PRONOUNS), ]; @@ -252,7 +257,7 @@ private function getLanguageMap(IUser $user): array { $uid = $user->getUID(); - $userConfLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage()); + $userConfLang = $this->userConfig->getValueString($uid, 'core', 'lang', $this->l10nFactory->findLanguage()); $languages = $this->l10nFactory->getLanguages(); // associate the user language with the proper array @@ -284,8 +289,8 @@ private function getLocaleMap(IUser $user): array { } $uid = $user->getUID(); - $userLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage()); - $userLocaleString = $this->config->getUserValue($uid, 'core', 'locale', $this->l10nFactory->findLocale($userLang)); + $userLang = $this->userConfig->getValueString($uid, 'core', 'lang', $this->l10nFactory->findLanguage()); + $userLocaleString = $this->userConfig->getValueString($uid, 'core', 'locale', $this->l10nFactory->findLocale($userLang)); $localeCodes = $this->l10nFactory->findAvailableLocales(); $userLocale = array_filter($localeCodes, fn ($value) => $userLocaleString === $value['code']); diff --git a/apps/settings/tests/Controller/AdminSettingsControllerTest.php b/apps/settings/tests/Controller/AdminSettingsControllerTest.php index ce4f983bbbd79..41081448ba77b 100644 --- a/apps/settings/tests/Controller/AdminSettingsControllerTest.php +++ b/apps/settings/tests/Controller/AdminSettingsControllerTest.php @@ -69,7 +69,7 @@ protected function setUp(): void { ); $user = Server::get(IUserManager::class)->createUser($this->adminUid, 'mylongrandompassword'); - \OC_User::setUserId($user->getUID()); + self::setUserId($user->getUID()); Server::get(IGroupManager::class)->createGroup('admin')->addUser($user); } @@ -77,7 +77,7 @@ protected function tearDown(): void { Server::get(IUserManager::class) ->get($this->adminUid) ->delete(); - \OC_User::setUserId(null); + self::setUserId(null); Server::get(IUserSession::class)->setUser(null); parent::tearDown(); diff --git a/apps/user_ldap/lib/Controller/RenewPasswordController.php b/apps/user_ldap/lib/Controller/RenewPasswordController.php index d3e89a12d5621..cf5f12b923304 100644 --- a/apps/user_ldap/lib/Controller/RenewPasswordController.php +++ b/apps/user_ldap/lib/Controller/RenewPasswordController.php @@ -17,7 +17,6 @@ use OCP\AppFramework\Services\IInitialState; use OCP\Config\IUserConfig; use OCP\HintException; -use OCP\IConfig; use OCP\IL10N; use OCP\IRequest; use OCP\ISession; @@ -31,7 +30,6 @@ public function __construct( string $appName, IRequest $request, private IUserManager $userManager, - private IConfig $config, private IUserConfig $userConfig, protected IL10N $l10n, private ISession $session, @@ -98,17 +96,24 @@ public function tryRenewPassword(?string $user, string $oldPassword, ?string $ne } try { - if (!is_null($newPassword) && \OC_User::setPassword($user, $newPassword)) { - $this->session->set('loginMessages', [ - [], [$this->l10n->t('Please login with the new password')] - ]); - $this->userConfig->setValueBool($user, 'user_ldap', 'needsPasswordReset', false); - return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)); - } else { - $this->session->set('renewPasswordMessages', [ - ['internalexception'], [] - ]); + if (is_null($newPassword)) { + throw new HintException('The new password is null or empty'); } + + $userObject = $this->userManager->get($user); + if ($userObject === null) { + throw new HintException('No user with the given user name exists'); + } + + if (!$userObject->setPassword($newPassword)) { + throw new HintException('Unable to change the password'); + } + + $this->session->set('loginMessages', [ + [], [$this->l10n->t('Please login with the new password')] + ]); + $this->userConfig->setValueBool($user, 'user_ldap', 'needsPasswordReset', false); + return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)); } catch (HintException $e) { $this->session->set('renewPasswordMessages', [ [], [$e->getHint()] diff --git a/build/psalm-baseline.xml b/build/psalm-baseline.xml index e67cf7160eac6..3ee9658c883fe 100644 --- a/build/psalm-baseline.xml +++ b/build/psalm-baseline.xml @@ -485,6 +485,12 @@ + + + + + + @@ -1360,11 +1366,11 @@ - + getUID() . '/files_external')]]> - + getUID() . '/files_external')]]> @@ -1728,7 +1734,6 @@ 'trashPath' => Filesystem::normalizePath(static::getTrashFilename($filename, $timestamp))])]]> $targetPath, 'trashPath' => $sourcePath])]]> - @@ -1740,9 +1745,9 @@ - - - + getUID())]]> + getUID())]]> + getUID())]]> @@ -1805,9 +1810,9 @@ - - - + getUID())]]> + getUID())]]> + getUID())]]> @@ -1928,9 +1933,6 @@ - - - @@ -2204,20 +2206,10 @@ - - getUID())]]> - - - - - - - - @@ -3012,6 +3004,14 @@ + + + urlGenerator)]]> + + + urlGenerator)]]> + + @@ -3899,9 +3899,12 @@ - - - + + + + + + diff --git a/core/ajax/update.php b/core/ajax/update.php index 0a882929537d9..e412acbddc932 100644 --- a/core/ajax/update.php +++ b/core/ajax/update.php @@ -21,6 +21,7 @@ use OCP\IConfig; use OCP\IEventSourceFactory; use OCP\IL10N; +use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Server; use OCP\Util; @@ -51,7 +52,7 @@ // if a user is currently logged in, their session must be ignored to // avoid side effects - \OC_User::setIncognitoMode(true); + Server::get(IUserSession::class)->setIncognitoMode(true); $config = Server::get(IConfig::class); $updater = Server::get(Updater::class); diff --git a/lib/base.php b/lib/base.php index a11334c50cfd7..cf947d8e57bb3 100644 --- a/lib/base.php +++ b/lib/base.php @@ -834,7 +834,7 @@ public static function init(): void { OC_User::setupBackends(); } else { // Run upgrades in incognito mode - OC_User::setIncognitoMode(true); + Server::get(IUserSession::class)->setIncognitoMode(true); } $eventLogger->end('setup_backends'); diff --git a/lib/private/AppFramework/DependencyInjection/DIContainer.php b/lib/private/AppFramework/DependencyInjection/DIContainer.php index 7527d2495863b..4df0c1c99b492 100644 --- a/lib/private/AppFramework/DependencyInjection/DIContainer.php +++ b/lib/private/AppFramework/DependencyInjection/DIContainer.php @@ -287,15 +287,6 @@ public function isLoggedIn() { return Server::get(IUserSession::class)->isLoggedIn(); } - /** - * @deprecated 12.0.0 use IGroupManager->isAdmin($userId) - * @return boolean - */ - public function isAdminUser() { - $uid = $this->getUserId(); - return \OC_User::isAdminUser($uid); - } - private function getUserId(): string { return $this->getServer()->get(Session::class)->getSession()->get('user_id'); } diff --git a/lib/private/DirectEditing/Manager.php b/lib/private/DirectEditing/Manager.php index bcb69163dbbab..709bf0329ef5f 100644 --- a/lib/private/DirectEditing/Manager.php +++ b/lib/private/DirectEditing/Manager.php @@ -25,6 +25,8 @@ use OCP\Files\NotFoundException; use OCP\IDBConnection; use OCP\IL10N; +use OCP\ISession; +use OCP\IUserManager; use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Security\ISecureRandom; @@ -239,8 +241,14 @@ public function accessToken(string $token): bool { return $result !== 0; } - public function invokeTokenScope($userId): void { - \OC_User::setUserId($userId); + public function invokeTokenScope(string $userId): void { + $userSession = Server::get(IUserSession::class); + $userManager = Server::get(IUserManager::class); + if ($user = $userManager->get($userId)) { + $userSession->setUser($user); + } else { + Server::get(ISession::class)->set('user_id', $userId); + } } public function revertTokenScope(): void { diff --git a/lib/private/Files/View.php b/lib/private/Files/View.php index 21265b7d0483b..605b952e077bf 100644 --- a/lib/private/Files/View.php +++ b/lib/private/Files/View.php @@ -1427,6 +1427,7 @@ public function getFileInfo($path, $includeMountPoints = true) { $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path); $mount = Filesystem::getMountManager()->find($path); + /** @var ?Storage $storage */ $storage = $mount->getStorage(); $internalPath = $mount->getInternalPath($path); if ($storage) { @@ -1502,6 +1503,7 @@ public function getDirectoryContent(string $directory, ?string $mimeTypeFilter = $path = $this->getAbsolutePath($directory); $path = Filesystem::normalizePath($path); $mount = $this->getMount($directory); + /** @var ?Storage $storage */ $storage = $mount->getStorage(); $internalPath = $mount->getInternalPath($path); if (!$storage) { diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index 811c5ba4bc326..05a4d31bf0f81 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -19,7 +19,6 @@ use OC\Hooks\PublicEmitter; use OC\Http\CookieHelper; use OC\Security\CSRF\CsrfTokenManager; -use OC_User; use OC_Util; use OCA\DAV\Connector\Sabre\Auth; use OCP\AppFramework\Db\TTransactional; @@ -73,6 +72,8 @@ class Session implements IUserSession, Emitter { /** @var User $activeUser */ protected $activeUser; + private bool $incognitoMode = false; + public function __construct( private Manager $manager, private ISession $session, @@ -170,10 +171,10 @@ public function setVolatileActiveUser(?IUser $user): void { * * @return IUser|null Current user, otherwise null */ - public function getUser() { + public function getUser(): ?IUser { // FIXME: This is a quick'n dirty work-around for the incognito mode as // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155 - if (OC_User::isIncognitoMode()) { + if ($this->isIncognitoMode()) { return null; } if (is_null($this->activeUser)) { @@ -1065,4 +1066,16 @@ public function updateSessionTokenPassword($password) { public function updateTokens(string $uid, string $password) { $this->tokenProvider->updatePasswords($uid, $password); } + + public function isIncognitoMode(): bool { + return $this->incognitoMode; + } + + /** + * Set whether the current session is in incognito mode or not. + * @since 34.0.0 + */ + public function setIncognitoMode(bool $incognitoMode): void { + $this->incognitoMode = $incognitoMode; + } } diff --git a/lib/private/legacy/OC_User.php b/lib/private/legacy/OC_User.php index df0740ef5d808..87315d55d530d 100644 --- a/lib/private/legacy/OC_User.php +++ b/lib/private/legacy/OC_User.php @@ -7,15 +7,17 @@ */ use OC\Authentication\Token\IProvider; use OC\SystemConfig; -use OC\User\Database; use OC\User\DisabledUserException; use OC\User\Session; +use OCP\App\IAppManager; use OCP\Authentication\Exceptions\InvalidTokenException; use OCP\Authentication\Exceptions\WipeTokenException; use OCP\Authentication\IApacheBackend; use OCP\Authentication\IProvideUserSecretBackend; use OCP\Authentication\Token\IToken; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\IRootFolder; +use OCP\Files\ISetupManager; use OCP\IGroupManager; use OCP\IRequest; use OCP\ISession; @@ -23,12 +25,12 @@ use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; +use OCP\L10N\IFactory; use OCP\Server; use OCP\Session\Exceptions\SessionNotAvailableException; use OCP\User\Backend\ICustomLogout; use OCP\User\Events\BeforeUserLoggedInEvent; use OCP\User\Events\UserLoggedInEvent; -use OCP\UserInterface; use OCP\Util; use Psr\Log\LoggerInterface; @@ -49,70 +51,28 @@ * pre_login(&run, uid, password) * post_login(uid) * logout() + * + * @deprecated 34.0.0 */ class OC_User { private static $_setupedBackends = []; - // bool, stores if a user want to access a resource anonymously, e.g if they open a public link - private static $incognitoMode = false; - /** - * Adds the backend to the list of used backends - * - * @param string|UserInterface $backend default: database The backend to use for user management - * @return bool - * @deprecated 32.0.0 Use IUserManager::registerBackend instead + * Set up the configured backends in config.php. * - * Set the User Authentication Module + * @suppress PhanDeprecatedFunction + * @deprecated 34.0.0 This is internal, not to be used by apps */ - public static function useBackend($backend = 'database') { - if ($backend instanceof UserInterface) { - Server::get(IUserManager::class)->registerBackend($backend); - } else { - // You'll never know what happens - if ($backend === null || !is_string($backend)) { - $backend = 'database'; - } - - // Load backend - switch ($backend) { - case 'database': - case 'mysql': - case 'sqlite': - Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']); - Server::get(IUserManager::class)->registerBackend(new Database()); - break; - case 'dummy': - Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); - break; - default: - Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']); - $className = 'OC_USER_' . strtoupper($backend); - Server::get(IUserManager::class)->registerBackend(new $className()); - break; - } + public static function setupBackends(): void { + if (!Server::get(SystemConfig::class)->getValue('installed', false)) { + return; } - return true; - } + Server::get(IAppManager::class)->loadApps(['prelogin']); - /** - * remove all used backends - * @deprecated 32.0.0 Use IUserManager::clearBackends instead - */ - public static function clearBackends() { - Server::get(IUserManager::class)->clearBackends(); - } - - /** - * setup the configured backends in config.php - * @suppress PhanDeprecatedFunction - */ - public static function setupBackends() { - OC_App::loadApps(['prelogin']); $backends = Server::get(SystemConfig::class)->getValue('user_backends', []); if (isset($backends['default']) && !$backends['default']) { // clear default backends - self::clearBackends(); + Server::get(IUserManager::class)->clearBackends(); } foreach ($backends as $i => $config) { if (!is_array($config)) { @@ -120,104 +80,111 @@ public static function setupBackends() { } $class = $config['class']; $arguments = $config['arguments']; - if (class_exists($class)) { - if (!in_array($i, self::$_setupedBackends)) { - // make a reflection object - $reflectionObj = new ReflectionClass($class); - - // use Reflection to create a new instance, using the $args - $backend = $reflectionObj->newInstanceArgs($arguments); - self::useBackend($backend); - self::$_setupedBackends[] = $i; - } else { - Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']); - } - } else { + if (!class_exists($class)) { Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']); } + if (in_array($i, self::$_setupedBackends)) { + Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']); + } + // make a reflection object + $reflectionObj = new ReflectionClass($class); + + // use Reflection to create a new instance, using the $args + $backend = $reflectionObj->newInstanceArgs($arguments); + Server::get(IUserManager::class)->registerBackend($backend); + self::$_setupedBackends[] = $i; } } /** - * Try to login a user, assuming authentication + * Try to log in a user, assuming authentication * has already happened (e.g. via Single Sign On). * * Log in a user and regenerate a new session. + * + * @deprecated 34.0.0 This is internal, not to be used by apps */ public static function loginWithApache(IApacheBackend $backend): bool { $uid = $backend->getCurrentUserId(); $run = true; OC_Hook::emit('OC_User', 'pre_login', ['run' => &$run, 'uid' => $uid, 'backend' => $backend]); - if ($uid) { - if (self::getUser() !== $uid) { - self::setUserId($uid); - /** @var Session $userSession */ - $userSession = Server::get(IUserSession::class); + if (!$uid) { + return false; + } - /** @var IEventDispatcher $dispatcher */ - $dispatcher = Server::get(IEventDispatcher::class); + $userSession = Server::get(IUserSession::class); + $userManager = Server::get(IUserManager::class); + $dispatcher = Server::get(IEventDispatcher::class); - if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) { - $message = \OC::$server->getL10N('lib')->t('Account disabled'); - throw new DisabledUserException($message); - } - $userSession->setLoginName($uid); - $request = Server::get(IRequest::class); - $password = null; - if ($backend instanceof IProvideUserSecretBackend) { - $password = $backend->getCurrentUserSecret(); - } + $user = $userSession->getUser(); + if ($user && $user->getUID() === $uid) { + return true; + } - /** @var IEventDispatcher $dispatcher */ - $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend)); - - $userSession->createSessionToken($request, $uid, $uid, $password); - $userSession->createRememberMeToken($userSession->getUser()); - - if (empty($password)) { - $tokenProvider = Server::get(IProvider::class); - try { - $token = $tokenProvider->getToken($userSession->getSession()->getId()); - $token->setScope([ - IToken::SCOPE_SKIP_PASSWORD_VALIDATION => true, - IToken::SCOPE_FILESYSTEM => true, - ]); - $tokenProvider->updateToken($token); - } catch (InvalidTokenException|WipeTokenException|SessionNotAvailableException) { - // swallow the exceptions as we do not deal with them here - // simply skip updating the token when is it missing - } - } + if ($user = $userManager->get($uid)) { + $userSession->setUser($user); + } else { + Server::get(ISession::class)->set('user_id', $uid); + } - // setup the filesystem - OC_Util::setupFS($uid); - // first call the post_login hooks, the login-process needs to be - // completed before we can safely create the users folder. - // For example encryption needs to initialize the users keys first - // before we can create the user folder with the skeleton files - OC_Hook::emit( - 'OC_User', - 'post_login', - [ - 'uid' => $uid, - 'password' => $password, - 'isTokenLogin' => false, - ] - ); - $dispatcher->dispatchTyped(new UserLoggedInEvent( - Server::get(IUserManager::class)->get($uid), - $uid, - null, - false) - ); - - //trigger creation of user home and /files folder - \OC::$server->getUserFolder($uid); + if (!$user->isEnabled()) { + $message = Server::get(IFactory::class)->get('lib')->t('Account disabled'); + throw new DisabledUserException($message); + } + + $userSession->setLoginName($uid); + $request = Server::get(IRequest::class); + $password = null; + if ($backend instanceof IProvideUserSecretBackend) { + $password = $backend->getCurrentUserSecret(); + } + + $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend)); + + $userSession->createSessionToken($request, $uid, $uid, $password); + $userSession->createRememberMeToken($user); + + if (empty($password)) { + $tokenProvider = Server::get(IProvider::class); + try { + $token = $tokenProvider->getToken($userSession->getSession()->getId()); + $token->setScope([ + IToken::SCOPE_SKIP_PASSWORD_VALIDATION => true, + IToken::SCOPE_FILESYSTEM => true, + ]); + $tokenProvider->updateToken($token); + } catch (InvalidTokenException|WipeTokenException|SessionNotAvailableException) { + // swallow the exceptions as we do not deal with them here + // simply skip updating the token when is it missing } - return true; } - return false; + + // Set up the filesystem + Server::get(ISetupManager::class)->setupForUser($user); + // first call the post_login hooks, the login-process needs to be + // completed before we can safely create the user's folder. + // For example encryption needs to initialize the users keys first + // before we can create the user folder with the skeleton files + OC_Hook::emit( + 'OC_User', + 'post_login', + [ + 'uid' => $uid, + 'password' => $password, + 'isTokenLogin' => false, + ] + ); + $dispatcher->dispatchTyped(new UserLoggedInEvent( + Server::get(IUserManager::class)->get($uid), + $uid, + null, + false) + ); + + // trigger creation of user home and /files folder + Server::get(IRootFolder::class)->getUserFolder($uid); + return true; } /** @@ -227,13 +194,15 @@ public static function loginWithApache(IApacheBackend $backend): bool { * true: authenticated * false: not authenticated * null: not handled / no backend available + * + * @deprecated 34.0.0 This is internal, not to be used by apps */ public static function handleApacheAuth(): ?bool { $backend = self::findFirstActiveUsedBackend(); if ($backend) { - OC_App::loadApps(); + Server::get(IAppManager::class)->loadApps(); - //setup extra user backends + // set up extra user backends self::setupBackends(); /** @var Session $session */ $session = Server::get(IUserSession::class); @@ -248,6 +217,7 @@ public static function handleApacheAuth(): ?bool { /** * Sets user id for session and triggers emit + * @deprecated 34.0.0 Use TestCase::setUserId in your test instead */ public static function setUserId(?string $uid): void { $userSession = Server::get(IUserSession::class); @@ -261,20 +231,23 @@ public static function setUserId(?string $uid): void { /** * Set incognito mode, e.g. if a user wants to open a public link + * @deprecated 34.0.0 Use IUserSession::setIncognitoMode */ public static function setIncognitoMode(bool $status): void { - self::$incognitoMode = $status; + Server::get(IUserSession::class)->setIncognitoMode($status); } /** * Get incognito mode status + * @deprecated 34.0.0 Use IUserSession::isIncognitoMode */ public static function isIncognitoMode(): bool { - return self::$incognitoMode; + return Server::get(IUserSession::class)->isIncognitoMode(); } /** * Returns the current logout URL valid for the currently logged-in user + * @deprecated 34.0.0 */ public static function getLogoutUrl(IURLGenerator $urlGenerator): string { $backend = self::findFirstActiveUsedBackend(); @@ -300,11 +273,12 @@ public static function getLogoutUrl(IURLGenerator $urlGenerator): string { * Check if the user is an admin user * * @param string $uid uid of the admin + * @deprecated 34.0.0 Use IGroupManager::isAdmin instead */ public static function isAdminUser(string $uid): bool { $user = Server::get(IUserManager::class)->get($uid); $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID()); - return $isAdmin && self::$incognitoMode === false; + return $isAdmin && !Server::get(IUserSession::class)->isIncognitoMode(); } @@ -312,10 +286,11 @@ public static function isAdminUser(string $uid): bool { * get the user id of the user currently logged in. * * @return string|false uid or false + * @deprecated 34.0.0 Use IUserSession::getUser instead */ public static function getUser(): string|false { $uid = Server::get(ISession::class)?->get('user_id'); - if (!is_null($uid) && self::$incognitoMode === false) { + if (!is_null($uid) && !Server::get(IUserSession::class)->isIncognitoMode()) { return $uid; } else { return false; diff --git a/lib/private/legacy/OC_Util.php b/lib/private/legacy/OC_Util.php index b3b0f4e3e20ca..ceec426b21cc7 100644 --- a/lib/private/legacy/OC_Util.php +++ b/lib/private/legacy/OC_Util.php @@ -572,7 +572,11 @@ public static function checkLoggedIn(): void { */ public static function checkAdminUser(): void { self::checkLoggedIn(); - if (!OC_User::isAdminUser(OC_User::getUser())) { + + $user = Server::get(IUserSession::class)->getUser(); + $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID()); + + if (!$isAdmin) { header('Location: ' . Util::linkToAbsolute('', 'index.php')); exit(); } diff --git a/lib/public/IUserSession.php b/lib/public/IUserSession.php index 42cc437aabae1..cfc23715d4b26 100644 --- a/lib/public/IUserSession.php +++ b/lib/public/IUserSession.php @@ -92,4 +92,16 @@ public function getImpersonatingUserID(): ?string; * @since 18.0.0 */ public function setImpersonatingUserID(bool $useCurrentUser = true): void; + + /** + * Returns whether the current session is in incognito mode. + * @since 34.0.0 + */ + public function isIncognitoMode(): bool; + + /** + * Set whether the current session is in incognito mode or not. + * @since 34.0.0 + */ + public function setIncognitoMode(bool $incognitoMode): void; } diff --git a/public.php b/public.php index 8ae6deff20305..b190a61333a10 100644 --- a/public.php +++ b/public.php @@ -15,6 +15,7 @@ use OCP\App\IAppManager; use OCP\IConfig; use OCP\IRequest; +use OCP\IUserSession; use OCP\Server; use OCP\Template\ITemplateManager; use OCP\Util; @@ -84,7 +85,8 @@ function resolveService(string $service): string { // Load the app $appManager->loadApp($app); - OC_User::setIncognitoMode(true); + $userSession = Server::get(IUserSession::class); + $userSession->setIncognitoMode(true); $baseuri = OC::$WEBROOT . '/public.php/' . $service . '/'; require_once $file; diff --git a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php index 4fbe5c8307ba4..4f1a583808394 100644 --- a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php +++ b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php @@ -20,18 +20,14 @@ use OCP\AppFramework\QueryException; use OCP\IConfig; use OCP\IRequestId; -use PHPUnit\Framework\MockObject\MockObject; #[\PHPUnit\Framework\Attributes\Group('DB')] class DIContainerTest extends \Test\TestCase { - private DIContainer&MockObject $container; + private DIContainer $container; protected function setUp(): void { parent::setUp(); - $this->container = $this->getMockBuilder(DIContainer::class) - ->onlyMethods(['isAdminUser']) - ->setConstructorArgs(['name']) - ->getMock(); + $this->container = new DIContainer('name'); } diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php index 83944ce2f7eb2..0b43e7fffa4b8 100644 --- a/tests/lib/AppTest.php +++ b/tests/lib/AppTest.php @@ -199,7 +199,7 @@ public function testEnabledApps($user, $expectedApps, $forceAll): void { $group2->addUser($user2); $group2->addUser($user3); - \OC_User::setUserId($user); + self::setUserId($user); $this->setupAppConfigMock()->expects($this->once()) ->method('searchValues') @@ -217,7 +217,7 @@ public function testEnabledApps($user, $expectedApps, $forceAll): void { $apps = \OC_App::getEnabledApps(false, $forceAll); $this->restoreAppConfig(); - \OC_User::setUserId(null); + self::setUserId(null); $user1->delete(); $user2->delete(); @@ -237,7 +237,7 @@ public function testEnabledAppsCache(): void { $userManager = Server::get(IUserManager::class); $user1 = $userManager->createUser(self::TEST_USER1, 'NotAnEasyPassword123456+'); - \OC_User::setUserId(self::TEST_USER1); + self::setUserId(self::TEST_USER1); $this->setupAppConfigMock()->expects($this->once()) ->method('searchValues') @@ -256,7 +256,7 @@ public function testEnabledAppsCache(): void { $this->assertEquals(['files', 'app3', 'cloud_federation_api', 'dav', 'federatedfilesharing', 'lookup_server_connector', 'oauth2', 'profile', 'provisioning_api', 'settings', 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine'], $apps); $this->restoreAppConfig(); - \OC_User::setUserId(null); + self::setUserId(null); $user1->delete(); } diff --git a/tests/lib/Cache/FileCacheTest.php b/tests/lib/Cache/FileCacheTest.php index 9ba19553cf134..98ef96fa033de 100644 --- a/tests/lib/Cache/FileCacheTest.php +++ b/tests/lib/Cache/FileCacheTest.php @@ -59,7 +59,7 @@ protected function setUp(): void { $this->createUser('test', 'test'); $this->user = \OC_User::getUser(); - \OC_User::setUserId('test'); + self::setUserId('test'); //clear all proxies and hooks so we can do clean testing \OC_Hook::clear('OC_Filesystem'); @@ -86,7 +86,7 @@ protected function tearDown(): void { $this->instance->remove('hack', 'hack'); } - \OC_User::setUserId($this->user); + self::setUserId($this->user); if ($this->instance) { $this->instance->clear(); diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php index 94d55b4e9c411..1ad42ae76bfa3 100644 --- a/tests/lib/Files/ViewTest.php +++ b/tests/lib/Files/ViewTest.php @@ -147,7 +147,7 @@ protected function setUp(): void { } protected function tearDown(): void { - \OC_User::setUserId($this->user); + self::setUserId($this->user); foreach ($this->storages as $storage) { $cache = $storage->getCache(); $ids = $cache->getAll(); diff --git a/tests/lib/HelperStorageTest.php b/tests/lib/HelperStorageTest.php index 914936c9657ad..2f0bf31e5e9bf 100644 --- a/tests/lib/HelperStorageTest.php +++ b/tests/lib/HelperStorageTest.php @@ -40,7 +40,7 @@ protected function setUp(): void { $this->savedQuotaIncludeExternalStorage = $this->getIncludeExternalStorage(); Filesystem::tearDown(); - \OC_User::setUserId($this->user); + self::setUserId($this->user); Filesystem::init($this->user, '/' . $this->user . '/files'); /** @var IMountManager $manager */ @@ -60,7 +60,7 @@ protected function tearDown(): void { } Filesystem::tearDown(); - \OC_User::setUserId(''); + self::setUserId(''); Server::get(IConfig::class)->deleteAllUserValues($this->user); parent::tearDown(); diff --git a/tests/lib/Security/CertificateManagerTest.php b/tests/lib/Security/CertificateManagerTest.php index 04262b62818cb..2dcd83d03f0a6 100644 --- a/tests/lib/Security/CertificateManagerTest.php +++ b/tests/lib/Security/CertificateManagerTest.php @@ -45,7 +45,7 @@ protected function setUp(): void { $this->registerMount($this->username, $storage, '/' . $this->username . '/'); \OC_Util::tearDownFS(); - \OC_User::setUserId($this->username); + self::setUserId($this->username); Filesystem::tearDown(); \OC_Util::setupFS($this->username); diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php index 1827870ca6e21..1d580d1f2bf12 100644 --- a/tests/lib/TagsTest.php +++ b/tests/lib/TagsTest.php @@ -46,7 +46,7 @@ protected function setUp(): void { Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); $userId = $this->getUniqueID('user_'); Server::get(IUserManager::class)->createUser($userId, 'pass'); - \OC_User::setUserId($userId); + self::setUserId($userId); $this->user = $this->createMock(IUser::class); $this->user->method('getUID') ->willReturn($userId); diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index c40c05b3de773..92e53c37b5cc8 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -29,6 +29,7 @@ use OCP\Files\IRootFolder; use OCP\IConfig; use OCP\IDBConnection; +use OCP\ISession; use OCP\IUserManager; use OCP\IUserSession; use OCP\Lock\ILockingProvider; @@ -426,7 +427,7 @@ protected static function tearDownAfterClassCleanStrayLocks(): void { protected static function loginAsUser(string $user = ''): void { self::logout(); Filesystem::tearDown(); - \OC_User::setUserId($user); + self::setUserId($user); $userManager = Server::get(IUserManager::class); $setupManager = Server::get(SetupManager::class); $userObject = $userManager->get($user); @@ -533,4 +534,15 @@ protected function IsDatabaseAccessAllowed(): bool { $annotations = $this->getGroupAnnotations(); return in_array('DB', $annotations) || in_array('SLOWDB', $annotations); } + + + protected static function setUserId(?string $uid): void { + $userSession = Server::get(IUserSession::class); + $userManager = Server::get(IUserManager::class); + if ($user = $userManager->get($uid)) { + $userSession->setUser($user); + } else { + Server::get(ISession::class)->set('user_id', $uid); + } + } } diff --git a/tests/lib/Traits/EncryptionTrait.php b/tests/lib/Traits/EncryptionTrait.php index 2dc9213ff2431..a5f7f91a10ae4 100644 --- a/tests/lib/Traits/EncryptionTrait.php +++ b/tests/lib/Traits/EncryptionTrait.php @@ -17,6 +17,7 @@ use OCA\Encryption\Users\Setup; use OCP\App\IAppManager; use OCP\Encryption\IManager; +use OCP\Files\IRootFolder; use OCP\IConfig; use OCP\IUserManager; use OCP\IUserSession; @@ -53,19 +54,21 @@ abstract protected static function assertTrue($condition, string $message = ''): */ private $encryptionApp; - protected function loginWithEncryption($user = '') { - \OC_Util::tearDownFS(); - \OC_User::setUserId(''); + protected function loginWithEncryption(string $user = ''): void { + $this->setupManager->tearDown(); + self::setUserId(''); + // needed for fully logout - Server::get(IUserSession::class)->setUser(null); + $userSession = Server::get(IUserSession::class); + $userSession->setUser(null); $this->setupManager->tearDown(); - \OC_User::setUserId($user); + self::setUserId($user); $this->postLogin(); - \OC_Util::setupFS($user); if ($this->userManager->userExists($user)) { - \OC::$server->getUserFolder($user); + $this->setupManager->setupForUser($this->userManager->get($user)); + Server::get(IRootFolder::class)->getUserFolder($user); } } diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index 84d5bc898a057..2845979794e83 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -102,7 +102,7 @@ protected function setUp(): void { ]) ->getMock(); - \OC_User::setIncognitoMode(false); + $this->userSession->setIncognitoMode(false); } public static function isLoggedInData(): array {