AUserData.php 9.2 KB

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