AUserData.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Provisioning_API\Controller;
  8. use OC\Group\Manager as GroupManager;
  9. use OC\User\Backend;
  10. use OC\User\NoUserException;
  11. use OC_Helper;
  12. use OCA\Provisioning_API\ResponseDefinitions;
  13. use OCP\Accounts\IAccountManager;
  14. use OCP\Accounts\PropertyDoesNotExistException;
  15. use OCP\AppFramework\Http;
  16. use OCP\AppFramework\OCS\OCSException;
  17. use OCP\AppFramework\OCS\OCSNotFoundException;
  18. use OCP\AppFramework\OCSController;
  19. use OCP\Files\NotFoundException;
  20. use OCP\Group\ISubAdmin;
  21. use OCP\IConfig;
  22. use OCP\IRequest;
  23. use OCP\IUser;
  24. use OCP\IUserManager;
  25. use OCP\IUserSession;
  26. use OCP\L10N\IFactory;
  27. use OCP\User\Backend\ISetDisplayNameBackend;
  28. use OCP\User\Backend\ISetPasswordBackend;
  29. /**
  30. * @psalm-import-type Provisioning_APIUserDetails from ResponseDefinitions
  31. * @psalm-import-type Provisioning_APIUserDetailsQuota from ResponseDefinitions
  32. */
  33. abstract class AUserData extends OCSController {
  34. public const SCOPE_SUFFIX = 'Scope';
  35. public const USER_FIELD_DISPLAYNAME = 'display';
  36. public const USER_FIELD_LANGUAGE = 'language';
  37. public const USER_FIELD_LOCALE = 'locale';
  38. public const USER_FIELD_FIRST_DAY_OF_WEEK = 'first_day_of_week';
  39. public const USER_FIELD_PASSWORD = 'password';
  40. public const USER_FIELD_QUOTA = 'quota';
  41. public const USER_FIELD_MANAGER = 'manager';
  42. public const USER_FIELD_NOTIFICATION_EMAIL = 'notify_email';
  43. public function __construct(
  44. string $appName,
  45. IRequest $request,
  46. protected IUserManager $userManager,
  47. protected IConfig $config,
  48. protected GroupManager $groupManager,
  49. protected IUserSession $userSession,
  50. protected IAccountManager $accountManager,
  51. protected ISubAdmin $subAdminManager,
  52. protected IFactory $l10nFactory,
  53. ) {
  54. parent::__construct($appName, $request);
  55. }
  56. /**
  57. * creates a array with all user data
  58. *
  59. * @param string $userId
  60. * @param bool $includeScopes
  61. * @return Provisioning_APIUserDetails|null
  62. * @throws NotFoundException
  63. * @throws OCSException
  64. * @throws OCSNotFoundException
  65. */
  66. protected function getUserData(string $userId, bool $includeScopes = false): ?array {
  67. $currentLoggedInUser = $this->userSession->getUser();
  68. assert($currentLoggedInUser !== null, 'No user logged in');
  69. $data = [];
  70. // Check if the target user exists
  71. $targetUserObject = $this->userManager->get($userId);
  72. if ($targetUserObject === null) {
  73. throw new OCSNotFoundException('User does not exist');
  74. }
  75. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  76. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID());
  77. if ($isAdmin
  78. || $isDelegatedAdmin
  79. || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
  80. $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true') === 'true';
  81. } else {
  82. // Check they are looking up themselves
  83. if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
  84. return null;
  85. }
  86. }
  87. // Get groups data
  88. $userAccount = $this->accountManager->getAccount($targetUserObject);
  89. $groups = $this->groupManager->getUserGroups($targetUserObject);
  90. $gids = [];
  91. foreach ($groups as $group) {
  92. $gids[] = $group->getGID();
  93. }
  94. if ($isAdmin || $isDelegatedAdmin) {
  95. try {
  96. # might be thrown by LDAP due to handling of users disappears
  97. # from the external source (reasons unknown to us)
  98. # cf. https://github.com/nextcloud/server/issues/12991
  99. $data['storageLocation'] = $targetUserObject->getHome();
  100. } catch (NoUserException $e) {
  101. throw new OCSNotFoundException($e->getMessage(), $e);
  102. }
  103. }
  104. // Find the data
  105. $data['id'] = $targetUserObject->getUID();
  106. $data['lastLogin'] = $targetUserObject->getLastLogin() * 1000;
  107. $data['backend'] = $targetUserObject->getBackendClassName();
  108. $data['subadmin'] = $this->getUserSubAdminGroupsData($targetUserObject->getUID());
  109. $data[self::USER_FIELD_QUOTA] = $this->fillStorageInfo($targetUserObject->getUID());
  110. $managers = $this->getManagers($targetUserObject);
  111. $data[self::USER_FIELD_MANAGER] = empty($managers) ? '' : $managers[0];
  112. try {
  113. if ($includeScopes) {
  114. $data[IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope();
  115. }
  116. $data[IAccountManager::PROPERTY_EMAIL] = $targetUserObject->getSystemEMailAddress();
  117. if ($includeScopes) {
  118. $data[IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getScope();
  119. }
  120. $additionalEmails = $additionalEmailScopes = [];
  121. $emailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  122. foreach ($emailCollection->getProperties() as $property) {
  123. $additionalEmails[] = $property->getValue();
  124. if ($includeScopes) {
  125. $additionalEmailScopes[] = $property->getScope();
  126. }
  127. }
  128. $data[IAccountManager::COLLECTION_EMAIL] = $additionalEmails;
  129. if ($includeScopes) {
  130. $data[IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX] = $additionalEmailScopes;
  131. }
  132. $data[IAccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
  133. $data[IAccountManager::PROPERTY_DISPLAYNAME_LEGACY] = $data[IAccountManager::PROPERTY_DISPLAYNAME];
  134. if ($includeScopes) {
  135. $data[IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getScope();
  136. }
  137. foreach ([
  138. IAccountManager::PROPERTY_PHONE,
  139. IAccountManager::PROPERTY_ADDRESS,
  140. IAccountManager::PROPERTY_WEBSITE,
  141. IAccountManager::PROPERTY_TWITTER,
  142. IAccountManager::PROPERTY_FEDIVERSE,
  143. IAccountManager::PROPERTY_ORGANISATION,
  144. IAccountManager::PROPERTY_ROLE,
  145. IAccountManager::PROPERTY_HEADLINE,
  146. IAccountManager::PROPERTY_BIOGRAPHY,
  147. IAccountManager::PROPERTY_PROFILE_ENABLED,
  148. IAccountManager::PROPERTY_PRONOUNS,
  149. ] as $propertyName) {
  150. $property = $userAccount->getProperty($propertyName);
  151. $data[$propertyName] = $property->getValue();
  152. if ($includeScopes) {
  153. $data[$propertyName . self::SCOPE_SUFFIX] = $property->getScope();
  154. }
  155. }
  156. } catch (PropertyDoesNotExistException $e) {
  157. // hard coded properties should exist
  158. throw new OCSException($e->getMessage(), Http::STATUS_INTERNAL_SERVER_ERROR, $e);
  159. }
  160. $data['groups'] = $gids;
  161. $data[self::USER_FIELD_LANGUAGE] = $this->l10nFactory->getUserLanguage($targetUserObject);
  162. $data[self::USER_FIELD_LOCALE] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'locale');
  163. $data[self::USER_FIELD_NOTIFICATION_EMAIL] = $targetUserObject->getPrimaryEMailAddress();
  164. $backend = $targetUserObject->getBackend();
  165. $data['backendCapabilities'] = [
  166. 'setDisplayName' => $backend instanceof ISetDisplayNameBackend || $backend->implementsActions(Backend::SET_DISPLAYNAME),
  167. 'setPassword' => $backend instanceof ISetPasswordBackend || $backend->implementsActions(Backend::SET_PASSWORD),
  168. ];
  169. return $data;
  170. }
  171. /**
  172. * @return string[]
  173. */
  174. protected function getManagers(IUser $user): array {
  175. $currentLoggedInUser = $this->userSession->getUser();
  176. $managerUids = $user->getManagerUids();
  177. if ($this->groupManager->isAdmin($currentLoggedInUser->getUID()) || $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID())) {
  178. return $managerUids;
  179. }
  180. if ($this->subAdminManager->isSubAdmin($currentLoggedInUser)) {
  181. $accessibleManagerUids = array_values(array_filter(
  182. $managerUids,
  183. function (string $managerUid) use ($currentLoggedInUser) {
  184. $manager = $this->userManager->get($managerUid);
  185. if (!($manager instanceof IUser)) {
  186. return false;
  187. }
  188. return $this->subAdminManager->isUserAccessible($currentLoggedInUser, $manager);
  189. },
  190. ));
  191. return $accessibleManagerUids;
  192. }
  193. return [];
  194. }
  195. /**
  196. * Get the groups a user is a subadmin of
  197. *
  198. * @param string $userId
  199. * @return list<string>
  200. * @throws OCSException
  201. */
  202. protected function getUserSubAdminGroupsData(string $userId): array {
  203. $user = $this->userManager->get($userId);
  204. // Check if the user exists
  205. if ($user === null) {
  206. throw new OCSNotFoundException('User does not exist');
  207. }
  208. // Get the subadmin groups
  209. $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
  210. $groups = [];
  211. foreach ($subAdminGroups as $key => $group) {
  212. $groups[] = $group->getGID();
  213. }
  214. return $groups;
  215. }
  216. /**
  217. * @param string $userId
  218. * @return Provisioning_APIUserDetailsQuota
  219. * @throws OCSException
  220. */
  221. protected function fillStorageInfo(string $userId): array {
  222. try {
  223. \OC_Util::tearDownFS();
  224. \OC_Util::setupFS($userId);
  225. $storage = OC_Helper::getStorageInfo('/', null, true, false);
  226. $data = [
  227. 'free' => $storage['free'],
  228. 'used' => $storage['used'],
  229. 'total' => $storage['total'],
  230. 'relative' => $storage['relative'],
  231. self::USER_FIELD_QUOTA => $storage['quota'],
  232. ];
  233. } catch (NotFoundException $ex) {
  234. // User fs is not setup yet
  235. $user = $this->userManager->get($userId);
  236. if ($user === null) {
  237. throw new OCSException('User does not exist', 101);
  238. }
  239. $quota = $user->getQuota();
  240. if ($quota !== 'none') {
  241. $quota = OC_Helper::computerFileSize($quota);
  242. }
  243. $data = [
  244. self::USER_FIELD_QUOTA => $quota !== false ? $quota : 'none',
  245. 'used' => 0
  246. ];
  247. } catch (\Exception $e) {
  248. \OC::$server->get(\Psr\Log\LoggerInterface::class)->error(
  249. 'Could not load storage info for {user}',
  250. [
  251. 'app' => 'provisioning_api',
  252. 'user' => $userId,
  253. 'exception' => $e,
  254. ]
  255. );
  256. /* In case the Exception left things in a bad state */
  257. \OC_Util::tearDownFS();
  258. return [];
  259. }
  260. return $data;
  261. }
  262. }