123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440 |
- <?php
- /**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Aldo "xoen" Giambelluca <xoen@xoen.org>
- * @author Andreas Fischer <bantu@owncloud.com>
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Bartek Przybylski <bart.p.pl@gmail.com>
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Georg Ehrke <oc.list@georgehrke.com>
- * @author Jakob Sack <mail@jakobsack.de>
- * @author Jörn Friedrich Dreyer <jfd@butonic.de>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Robin McCorkell <robin@mccorkell.me.uk>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author shkdee <louis.traynard@m4x.org>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
- */
- use OC\Authentication\Token\IProvider;
- use OC\User\LoginException;
- use OCP\Authentication\Exceptions\InvalidTokenException;
- use OCP\Authentication\Exceptions\WipeTokenException;
- use OCP\EventDispatcher\IEventDispatcher;
- use OCP\IGroupManager;
- use OCP\ISession;
- use OCP\IUser;
- use OCP\IUserManager;
- use OCP\Server;
- use OCP\Session\Exceptions\SessionNotAvailableException;
- use OCP\User\Events\BeforeUserLoggedInEvent;
- use OCP\User\Events\UserLoggedInEvent;
- use Psr\Log\LoggerInterface;
- /**
- * This class provides wrapper methods for user management. Multiple backends are
- * supported. User management operations are delegated to the configured backend for
- * execution.
- *
- * Note that &run is deprecated and won't work anymore.
- *
- * Hooks provided:
- * pre_createUser(&run, uid, password)
- * post_createUser(uid, password)
- * pre_deleteUser(&run, uid)
- * post_deleteUser(uid)
- * pre_setPassword(&run, uid, password, recoveryPassword)
- * post_setPassword(uid, password, recoveryPassword)
- * pre_login(&run, uid, password)
- * post_login(uid)
- * logout()
- */
- class OC_User {
- private static $_usedBackends = [];
- 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|\OCP\UserInterface $backend default: database The backend to use for user management
- * @return bool
- *
- * Set the User Authentication Module
- * @suppress PhanDeprecatedFunction
- */
- public static function useBackend($backend = 'database') {
- if ($backend instanceof \OCP\UserInterface) {
- self::$_usedBackends[get_class($backend)] = $backend;
- \OC::$server->getUserManager()->registerBackend($backend);
- } else {
- // You'll never know what happens
- if (null === $backend or !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']);
- self::$_usedBackends[$backend] = new \OC\User\Database();
- \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
- break;
- case 'dummy':
- self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
- \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
- break;
- default:
- Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']);
- $className = 'OC_USER_' . strtoupper($backend);
- self::$_usedBackends[$backend] = new $className();
- \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
- break;
- }
- }
- return true;
- }
- /**
- * remove all used backends
- */
- public static function clearBackends() {
- self::$_usedBackends = [];
- \OC::$server->getUserManager()->clearBackends();
- }
- /**
- * setup the configured backends in config.php
- * @suppress PhanDeprecatedFunction
- */
- public static function setupBackends() {
- OC_App::loadApps(['prelogin']);
- $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
- if (isset($backends['default']) && !$backends['default']) {
- // clear default backends
- self::clearBackends();
- }
- foreach ($backends as $i => $config) {
- if (!is_array($config)) {
- continue;
- }
- $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 {
- Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']);
- }
- }
- }
- /**
- * Try to login a user, assuming authentication
- * has already happened (e.g. via Single Sign On).
- *
- * Log in a user and regenerate a new session.
- *
- * @param \OCP\Authentication\IApacheBackend $backend
- * @return bool
- */
- public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
- $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);
- $userSession = \OC::$server->getUserSession();
- /** @var IEventDispatcher $dispatcher */
- $dispatcher = \OC::$server->get(IEventDispatcher::class);
- if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) {
- $message = \OC::$server->getL10N('lib')->t('User disabled');
- throw new LoginException($message);
- }
- $userSession->setLoginName($uid);
- $request = OC::$server->getRequest();
- $password = null;
- if ($backend instanceof \OCP\Authentication\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 = \OC::$server->get(IProvider::class);
- try {
- $token = $tokenProvider->getToken($userSession->getSession()->getId());
- $token->setScope([
- 'password-unconfirmable' => true,
- '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(
- \OC::$server->get(IUserManager::class)->get($uid),
- $uid,
- null,
- false)
- );
- //trigger creation of user home and /files folder
- \OC::$server->getUserFolder($uid);
- }
- return true;
- }
- return false;
- }
- /**
- * Verify with Apache whether user is authenticated.
- *
- * @return boolean|null
- * true: authenticated
- * false: not authenticated
- * null: not handled / no backend available
- */
- public static function handleApacheAuth() {
- $backend = self::findFirstActiveUsedBackend();
- if ($backend) {
- OC_App::loadApps();
- //setup extra user backends
- self::setupBackends();
- \OC::$server->getUserSession()->unsetMagicInCookie();
- return self::loginWithApache($backend);
- }
- return null;
- }
- /**
- * Sets user id for session and triggers emit
- *
- * @param string $uid
- */
- public static function setUserId($uid) {
- $userSession = \OC::$server->getUserSession();
- $userManager = \OC::$server->getUserManager();
- if ($user = $userManager->get($uid)) {
- $userSession->setUser($user);
- } else {
- \OC::$server->getSession()->set('user_id', $uid);
- }
- }
- /**
- * Check if the user is logged in, considers also the HTTP basic credentials
- *
- * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
- * @return bool
- */
- public static function isLoggedIn() {
- return \OC::$server->getUserSession()->isLoggedIn();
- }
- /**
- * set incognito mode, e.g. if a user wants to open a public link
- *
- * @param bool $status
- */
- public static function setIncognitoMode($status) {
- self::$incognitoMode = $status;
- }
- /**
- * get incognito mode status
- *
- * @return bool
- */
- public static function isIncognitoMode() {
- return self::$incognitoMode;
- }
- /**
- * Returns the current logout URL valid for the currently logged-in user
- *
- * @param \OCP\IURLGenerator $urlGenerator
- * @return string
- */
- public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
- $backend = self::findFirstActiveUsedBackend();
- if ($backend) {
- return $backend->getLogoutUrl();
- }
- $user = \OC::$server->getUserSession()->getUser();
- if ($user instanceof IUser) {
- $backend = $user->getBackend();
- if ($backend instanceof \OCP\User\Backend\ICustomLogout) {
- return $backend->getLogoutUrl();
- }
- }
- $logoutUrl = $urlGenerator->linkToRoute('core.login.logout');
- $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister());
- return $logoutUrl;
- }
- /**
- * Check if the user is an admin user
- *
- * @param string $uid uid of the admin
- * @return bool
- */
- public static function isAdminUser($uid) {
- $user = Server::get(IUserManager::class)->get($uid);
- $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID());
- return $isAdmin && self::$incognitoMode === false;
- }
- /**
- * get the user id of the user currently logged in.
- *
- * @return string|false uid or false
- */
- public static function getUser() {
- $uid = Server::get(ISession::class)?->get('user_id');
- if (!is_null($uid) && self::$incognitoMode === false) {
- return $uid;
- } else {
- return false;
- }
- }
- /**
- * Set password
- *
- * @param string $uid The username
- * @param string $password The new password
- * @param string $recoveryPassword for the encryption app to reset encryption keys
- * @return bool
- *
- * Change the password of a user
- */
- public static function setPassword($uid, $password, $recoveryPassword = null) {
- $user = \OC::$server->getUserManager()->get($uid);
- if ($user) {
- return $user->setPassword($password, $recoveryPassword);
- } else {
- return false;
- }
- }
- /**
- * @param string $uid The username
- * @return string
- *
- * returns the path to the users home directory
- * @deprecated Use \OC::$server->getUserManager->getHome()
- */
- public static function getHome($uid) {
- $user = \OC::$server->getUserManager()->get($uid);
- if ($user) {
- return $user->getHome();
- } else {
- return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
- }
- }
- /**
- * Get a list of all users display name
- *
- * @param string $search
- * @param int $limit
- * @param int $offset
- * @return array associative array with all display names (value) and corresponding uids (key)
- *
- * Get a list of all display names and user ids.
- * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
- */
- public static function getDisplayNames($search = '', $limit = null, $offset = null) {
- $displayNames = [];
- $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
- foreach ($users as $user) {
- $displayNames[$user->getUID()] = $user->getDisplayName();
- }
- return $displayNames;
- }
- /**
- * Returns the first active backend from self::$_usedBackends.
- *
- * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
- */
- private static function findFirstActiveUsedBackend() {
- foreach (self::$_usedBackends as $backend) {
- if ($backend instanceof OCP\Authentication\IApacheBackend) {
- if ($backend->isSessionActive()) {
- return $backend;
- }
- }
- }
- return null;
- }
- }
|