Compare commits

...

2 Commits

Author SHA1 Message Date
Carl Schwan d89fdb454d refactor: Deprecate and remove large part of OC_User
And replace most usages in Server with the newer APIs

Signed-off-by: Carl Schwan <carlschwan@kde.org>
2026-03-10 18:24:43 +01:00
Carl Schwan 02810c118a refactor(user): Replace all usage of OC_User::setPassword
And deprecated OC_User::setPassword

Signed-off-by: Carl Schwan <carlschwan@kde.org>
2026-03-10 15:40:03 +01:00
43 changed files with 418 additions and 334 deletions
+2 -1
View File
@@ -47,7 +47,8 @@ $authBackend = new LegacyPublicAuth(
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);
+1
View File
@@ -64,6 +64,7 @@ $authBackend = new PublicAuth(
Server::get(IThrottler::class),
Server::get(LoggerInterface::class),
Server::get(IURLGenerator::class),
Server::get(IUserSession::class),
);
$authPlugin = new \Sabre\DAV\Auth\Plugin($authBackend);
+7 -5
View File
@@ -11,6 +11,7 @@ use OCA\DAV\Connector\Sabre\PublicAuth;
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 @@ class LegacyPublicAuth extends AbstractBasic {
$this->share = $share;
\OC_User::setIncognitoMode(true);
$this->userSession->setIncognitoMode(true);
// check if the share is password protected
if ($share->getPassword() !== null) {
+10 -8
View File
@@ -15,6 +15,7 @@ use OCP\Defaults;
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 @@ class PublicAuth extends AbstractBasic {
}
$this->share = $share;
\OC_User::setIncognitoMode(true);
$this->userSession->setIncognitoMode(true);
// If already authenticated
if ($this->isShareInSession($share)) {
@@ -172,7 +174,7 @@ class PublicAuth extends AbstractBasic {
return false;
}
\OC_User::setIncognitoMode(true);
$this->userSession->setIncognitoMode(true);
// check if the share is password protected
if ($share->getPassword() !== null) {
@@ -9,9 +9,13 @@ declare(strict_types=1);
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 @@ class LegacyPublicAuthTest extends TestCase {
$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();
@@ -9,10 +9,14 @@ declare(strict_types=1);
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 @@ class PublicAuthTest extends \Test\TestCase {
$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();
+11 -7
View File
@@ -11,6 +11,7 @@ namespace OCA\FederatedFileSharing\Tests;
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 @@ abstract class TestCase extends \Test\TestCase {
$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 @@ abstract class TestCase extends \Test\TestCase {
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 @@ abstract class TestCase extends \Test\TestCase {
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);
}
}
+2 -2
View File
@@ -41,7 +41,7 @@ class TagServiceTest extends \Test\TestCase {
$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 @@ class TagServiceTest extends \Test\TestCase {
}
protected function tearDown(): void {
\OC_User::setUserId('');
self::setUserId('');
$user = Server::get(IUserManager::class)->get($this->user);
if ($user !== null) {
$user->delete();
+4 -4
View File
@@ -17,6 +17,7 @@ use OCP\Cache\CappedMemoryCache;
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 @@ class SFTP extends Common {
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) {
}
@@ -9,6 +9,7 @@ namespace OCA\Files_External\Migration;
use OCP\IUser;
use OCP\IUserSession;
use Override;
class DummyUserSession implements IUserSession {
@@ -54,4 +55,13 @@ class DummyUserSession implements IUserSession {
public function setImpersonatingUserID(bool $useCurrentUser = true): void {
//no OP
}
#[Override]
public function setIncognitoMode(bool $incognitoMode): void {
}
#[Override]
public function isIncognitoMode(): bool {
return false;
}
}
@@ -40,6 +40,7 @@ use OCP\IRequest;
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 @@ class ShareController extends AuthPublicShareController {
protected ISecureRandom $secureRandom,
protected Defaults $defaults,
private IPublicShareTemplateFactory $publicShareTemplateFactory,
private IUserSession $userSession,
) {
parent::__construct($appName, $request, $session, $urlGenerator);
}
@@ -299,7 +301,7 @@ class ShareController extends AuthPublicShareController {
#[PublicPage]
#[NoCSRFRequired]
public function showShare($path = ''): TemplateResponse {
\OC_User::setIncognitoMode(true);
$this->userSession->setIncognitoMode(true);
// Check whether share exists
try {
@@ -353,7 +355,7 @@ class ShareController extends AuthPublicShareController {
#[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);
+10 -4
View File
@@ -14,8 +14,10 @@ use OCP\Constants;
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 @@ class Updater {
* @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);
@@ -42,6 +42,7 @@ use OCP\ISession;
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 @@ class ShareControllerTest extends \Test\TestCase {
$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 @@ class ShareControllerTest extends \Test\TestCase {
$this->secureRandom,
$this->defaults,
$this->publicShareTemplateFactory,
$this->userSession,
);
@@ -157,7 +161,7 @@ class ShareControllerTest extends \Test\TestCase {
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 @@ class ShareControllerTest extends \Test\TestCase {
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();
}
+3 -2
View File
@@ -18,6 +18,7 @@ use OCA\Files_Sharing\External\MountProvider as ExternalMountProvider;
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 @@ abstract class TestCase extends \Test\TestCase {
$group->delete();
}
\OC_Util::tearDownFS();
\OC_User::setUserId('');
Server::get(ISetupManager::class)->tearDown();
self::setUserId('');
Filesystem::tearDown();
// reset backend
+36 -33
View File
@@ -15,7 +15,6 @@ use OC\Files\Node\NonExistingFile;
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\IRequest;
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 @@ class Trashbin implements IEventListener {
* 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 @@ class Trashbin implements IEventListener {
*/
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 @@ class Trashbin implements IEventListener {
* @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 @@ class Trashbin implements IEventListener {
$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 @@ class Trashbin implements IEventListener {
// 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 @@ class Trashbin implements IEventListener {
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 @@ class Trashbin implements IEventListener {
*/
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 @@ class Trashbin implements IEventListener {
* 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 @@ class Trashbin implements IEventListener {
$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 @@ class Trashbin implements IEventListener {
* @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);
+2 -2
View File
@@ -701,9 +701,9 @@ class TrashbinTest extends \Test\TestCase {
}
\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);
}
+5 -5
View File
@@ -15,7 +15,6 @@ use OC\Files\Search\SearchComparison;
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 OCA\Files_Versions\Versions\IVersionManager;
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\Files\StorageNotAvailableException;
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 @@ class Storage {
// 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 @@ class Storage {
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)) {
+2 -2
View File
@@ -973,9 +973,9 @@ class VersioningTest extends \Test\TestCase {
}
\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);
}
@@ -18,7 +18,9 @@ use OCP\Accounts\IAccountProperty;
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 @@ use OCP\Util;
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 @@ class PersonalInfo implements ISettings {
private IL10N $l,
private IInitialState $initialStateService,
private IManager $manager,
private ISetupManager $setupManager,
) {
}
@@ -60,12 +65,12 @@ class PersonalInfo implements ISettings {
$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 @@ class PersonalInfo implements ISettings {
] + $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 @@ class PersonalInfo implements ISettings {
'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 @@ class PersonalInfo implements ISettings {
$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 @@ class PersonalInfo implements ISettings {
}
$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']);
@@ -69,7 +69,7 @@ class AdminSettingsControllerTest extends TestCase {
);
$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 @@ class AdminSettingsControllerTest extends TestCase {
Server::get(IUserManager::class)
->get($this->adminUid)
->delete();
\OC_User::setUserId(null);
self::setUserId(null);
Server::get(IUserSession::class)->setUser(null);
parent::tearDown();
@@ -17,7 +17,6 @@ use OCP\AppFramework\Http\TemplateResponse;
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 @@ class RenewPasswordController extends Controller {
string $appName,
IRequest $request,
private IUserManager $userManager,
private IConfig $config,
private IUserConfig $userConfig,
protected IL10N $l10n,
private ISession $session,
@@ -98,17 +96,24 @@ class RenewPasswordController extends Controller {
}
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()]
+15 -9
View File
@@ -1238,9 +1238,11 @@ class User_LDAPTest extends TestCase {
->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 @@ class User_LDAPTest extends TestCase {
->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 @@ class User_LDAPTest extends TestCase {
$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$'));
}
+28 -25
View File
@@ -485,6 +485,12 @@
</InvalidNullableReturnType>
</file>
<file src="apps/dav/lib/Connector/Sabre/Auth.php">
<DeprecatedClass>
<code><![CDATA[\OC_User::handleApacheAuth()]]></code>
</DeprecatedClass>
<DeprecatedMethod>
<code><![CDATA[\OC_User::handleApacheAuth()]]></code>
</DeprecatedMethod>
<LessSpecificReturnStatement>
<code><![CDATA[$data]]></code>
</LessSpecificReturnStatement>
@@ -1360,11 +1366,11 @@
</file>
<file src="apps/files_external/lib/Lib/Storage/SFTP.php">
<InternalClass>
<code><![CDATA[new View('/' . $userId . '/files_external')]]></code>
<code><![CDATA[new View('/' . $user->getUID() . '/files_external')]]></code>
</InternalClass>
<InternalMethod>
<code><![CDATA[getLocalFile]]></code>
<code><![CDATA[new View('/' . $userId . '/files_external')]]></code>
<code><![CDATA[new View('/' . $user->getUID() . '/files_external')]]></code>
<code><![CDATA[put]]></code>
</InternalMethod>
</file>
@@ -1728,7 +1734,6 @@
'trashPath' => Filesystem::normalizePath(static::getTrashFilename($filename, $timestamp))])]]></code>
<code><![CDATA[Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => $targetPath, 'trashPath' => $sourcePath])]]></code>
<code><![CDATA[getUserFolder]]></code>
<code><![CDATA[getUserFolder]]></code>
</DeprecatedMethod>
<InternalClass>
<code><![CDATA[new View('/' . $owner)]]></code>
@@ -1740,9 +1745,9 @@
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user->getUID())]]></code>
<code><![CDATA[new View('/' . $user->getUID())]]></code>
<code><![CDATA[new View('/' . $user->getUID())]]></code>
<code><![CDATA[new View('/')]]></code>
<code><![CDATA[new View('/')]]></code>
<code><![CDATA[new View('/')]]></code>
@@ -1805,9 +1810,9 @@
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user)]]></code>
<code><![CDATA[new View('/' . $user->getUID())]]></code>
<code><![CDATA[new View('/' . $user->getUID())]]></code>
<code><![CDATA[new View('/' . $user->getUID())]]></code>
<code><![CDATA[new View('/')]]></code>
<code><![CDATA[new View('/')]]></code>
<code><![CDATA[new View('/')]]></code>
@@ -1928,9 +1933,6 @@
</InvalidNullableReturnType>
</file>
<file src="apps/files_versions/lib/Storage.php">
<DeprecatedClass>
<code><![CDATA[\OC_Util::setupFS($uid)]]></code>
</DeprecatedClass>
<DeprecatedInterface>
<code><![CDATA[$bus]]></code>
</DeprecatedInterface>
@@ -2204,20 +2206,10 @@
</DeprecatedMethod>
</file>
<file src="apps/settings/lib/Settings/Personal/PersonalInfo.php">
<DeprecatedClass>
<code><![CDATA[\OC_Util::setupFS($user->getUID())]]></code>
</DeprecatedClass>
<DeprecatedConstant>
<code><![CDATA[IAccountManager::PROPERTY_TWITTER]]></code>
<code><![CDATA[IAccountManager::PROPERTY_TWITTER]]></code>
</DeprecatedConstant>
<DeprecatedMethod>
<code><![CDATA[getUserValue]]></code>
<code><![CDATA[getUserValue]]></code>
<code><![CDATA[getUserValue]]></code>
<code><![CDATA[getUserValue]]></code>
<code><![CDATA[getUserValue]]></code>
</DeprecatedMethod>
</file>
<file src="apps/settings/lib/Settings/Personal/Security/Authtokens.php">
<DeprecatedClass>
@@ -3012,6 +3004,14 @@
<code><![CDATA[private]]></code>
</DeprecatedInterface>
</file>
<file src="core/Controller/TwoFactorChallengeController.php">
<DeprecatedClass>
<code><![CDATA[OC_User::getLogoutUrl($this->urlGenerator)]]></code>
</DeprecatedClass>
<DeprecatedMethod>
<code><![CDATA[OC_User::getLogoutUrl($this->urlGenerator)]]></code>
</DeprecatedMethod>
</file>
<file src="core/Controller/UnifiedSearchController.php">
<DeprecatedInterface>
<code><![CDATA[private]]></code>
@@ -3899,9 +3899,12 @@
</UndefinedInterfaceMethod>
</file>
<file src="lib/private/legacy/OC_User.php">
<UndefinedClass>
<code><![CDATA[\Test\Util\User\Dummy]]></code>
</UndefinedClass>
<UndefinedInterfaceMethod>
<code><![CDATA[createRememberMeToken]]></code>
<code><![CDATA[createSessionToken]]></code>
<code><![CDATA[getSession]]></code>
<code><![CDATA[setLoginName]]></code>
</UndefinedInterfaceMethod>
</file>
<file src="lib/public/AppFramework/Http/Response.php">
<LessSpecificReturnStatement>
+2 -1
View File
@@ -21,6 +21,7 @@ use OCP\EventDispatcher\IEventDispatcher;
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 (Util::needUpgrade()) {
// 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);
+1 -1
View File
@@ -834,7 +834,7 @@ class OC {
OC_User::setupBackends();
} else {
// Run upgrades in incognito mode
OC_User::setIncognitoMode(true);
Server::get(IUserSession::class)->setIncognitoMode(true);
}
$eventLogger->end('setup_backends');
@@ -287,15 +287,6 @@ class DIContainer extends SimpleContainer implements IAppContainer {
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');
}
+10 -2
View File
@@ -25,6 +25,8 @@ use OCP\Files\Node;
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 @@ class Manager implements IManager {
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 {
+2
View File
@@ -1427,6 +1427,7 @@ class View {
$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 @@ class View {
$path = $this->getAbsolutePath($directory);
$path = Filesystem::normalizePath($path);
$mount = $this->getMount($directory);
/** @var ?Storage $storage */
$storage = $mount->getStorage();
$internalPath = $mount->getInternalPath($path);
if (!$storage) {
+16 -3
View File
@@ -19,7 +19,6 @@ use OC\Hooks\Emitter;
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 @@ class Session implements IUserSession, Emitter {
*
* @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 @@ class Session implements IUserSession, Emitter {
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;
}
}
+116 -140
View File
@@ -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\IURLGenerator;
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 @@ use Psr\Log\LoggerInterface;
* 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
* Set up the configured backends in config.php.
*
* @param string|UserInterface $backend default: database The backend to use for user management
* @return bool
* @deprecated 32.0.0 Use IUserManager::registerBackend instead
*
* Set the User Authentication Module
*/
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;
}
}
return true;
}
/**
* 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
* @deprecated 34.0.0 This is internal, not to be used by apps
*/
public static function setupBackends() {
OC_App::loadApps(['prelogin']);
public static function setupBackends(): void {
if (!Server::get(SystemConfig::class)->getValue('installed', false)) {
return;
}
Server::get(IAppManager::class)->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 @@ class OC_User {
}
$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();
}
/** @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
}
}
// 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);
}
$user = $userSession->getUser();
if ($user && $user->getUID() === $uid) {
return true;
}
return false;
if ($user = $userManager->get($uid)) {
$userSession->setUser($user);
} else {
Server::get(ISession::class)->set('user_id', $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
}
}
// 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 @@ class OC_User {
* 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 @@ class OC_User {
/**
* 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 @@ class OC_User {
/**
* 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 @@ class OC_User {
* 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 @@ class OC_User {
* 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;
@@ -330,6 +305,7 @@ class OC_User {
* @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);
+5 -1
View File
@@ -572,7 +572,11 @@ class OC_Util {
*/
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();
}
+12
View File
@@ -92,4 +92,16 @@ interface IUserSession {
* @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;
}
+3 -1
View File
@@ -15,6 +15,7 @@ require_once __DIR__ . '/lib/versioncheck.php';
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 @@ try {
// 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;
@@ -20,18 +20,14 @@ use OCP\AppFramework\Middleware;
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');
}
+4 -4
View File
@@ -199,7 +199,7 @@ class AppTest extends \Test\TestCase {
$group2->addUser($user2);
$group2->addUser($user3);
\OC_User::setUserId($user);
self::setUserId($user);
$this->setupAppConfigMock()->expects($this->once())
->method('searchValues')
@@ -217,7 +217,7 @@ class AppTest extends \Test\TestCase {
$apps = \OC_App::getEnabledApps(false, $forceAll);
$this->restoreAppConfig();
\OC_User::setUserId(null);
self::setUserId(null);
$user1->delete();
$user2->delete();
@@ -237,7 +237,7 @@ class AppTest extends \Test\TestCase {
$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 @@ class AppTest extends \Test\TestCase {
$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();
}
+2 -2
View File
@@ -59,7 +59,7 @@ class FileCacheTest extends TestCache {
$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 @@ class FileCacheTest extends TestCache {
$this->instance->remove('hack', 'hack');
}
\OC_User::setUserId($this->user);
self::setUserId($this->user);
if ($this->instance) {
$this->instance->clear();
+1 -1
View File
@@ -147,7 +147,7 @@ class ViewTest extends \Test\TestCase {
}
protected function tearDown(): void {
\OC_User::setUserId($this->user);
self::setUserId($this->user);
foreach ($this->storages as $storage) {
$cache = $storage->getCache();
$ids = $cache->getAll();
+2 -2
View File
@@ -40,7 +40,7 @@ class HelperStorageTest extends \Test\TestCase {
$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 @@ class HelperStorageTest extends \Test\TestCase {
}
Filesystem::tearDown();
\OC_User::setUserId('');
self::setUserId('');
Server::get(IConfig::class)->deleteAllUserValues($this->user);
parent::tearDown();
@@ -45,7 +45,7 @@ class CertificateManagerTest extends \Test\TestCase {
$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);
+1 -1
View File
@@ -46,7 +46,7 @@ class TagsTest extends \Test\TestCase {
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);
+13 -1
View File
@@ -29,6 +29,7 @@ use OCP\DB\QueryBuilder\IQueryBuilder;
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 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase {
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 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase {
$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);
}
}
}
+10 -7
View File
@@ -17,6 +17,7 @@ use OCA\Encryption\KeyManager;
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 @@ trait EncryptionTrait {
*/
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);
}
}
+1 -1
View File
@@ -102,7 +102,7 @@ class SessionTest extends \Test\TestCase {
])
->getMock();
\OC_User::setIncognitoMode(false);
$this->userSession->setIncognitoMode(false);
}
public static function isLoggedInData(): array {