AUserData.php 8.9 KB

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