AUserData.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018 John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Georg Ehrke <oc.list@georgehrke.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Vincent Petry <vincent@nextcloud.com>
  13. * @author Kate Döen <kate.doeen@nextcloud.com>
  14. *
  15. * @license GNU AGPL version 3 or any later version
  16. *
  17. * This program is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License as
  19. * published by the Free Software Foundation, either version 3 of the
  20. * License, or (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  29. *
  30. */
  31. namespace OCA\Provisioning_API\Controller;
  32. use OC\Group\Manager;
  33. use OC\User\Backend;
  34. use OC\User\NoUserException;
  35. use OC_Helper;
  36. use OCA\Provisioning_API\ResponseDefinitions;
  37. use OCP\Accounts\IAccountManager;
  38. use OCP\Accounts\PropertyDoesNotExistException;
  39. use OCP\AppFramework\Http;
  40. use OCP\AppFramework\OCS\OCSException;
  41. use OCP\AppFramework\OCS\OCSNotFoundException;
  42. use OCP\AppFramework\OCSController;
  43. use OCP\Files\NotFoundException;
  44. use OCP\IConfig;
  45. use OCP\IGroupManager;
  46. use OCP\IRequest;
  47. use OCP\IUserManager;
  48. use OCP\IUserSession;
  49. use OCP\L10N\IFactory;
  50. use OCP\User\Backend\ISetDisplayNameBackend;
  51. use OCP\User\Backend\ISetPasswordBackend;
  52. /**
  53. * @psalm-import-type ProvisioningApiUserDetails from ResponseDefinitions
  54. * @psalm-import-type ProvisioningApiUserDetailsQuota from ResponseDefinitions
  55. */
  56. abstract class AUserData extends OCSController {
  57. public const SCOPE_SUFFIX = 'Scope';
  58. public const USER_FIELD_DISPLAYNAME = 'display';
  59. public const USER_FIELD_LANGUAGE = 'language';
  60. public const USER_FIELD_LOCALE = 'locale';
  61. public const USER_FIELD_PASSWORD = 'password';
  62. public const USER_FIELD_QUOTA = 'quota';
  63. public const USER_FIELD_MANAGER = 'manager';
  64. public const USER_FIELD_NOTIFICATION_EMAIL = 'notify_email';
  65. /** @var IUserManager */
  66. protected $userManager;
  67. /** @var IConfig */
  68. protected $config;
  69. /** @var Manager */
  70. protected $groupManager;
  71. /** @var IUserSession */
  72. protected $userSession;
  73. /** @var IAccountManager */
  74. protected $accountManager;
  75. /** @var IFactory */
  76. protected $l10nFactory;
  77. public function __construct(string $appName,
  78. IRequest $request,
  79. IUserManager $userManager,
  80. IConfig $config,
  81. IGroupManager $groupManager,
  82. IUserSession $userSession,
  83. IAccountManager $accountManager,
  84. IFactory $l10nFactory) {
  85. parent::__construct($appName, $request);
  86. $this->userManager = $userManager;
  87. $this->config = $config;
  88. $this->groupManager = $groupManager;
  89. $this->userSession = $userSession;
  90. $this->accountManager = $accountManager;
  91. $this->l10nFactory = $l10nFactory;
  92. }
  93. /**
  94. * creates a array with all user data
  95. *
  96. * @param string $userId
  97. * @param bool $includeScopes
  98. * @return ProvisioningApiUserDetails|null
  99. * @throws NotFoundException
  100. * @throws OCSException
  101. * @throws OCSNotFoundException
  102. */
  103. protected function getUserData(string $userId, bool $includeScopes = false): ?array {
  104. $currentLoggedInUser = $this->userSession->getUser();
  105. assert($currentLoggedInUser !== null, 'No user logged in');
  106. $data = [];
  107. // Check if the target user exists
  108. $targetUserObject = $this->userManager->get($userId);
  109. if ($targetUserObject === null) {
  110. throw new OCSNotFoundException('User does not exist');
  111. }
  112. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  113. if ($isAdmin
  114. || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
  115. $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true') === 'true';
  116. } else {
  117. // Check they are looking up themselves
  118. if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
  119. return null;
  120. }
  121. }
  122. // Get groups data
  123. $userAccount = $this->accountManager->getAccount($targetUserObject);
  124. $groups = $this->groupManager->getUserGroups($targetUserObject);
  125. $gids = [];
  126. foreach ($groups as $group) {
  127. $gids[] = $group->getGID();
  128. }
  129. if ($isAdmin) {
  130. try {
  131. # might be thrown by LDAP due to handling of users disappears
  132. # from the external source (reasons unknown to us)
  133. # cf. https://github.com/nextcloud/server/issues/12991
  134. $data['storageLocation'] = $targetUserObject->getHome();
  135. } catch (NoUserException $e) {
  136. throw new OCSNotFoundException($e->getMessage(), $e);
  137. }
  138. }
  139. // Find the data
  140. $data['id'] = $targetUserObject->getUID();
  141. $data['lastLogin'] = $targetUserObject->getLastLogin() * 1000;
  142. $data['backend'] = $targetUserObject->getBackendClassName();
  143. $data['subadmin'] = $this->getUserSubAdminGroupsData($targetUserObject->getUID());
  144. $data[self::USER_FIELD_QUOTA] = $this->fillStorageInfo($targetUserObject->getUID());
  145. $managerUids = $targetUserObject->getManagerUids();
  146. $data[self::USER_FIELD_MANAGER] = empty($managerUids) ? '' : $managerUids[0];
  147. try {
  148. if ($includeScopes) {
  149. $data[IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope();
  150. }
  151. $data[IAccountManager::PROPERTY_EMAIL] = $targetUserObject->getSystemEMailAddress();
  152. if ($includeScopes) {
  153. $data[IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getScope();
  154. }
  155. $additionalEmails = $additionalEmailScopes = [];
  156. $emailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  157. foreach ($emailCollection->getProperties() as $property) {
  158. $additionalEmails[] = $property->getValue();
  159. if ($includeScopes) {
  160. $additionalEmailScopes[] = $property->getScope();
  161. }
  162. }
  163. $data[IAccountManager::COLLECTION_EMAIL] = $additionalEmails;
  164. if ($includeScopes) {
  165. $data[IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX] = $additionalEmailScopes;
  166. }
  167. $data[IAccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
  168. $data[IAccountManager::PROPERTY_DISPLAYNAME_LEGACY] = $data[IAccountManager::PROPERTY_DISPLAYNAME];
  169. if ($includeScopes) {
  170. $data[IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getScope();
  171. }
  172. foreach ([
  173. IAccountManager::PROPERTY_PHONE,
  174. IAccountManager::PROPERTY_ADDRESS,
  175. IAccountManager::PROPERTY_WEBSITE,
  176. IAccountManager::PROPERTY_TWITTER,
  177. IAccountManager::PROPERTY_FEDIVERSE,
  178. IAccountManager::PROPERTY_ORGANISATION,
  179. IAccountManager::PROPERTY_ROLE,
  180. IAccountManager::PROPERTY_HEADLINE,
  181. IAccountManager::PROPERTY_BIOGRAPHY,
  182. IAccountManager::PROPERTY_PROFILE_ENABLED,
  183. ] as $propertyName) {
  184. $property = $userAccount->getProperty($propertyName);
  185. $data[$propertyName] = $property->getValue();
  186. if ($includeScopes) {
  187. $data[$propertyName . self::SCOPE_SUFFIX] = $property->getScope();
  188. }
  189. }
  190. } catch (PropertyDoesNotExistException $e) {
  191. // hard coded properties should exist
  192. throw new OCSException($e->getMessage(), Http::STATUS_INTERNAL_SERVER_ERROR, $e);
  193. }
  194. $data['groups'] = $gids;
  195. $data[self::USER_FIELD_LANGUAGE] = $this->l10nFactory->getUserLanguage($targetUserObject);
  196. $data[self::USER_FIELD_LOCALE] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'locale');
  197. $data[self::USER_FIELD_NOTIFICATION_EMAIL] = $targetUserObject->getPrimaryEMailAddress();
  198. $backend = $targetUserObject->getBackend();
  199. $data['backendCapabilities'] = [
  200. 'setDisplayName' => $backend instanceof ISetDisplayNameBackend || $backend->implementsActions(Backend::SET_DISPLAYNAME),
  201. 'setPassword' => $backend instanceof ISetPasswordBackend || $backend->implementsActions(Backend::SET_PASSWORD),
  202. ];
  203. return $data;
  204. }
  205. /**
  206. * Get the groups a user is a subadmin of
  207. *
  208. * @param string $userId
  209. * @return string[]
  210. * @throws OCSException
  211. */
  212. protected function getUserSubAdminGroupsData(string $userId): array {
  213. $user = $this->userManager->get($userId);
  214. // Check if the user exists
  215. if ($user === null) {
  216. throw new OCSNotFoundException('User does not exist');
  217. }
  218. // Get the subadmin groups
  219. $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
  220. $groups = [];
  221. foreach ($subAdminGroups as $key => $group) {
  222. $groups[] = $group->getGID();
  223. }
  224. return $groups;
  225. }
  226. /**
  227. * @param string $userId
  228. * @return ProvisioningApiUserDetailsQuota
  229. * @throws OCSException
  230. */
  231. protected function fillStorageInfo(string $userId): array {
  232. try {
  233. \OC_Util::tearDownFS();
  234. \OC_Util::setupFS($userId);
  235. $storage = OC_Helper::getStorageInfo('/', null, true, false);
  236. $data = [
  237. 'free' => $storage['free'],
  238. 'used' => $storage['used'],
  239. 'total' => $storage['total'],
  240. 'relative' => $storage['relative'],
  241. self::USER_FIELD_QUOTA => $storage['quota'],
  242. ];
  243. } catch (NotFoundException $ex) {
  244. // User fs is not setup yet
  245. $user = $this->userManager->get($userId);
  246. if ($user === null) {
  247. throw new OCSException('User does not exist', 101);
  248. }
  249. $quota = $user->getQuota();
  250. if ($quota !== 'none') {
  251. $quota = OC_Helper::computerFileSize($quota);
  252. }
  253. $data = [
  254. self::USER_FIELD_QUOTA => $quota !== false ? $quota : 'none',
  255. 'used' => 0
  256. ];
  257. } catch (\Exception $e) {
  258. \OC::$server->get(\Psr\Log\LoggerInterface::class)->error(
  259. "Could not load storage info for {user}",
  260. [
  261. 'app' => 'provisioning_api',
  262. 'user' => $userId,
  263. 'exception' => $e,
  264. ]
  265. );
  266. /* In case the Exception left things in a bad state */
  267. \OC_Util::tearDownFS();
  268. return [];
  269. }
  270. return $data;
  271. }
  272. }