UsersController.php 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OCA\Provisioning_API\Controller;
  9. use InvalidArgumentException;
  10. use OC\Authentication\Token\RemoteWipe;
  11. use OC\KnownUser\KnownUserService;
  12. use OC\User\Backend;
  13. use OCA\Provisioning_API\ResponseDefinitions;
  14. use OCA\Settings\Mailer\NewUserMailHelper;
  15. use OCA\Settings\Settings\Admin\Users;
  16. use OCP\Accounts\IAccountManager;
  17. use OCP\Accounts\IAccountProperty;
  18. use OCP\Accounts\PropertyDoesNotExistException;
  19. use OCP\AppFramework\Http;
  20. use OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting;
  21. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  22. use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired;
  23. use OCP\AppFramework\Http\Attribute\UserRateLimit;
  24. use OCP\AppFramework\Http\DataResponse;
  25. use OCP\AppFramework\OCS\OCSException;
  26. use OCP\AppFramework\OCS\OCSForbiddenException;
  27. use OCP\AppFramework\OCS\OCSNotFoundException;
  28. use OCP\AppFramework\OCSController;
  29. use OCP\EventDispatcher\IEventDispatcher;
  30. use OCP\HintException;
  31. use OCP\IConfig;
  32. use OCP\IGroup;
  33. use OCP\IGroupManager;
  34. use OCP\IL10N;
  35. use OCP\IPhoneNumberUtil;
  36. use OCP\IRequest;
  37. use OCP\IURLGenerator;
  38. use OCP\IUser;
  39. use OCP\IUserManager;
  40. use OCP\IUserSession;
  41. use OCP\L10N\IFactory;
  42. use OCP\Security\Events\GenerateSecurePasswordEvent;
  43. use OCP\Security\ISecureRandom;
  44. use OCP\User\Backend\ISetDisplayNameBackend;
  45. use Psr\Log\LoggerInterface;
  46. /**
  47. * @psalm-import-type Provisioning_APIUserDetails from ResponseDefinitions
  48. */
  49. class UsersController extends AUserData {
  50. private IL10N $l10n;
  51. public function __construct(
  52. string $appName,
  53. IRequest $request,
  54. IUserManager $userManager,
  55. IConfig $config,
  56. IGroupManager $groupManager,
  57. IUserSession $userSession,
  58. IAccountManager $accountManager,
  59. IFactory $l10nFactory,
  60. private IURLGenerator $urlGenerator,
  61. private LoggerInterface $logger,
  62. private NewUserMailHelper $newUserMailHelper,
  63. private ISecureRandom $secureRandom,
  64. private RemoteWipe $remoteWipe,
  65. private KnownUserService $knownUserService,
  66. private IEventDispatcher $eventDispatcher,
  67. private IPhoneNumberUtil $phoneNumberUtil,
  68. ) {
  69. parent::__construct(
  70. $appName,
  71. $request,
  72. $userManager,
  73. $config,
  74. $groupManager,
  75. $userSession,
  76. $accountManager,
  77. $l10nFactory
  78. );
  79. $this->l10n = $l10nFactory->get($appName);
  80. }
  81. /**
  82. * Get a list of users
  83. *
  84. * @param string $search Text to search for
  85. * @param int|null $limit Limit the amount of groups returned
  86. * @param int $offset Offset for searching for groups
  87. * @return DataResponse<Http::STATUS_OK, array{users: string[]}, array{}>
  88. *
  89. * 200: Users returned
  90. */
  91. #[NoAdminRequired]
  92. public function getUsers(string $search = '', ?int $limit = null, int $offset = 0): DataResponse {
  93. $user = $this->userSession->getUser();
  94. $users = [];
  95. // Admin? Or SubAdmin?
  96. $uid = $user->getUID();
  97. $subAdminManager = $this->groupManager->getSubAdmin();
  98. $isAdmin = $this->groupManager->isAdmin($uid);
  99. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($uid);
  100. if ($isAdmin || $isDelegatedAdmin) {
  101. $users = $this->userManager->search($search, $limit, $offset);
  102. } elseif ($subAdminManager->isSubAdmin($user)) {
  103. $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
  104. foreach ($subAdminOfGroups as $key => $group) {
  105. $subAdminOfGroups[$key] = $group->getGID();
  106. }
  107. $users = [];
  108. foreach ($subAdminOfGroups as $group) {
  109. $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
  110. }
  111. }
  112. /** @var string[] $users */
  113. $users = array_keys($users);
  114. return new DataResponse([
  115. 'users' => $users
  116. ]);
  117. }
  118. /**
  119. * Get a list of users and their details
  120. *
  121. * @param string $search Text to search for
  122. * @param int|null $limit Limit the amount of groups returned
  123. * @param int $offset Offset for searching for groups
  124. * @return DataResponse<Http::STATUS_OK, array{users: array<string, Provisioning_APIUserDetails|array{id: string}>}, array{}>
  125. *
  126. * 200: Users details returned
  127. */
  128. #[NoAdminRequired]
  129. public function getUsersDetails(string $search = '', ?int $limit = null, int $offset = 0): DataResponse {
  130. $currentUser = $this->userSession->getUser();
  131. $users = [];
  132. // Admin? Or SubAdmin?
  133. $uid = $currentUser->getUID();
  134. $subAdminManager = $this->groupManager->getSubAdmin();
  135. $isAdmin = $this->groupManager->isAdmin($uid);
  136. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($uid);
  137. if ($isAdmin || $isDelegatedAdmin) {
  138. $users = $this->userManager->search($search, $limit, $offset);
  139. $users = array_keys($users);
  140. } elseif ($subAdminManager->isSubAdmin($currentUser)) {
  141. $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
  142. foreach ($subAdminOfGroups as $key => $group) {
  143. $subAdminOfGroups[$key] = $group->getGID();
  144. }
  145. $users = [];
  146. foreach ($subAdminOfGroups as $group) {
  147. $users[] = array_keys($this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
  148. }
  149. $users = array_merge(...$users);
  150. }
  151. $usersDetails = [];
  152. foreach ($users as $userId) {
  153. $userId = (string)$userId;
  154. try {
  155. $userData = $this->getUserData($userId);
  156. } catch (OCSNotFoundException $e) {
  157. // We still want to return all other accounts, but this one was removed from the backends
  158. // yet they are still in our database. Might be a LDAP remnant.
  159. $userData = null;
  160. $this->logger->warning('Found one enabled account that is removed from its backend, but still exists in Nextcloud database', ['accountId' => $userId]);
  161. }
  162. // Do not insert empty entry
  163. if ($userData !== null) {
  164. $usersDetails[$userId] = $userData;
  165. } else {
  166. // Logged user does not have permissions to see this user
  167. // only showing its id
  168. $usersDetails[$userId] = ['id' => $userId];
  169. }
  170. }
  171. return new DataResponse([
  172. 'users' => $usersDetails
  173. ]);
  174. }
  175. /**
  176. * Get the list of disabled users and their details
  177. *
  178. * @param string $search Text to search for
  179. * @param ?int $limit Limit the amount of users returned
  180. * @param int $offset Offset
  181. * @return DataResponse<Http::STATUS_OK, array{users: array<string, Provisioning_APIUserDetails|array{id: string}>}, array{}>
  182. *
  183. * 200: Disabled users details returned
  184. */
  185. #[NoAdminRequired]
  186. public function getDisabledUsersDetails(string $search = '', ?int $limit = null, int $offset = 0): DataResponse {
  187. $currentUser = $this->userSession->getUser();
  188. if ($currentUser === null) {
  189. return new DataResponse(['users' => []]);
  190. }
  191. if ($limit !== null && $limit < 0) {
  192. throw new InvalidArgumentException("Invalid limit value: $limit");
  193. }
  194. if ($offset < 0) {
  195. throw new InvalidArgumentException("Invalid offset value: $offset");
  196. }
  197. $users = [];
  198. // Admin? Or SubAdmin?
  199. $uid = $currentUser->getUID();
  200. $subAdminManager = $this->groupManager->getSubAdmin();
  201. $isAdmin = $this->groupManager->isAdmin($uid);
  202. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($uid);
  203. if ($isAdmin || $isDelegatedAdmin) {
  204. $users = $this->userManager->getDisabledUsers($limit, $offset, $search);
  205. $users = array_map(fn (IUser $user): string => $user->getUID(), $users);
  206. } elseif ($subAdminManager->isSubAdmin($currentUser)) {
  207. $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
  208. $users = [];
  209. /* We have to handle offset ourselve for correctness */
  210. $tempLimit = ($limit === null ? null : $limit + $offset);
  211. foreach ($subAdminOfGroups as $group) {
  212. $users = array_merge(
  213. $users,
  214. array_map(
  215. fn (IUser $user): string => $user->getUID(),
  216. array_filter(
  217. $group->searchUsers($search, ($tempLimit === null ? null : $tempLimit - count($users))),
  218. fn (IUser $user): bool => !$user->isEnabled()
  219. )
  220. )
  221. );
  222. if (($tempLimit !== null) && (count($users) >= $tempLimit)) {
  223. break;
  224. }
  225. }
  226. $users = array_slice($users, $offset);
  227. }
  228. $usersDetails = [];
  229. foreach ($users as $userId) {
  230. try {
  231. $userData = $this->getUserData($userId);
  232. } catch (OCSNotFoundException $e) {
  233. // We still want to return all other accounts, but this one was removed from the backends
  234. // yet they are still in our database. Might be a LDAP remnant.
  235. $userData = null;
  236. $this->logger->warning('Found one disabled account that was removed from its backend, but still exists in Nextcloud database', ['accountId' => $userId]);
  237. }
  238. // Do not insert empty entry
  239. if ($userData !== null) {
  240. $usersDetails[$userId] = $userData;
  241. } else {
  242. // Currently logged in user does not have permissions to see this user
  243. // only showing its id
  244. $usersDetails[$userId] = ['id' => $userId];
  245. }
  246. }
  247. return new DataResponse([
  248. 'users' => $usersDetails
  249. ]);
  250. }
  251. /**
  252. * Gets the list of users sorted by lastLogin, from most recent to least recent
  253. *
  254. * @param string $search Text to search for
  255. * @param ?int $limit Limit the amount of users returned
  256. * @param int $offset Offset
  257. * @return DataResponse<Http::STATUS_OK, array{users: array<string, Provisioning_APIUserDetails|array{id: string}>}, array{}>
  258. *
  259. * 200: Users details returned based on last logged in information
  260. */
  261. #[AuthorizedAdminSetting(settings:Users::class)]
  262. public function getLastLoggedInUsers(string $search = '',
  263. ?int $limit = null,
  264. int $offset = 0,
  265. ): DataResponse {
  266. $currentUser = $this->userSession->getUser();
  267. if ($currentUser === null) {
  268. return new DataResponse(['users' => []]);
  269. }
  270. if ($limit !== null && $limit < 0) {
  271. throw new InvalidArgumentException("Invalid limit value: $limit");
  272. }
  273. if ($offset < 0) {
  274. throw new InvalidArgumentException("Invalid offset value: $offset");
  275. }
  276. $users = [];
  277. // For Admin alone user sorting based on lastLogin. For sub admin and groups this is not supported
  278. $users = $this->userManager->getLastLoggedInUsers($limit, $offset, $search);
  279. $usersDetails = [];
  280. foreach ($users as $userId) {
  281. try {
  282. $userData = $this->getUserData($userId);
  283. } catch (OCSNotFoundException $e) {
  284. // We still want to return all other accounts, but this one was removed from the backends
  285. // yet they are still in our database. Might be a LDAP remnant.
  286. $userData = null;
  287. $this->logger->warning('Found one account that was removed from its backend, but still exists in Nextcloud database', ['accountId' => $userId]);
  288. }
  289. // Do not insert empty entry
  290. if ($userData !== null) {
  291. $usersDetails[$userId] = $userData;
  292. } else {
  293. // Currently logged-in user does not have permissions to see this user
  294. // only showing its id
  295. $usersDetails[$userId] = ['id' => $userId];
  296. }
  297. }
  298. return new DataResponse([
  299. 'users' => $usersDetails
  300. ]);
  301. }
  302. /**
  303. * @NoSubAdminRequired
  304. *
  305. * Search users by their phone numbers
  306. *
  307. * @param string $location Location of the phone number (for country code)
  308. * @param array<string, string[]> $search Phone numbers to search for
  309. * @return DataResponse<Http::STATUS_OK, array<string, string>, array{}>|DataResponse<Http::STATUS_BAD_REQUEST, array<empty>, array{}>
  310. *
  311. * 200: Users returned
  312. * 400: Invalid location
  313. */
  314. #[NoAdminRequired]
  315. public function searchByPhoneNumbers(string $location, array $search): DataResponse {
  316. if ($this->phoneNumberUtil->getCountryCodeForRegion($location) === null) {
  317. // Not a valid region code
  318. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  319. }
  320. /** @var IUser $user */
  321. $user = $this->userSession->getUser();
  322. $knownTo = $user->getUID();
  323. $defaultPhoneRegion = $this->config->getSystemValueString('default_phone_region');
  324. $normalizedNumberToKey = [];
  325. foreach ($search as $key => $phoneNumbers) {
  326. foreach ($phoneNumbers as $phone) {
  327. $normalizedNumber = $this->phoneNumberUtil->convertToStandardFormat($phone, $location);
  328. if ($normalizedNumber !== null) {
  329. $normalizedNumberToKey[$normalizedNumber] = (string)$key;
  330. }
  331. if ($defaultPhoneRegion !== '' && $defaultPhoneRegion !== $location && str_starts_with($phone, '0')) {
  332. // If the number has a leading zero (no country code),
  333. // we also check the default phone region of the instance,
  334. // when it's different to the user's given region.
  335. $normalizedNumber = $this->phoneNumberUtil->convertToStandardFormat($phone, $defaultPhoneRegion);
  336. if ($normalizedNumber !== null) {
  337. $normalizedNumberToKey[$normalizedNumber] = (string)$key;
  338. }
  339. }
  340. }
  341. }
  342. $phoneNumbers = array_keys($normalizedNumberToKey);
  343. if (empty($phoneNumbers)) {
  344. return new DataResponse();
  345. }
  346. // Cleanup all previous entries and only allow new matches
  347. $this->knownUserService->deleteKnownTo($knownTo);
  348. $userMatches = $this->accountManager->searchUsers(IAccountManager::PROPERTY_PHONE, $phoneNumbers);
  349. if (empty($userMatches)) {
  350. return new DataResponse();
  351. }
  352. $cloudUrl = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/');
  353. if (strpos($cloudUrl, 'http://') === 0) {
  354. $cloudUrl = substr($cloudUrl, strlen('http://'));
  355. } elseif (strpos($cloudUrl, 'https://') === 0) {
  356. $cloudUrl = substr($cloudUrl, strlen('https://'));
  357. }
  358. $matches = [];
  359. foreach ($userMatches as $phone => $userId) {
  360. // Not using the ICloudIdManager as that would run a search for each contact to find the display name in the address book
  361. $matches[$normalizedNumberToKey[$phone]] = $userId . '@' . $cloudUrl;
  362. $this->knownUserService->storeIsKnownToUser($knownTo, $userId);
  363. }
  364. return new DataResponse($matches);
  365. }
  366. /**
  367. * @throws OCSException
  368. */
  369. private function createNewUserId(): string {
  370. $attempts = 0;
  371. do {
  372. $uidCandidate = $this->secureRandom->generate(10, ISecureRandom::CHAR_HUMAN_READABLE);
  373. if (!$this->userManager->userExists($uidCandidate)) {
  374. return $uidCandidate;
  375. }
  376. $attempts++;
  377. } while ($attempts < 10);
  378. throw new OCSException($this->l10n->t('Could not create non-existing user ID'), 111);
  379. }
  380. /**
  381. * Create a new user
  382. *
  383. * @param string $userid ID of the user
  384. * @param string $password Password of the user
  385. * @param string $displayName Display name of the user
  386. * @param string $email Email of the user
  387. * @param string[] $groups Groups of the user
  388. * @param string[] $subadmin Groups where the user is subadmin
  389. * @param string $quota Quota of the user
  390. * @param string $language Language of the user
  391. * @param ?string $manager Manager of the user
  392. * @return DataResponse<Http::STATUS_OK, array{id: string}, array{}>
  393. * @throws OCSException
  394. * @throws OCSForbiddenException Missing permissions to make user subadmin
  395. *
  396. * 200: User added successfully
  397. */
  398. #[PasswordConfirmationRequired]
  399. #[NoAdminRequired]
  400. public function addUser(
  401. string $userid,
  402. string $password = '',
  403. string $displayName = '',
  404. string $email = '',
  405. array $groups = [],
  406. array $subadmin = [],
  407. string $quota = '',
  408. string $language = '',
  409. ?string $manager = null,
  410. ): DataResponse {
  411. $user = $this->userSession->getUser();
  412. $isAdmin = $this->groupManager->isAdmin($user->getUID());
  413. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($user->getUID());
  414. $subAdminManager = $this->groupManager->getSubAdmin();
  415. if (empty($userid) && $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes') {
  416. $userid = $this->createNewUserId();
  417. }
  418. if ($this->userManager->userExists($userid)) {
  419. $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
  420. throw new OCSException($this->l10n->t('User already exists'), 102);
  421. }
  422. if ($groups !== []) {
  423. foreach ($groups as $group) {
  424. if (!$this->groupManager->groupExists($group)) {
  425. throw new OCSException($this->l10n->t('Group %1$s does not exist', [$group]), 104);
  426. }
  427. if (!$isAdmin && !($isDelegatedAdmin && $group !== 'admin') && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
  428. throw new OCSException($this->l10n->t('Insufficient privileges for group %1$s', [$group]), 105);
  429. }
  430. }
  431. } else {
  432. if (!$isAdmin && !$isDelegatedAdmin) {
  433. throw new OCSException($this->l10n->t('No group specified (required for sub-admins)'), 106);
  434. }
  435. }
  436. $subadminGroups = [];
  437. if ($subadmin !== []) {
  438. foreach ($subadmin as $groupid) {
  439. $group = $this->groupManager->get($groupid);
  440. // Check if group exists
  441. if ($group === null) {
  442. throw new OCSException($this->l10n->t('Sub-admin group does not exist'), 109);
  443. }
  444. // Check if trying to make subadmin of admin group
  445. if ($group->getGID() === 'admin') {
  446. throw new OCSException($this->l10n->t('Cannot create sub-admins for admin group'), 103);
  447. }
  448. // Check if has permission to promote subadmins
  449. if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin && !$isDelegatedAdmin) {
  450. throw new OCSForbiddenException($this->l10n->t('No permissions to promote sub-admins'));
  451. }
  452. $subadminGroups[] = $group;
  453. }
  454. }
  455. $generatePasswordResetToken = false;
  456. if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {
  457. throw new OCSException($this->l10n->t('Invalid password value'), 101);
  458. }
  459. if ($password === '') {
  460. if ($email === '') {
  461. throw new OCSException($this->l10n->t('An email address is required, to send a password link to the user.'), 108);
  462. }
  463. $passwordEvent = new GenerateSecurePasswordEvent();
  464. $this->eventDispatcher->dispatchTyped($passwordEvent);
  465. $password = $passwordEvent->getPassword();
  466. if ($password === null) {
  467. // Fallback: ensure to pass password_policy in any case
  468. $password = $this->secureRandom->generate(10)
  469. . $this->secureRandom->generate(1, ISecureRandom::CHAR_UPPER)
  470. . $this->secureRandom->generate(1, ISecureRandom::CHAR_LOWER)
  471. . $this->secureRandom->generate(1, ISecureRandom::CHAR_DIGITS)
  472. . $this->secureRandom->generate(1, ISecureRandom::CHAR_SYMBOLS);
  473. }
  474. $generatePasswordResetToken = true;
  475. }
  476. if ($email === '' && $this->config->getAppValue('core', 'newUser.requireEmail', 'no') === 'yes') {
  477. throw new OCSException($this->l10n->t('Required email address was not provided'), 110);
  478. }
  479. try {
  480. $newUser = $this->userManager->createUser($userid, $password);
  481. $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
  482. foreach ($groups as $group) {
  483. $this->groupManager->get($group)->addUser($newUser);
  484. $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
  485. }
  486. foreach ($subadminGroups as $group) {
  487. $subAdminManager->createSubAdmin($newUser, $group);
  488. }
  489. if ($displayName !== '') {
  490. try {
  491. $this->editUser($userid, self::USER_FIELD_DISPLAYNAME, $displayName);
  492. } catch (OCSException $e) {
  493. if ($newUser instanceof IUser) {
  494. $newUser->delete();
  495. }
  496. throw $e;
  497. }
  498. }
  499. if ($quota !== '') {
  500. $this->editUser($userid, self::USER_FIELD_QUOTA, $quota);
  501. }
  502. if ($language !== '') {
  503. $this->editUser($userid, self::USER_FIELD_LANGUAGE, $language);
  504. }
  505. /**
  506. * null -> nothing sent
  507. * '' -> unset manager
  508. * else -> set manager
  509. */
  510. if ($manager !== null) {
  511. $this->editUser($userid, self::USER_FIELD_MANAGER, $manager);
  512. }
  513. // Send new user mail only if a mail is set
  514. if ($email !== '') {
  515. $newUser->setEMailAddress($email);
  516. if ($this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes') {
  517. try {
  518. $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
  519. $this->newUserMailHelper->sendMail($newUser, $emailTemplate);
  520. } catch (\Exception $e) {
  521. // Mail could be failing hard or just be plain not configured
  522. // Logging error as it is the hardest of the two
  523. $this->logger->error(
  524. "Unable to send the invitation mail to $email",
  525. [
  526. 'app' => 'ocs_api',
  527. 'exception' => $e,
  528. ]
  529. );
  530. }
  531. }
  532. }
  533. return new DataResponse(['id' => $userid]);
  534. } catch (HintException $e) {
  535. $this->logger->warning(
  536. 'Failed addUser attempt with hint exception.',
  537. [
  538. 'app' => 'ocs_api',
  539. 'exception' => $e,
  540. ]
  541. );
  542. throw new OCSException($e->getHint(), 107);
  543. } catch (OCSException $e) {
  544. $this->logger->warning(
  545. 'Failed addUser attempt with ocs exception.',
  546. [
  547. 'app' => 'ocs_api',
  548. 'exception' => $e,
  549. ]
  550. );
  551. throw $e;
  552. } catch (InvalidArgumentException $e) {
  553. $this->logger->error(
  554. 'Failed addUser attempt with invalid argument exception.',
  555. [
  556. 'app' => 'ocs_api',
  557. 'exception' => $e,
  558. ]
  559. );
  560. throw new OCSException($e->getMessage(), 101);
  561. } catch (\Exception $e) {
  562. $this->logger->error(
  563. 'Failed addUser attempt with exception.',
  564. [
  565. 'app' => 'ocs_api',
  566. 'exception' => $e
  567. ]
  568. );
  569. throw new OCSException('Bad request', 101);
  570. }
  571. }
  572. /**
  573. * @NoSubAdminRequired
  574. *
  575. * Get the details of a user
  576. *
  577. * @param string $userId ID of the user
  578. * @return DataResponse<Http::STATUS_OK, Provisioning_APIUserDetails, array{}>
  579. * @throws OCSException
  580. *
  581. * 200: User returned
  582. */
  583. #[NoAdminRequired]
  584. public function getUser(string $userId): DataResponse {
  585. $includeScopes = false;
  586. $currentUser = $this->userSession->getUser();
  587. if ($currentUser && $currentUser->getUID() === $userId) {
  588. $includeScopes = true;
  589. }
  590. $data = $this->getUserData($userId, $includeScopes);
  591. // getUserData returns null if not enough permissions
  592. if ($data === null) {
  593. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  594. }
  595. return new DataResponse($data);
  596. }
  597. /**
  598. * @NoSubAdminRequired
  599. *
  600. * Get the details of the current user
  601. *
  602. * @return DataResponse<Http::STATUS_OK, Provisioning_APIUserDetails, array{}>
  603. * @throws OCSException
  604. *
  605. * 200: Current user returned
  606. */
  607. #[NoAdminRequired]
  608. public function getCurrentUser(): DataResponse {
  609. $user = $this->userSession->getUser();
  610. if ($user) {
  611. /** @var Provisioning_APIUserDetails $data */
  612. $data = $this->getUserData($user->getUID(), true);
  613. return new DataResponse($data);
  614. }
  615. throw new OCSException('', OCSController::RESPOND_UNAUTHORISED);
  616. }
  617. /**
  618. * @NoSubAdminRequired
  619. *
  620. * Get a list of fields that are editable for the current user
  621. *
  622. * @return DataResponse<Http::STATUS_OK, string[], array{}>
  623. * @throws OCSException
  624. *
  625. * 200: Editable fields returned
  626. */
  627. #[NoAdminRequired]
  628. public function getEditableFields(): DataResponse {
  629. $currentLoggedInUser = $this->userSession->getUser();
  630. if (!$currentLoggedInUser instanceof IUser) {
  631. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  632. }
  633. return $this->getEditableFieldsForUser($currentLoggedInUser->getUID());
  634. }
  635. /**
  636. * @NoSubAdminRequired
  637. *
  638. * Get a list of fields that are editable for a user
  639. *
  640. * @param string $userId ID of the user
  641. * @return DataResponse<Http::STATUS_OK, string[], array{}>
  642. * @throws OCSException
  643. *
  644. * 200: Editable fields for user returned
  645. */
  646. #[NoAdminRequired]
  647. public function getEditableFieldsForUser(string $userId): DataResponse {
  648. $currentLoggedInUser = $this->userSession->getUser();
  649. if (!$currentLoggedInUser instanceof IUser) {
  650. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  651. }
  652. $permittedFields = [];
  653. if ($userId !== $currentLoggedInUser->getUID()) {
  654. $targetUser = $this->userManager->get($userId);
  655. if (!$targetUser instanceof IUser) {
  656. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  657. }
  658. $subAdminManager = $this->groupManager->getSubAdmin();
  659. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  660. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID());
  661. if (
  662. !($isAdmin || $isDelegatedAdmin)
  663. && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  664. ) {
  665. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  666. }
  667. } else {
  668. $targetUser = $currentLoggedInUser;
  669. }
  670. // Editing self (display, email)
  671. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  672. if (
  673. $targetUser->getBackend() instanceof ISetDisplayNameBackend
  674. || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
  675. ) {
  676. $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
  677. }
  678. $permittedFields[] = IAccountManager::PROPERTY_EMAIL;
  679. }
  680. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  681. $permittedFields[] = IAccountManager::PROPERTY_PHONE;
  682. $permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
  683. $permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
  684. $permittedFields[] = IAccountManager::PROPERTY_TWITTER;
  685. $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
  686. $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
  687. $permittedFields[] = IAccountManager::PROPERTY_ROLE;
  688. $permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
  689. $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
  690. $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
  691. $permittedFields[] = IAccountManager::PROPERTY_PRONOUNS;
  692. return new DataResponse($permittedFields);
  693. }
  694. /**
  695. * @NoSubAdminRequired
  696. *
  697. * Update multiple values of the user's details
  698. *
  699. * @param string $userId ID of the user
  700. * @param string $collectionName Collection to update
  701. * @param string $key Key that will be updated
  702. * @param string $value New value for the key
  703. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  704. * @throws OCSException
  705. *
  706. * 200: User values edited successfully
  707. */
  708. #[PasswordConfirmationRequired]
  709. #[NoAdminRequired]
  710. #[UserRateLimit(limit: 5, period: 60)]
  711. public function editUserMultiValue(
  712. string $userId,
  713. string $collectionName,
  714. string $key,
  715. string $value,
  716. ): DataResponse {
  717. $currentLoggedInUser = $this->userSession->getUser();
  718. if ($currentLoggedInUser === null) {
  719. throw new OCSException('', OCSController::RESPOND_UNAUTHORISED);
  720. }
  721. $targetUser = $this->userManager->get($userId);
  722. if ($targetUser === null) {
  723. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  724. }
  725. $subAdminManager = $this->groupManager->getSubAdmin();
  726. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID());
  727. $isAdminOrSubadmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID())
  728. || $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser);
  729. $permittedFields = [];
  730. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  731. // Editing self (display, email)
  732. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  733. $permittedFields[] = IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX;
  734. } else {
  735. // Check if admin / subadmin
  736. if ($isAdminOrSubadmin || $isDelegatedAdmin && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')) {
  737. // They have permissions over the user
  738. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  739. } else {
  740. // No rights
  741. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  742. }
  743. }
  744. // Check if permitted to edit this field
  745. if (!in_array($collectionName, $permittedFields)) {
  746. throw new OCSException('', 103);
  747. }
  748. switch ($collectionName) {
  749. case IAccountManager::COLLECTION_EMAIL:
  750. $userAccount = $this->accountManager->getAccount($targetUser);
  751. $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  752. $mailCollection->removePropertyByValue($key);
  753. if ($value !== '') {
  754. $mailCollection->addPropertyWithDefaults($value);
  755. $property = $mailCollection->getPropertyByValue($key);
  756. if ($isAdminOrSubadmin && $property) {
  757. // admin set mails are auto-verified
  758. $property->setLocallyVerified(IAccountManager::VERIFIED);
  759. }
  760. }
  761. $this->accountManager->updateAccount($userAccount);
  762. if ($value === '' && $key === $targetUser->getPrimaryEMailAddress()) {
  763. $targetUser->setPrimaryEMailAddress('');
  764. }
  765. break;
  766. case IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX:
  767. $userAccount = $this->accountManager->getAccount($targetUser);
  768. $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  769. $targetProperty = null;
  770. foreach ($mailCollection->getProperties() as $property) {
  771. if ($property->getValue() === $key) {
  772. $targetProperty = $property;
  773. break;
  774. }
  775. }
  776. if ($targetProperty instanceof IAccountProperty) {
  777. try {
  778. $targetProperty->setScope($value);
  779. $this->accountManager->updateAccount($userAccount);
  780. } catch (InvalidArgumentException $e) {
  781. throw new OCSException('', 102);
  782. }
  783. } else {
  784. throw new OCSException('', 102);
  785. }
  786. break;
  787. default:
  788. throw new OCSException('', 103);
  789. }
  790. return new DataResponse();
  791. }
  792. /**
  793. * @NoSubAdminRequired
  794. *
  795. * Update a value of the user's details
  796. *
  797. * @param string $userId ID of the user
  798. * @param string $key Key that will be updated
  799. * @param string $value New value for the key
  800. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  801. * @throws OCSException
  802. *
  803. * 200: User value edited successfully
  804. */
  805. #[PasswordConfirmationRequired]
  806. #[NoAdminRequired]
  807. #[UserRateLimit(limit: 50, period: 60)]
  808. public function editUser(string $userId, string $key, string $value): DataResponse {
  809. $currentLoggedInUser = $this->userSession->getUser();
  810. $targetUser = $this->userManager->get($userId);
  811. if ($targetUser === null) {
  812. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  813. }
  814. $permittedFields = [];
  815. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  816. // Editing self (display, email)
  817. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  818. if (
  819. $targetUser->getBackend() instanceof ISetDisplayNameBackend
  820. || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
  821. ) {
  822. $permittedFields[] = self::USER_FIELD_DISPLAYNAME;
  823. $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
  824. }
  825. $permittedFields[] = IAccountManager::PROPERTY_EMAIL;
  826. }
  827. $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX;
  828. $permittedFields[] = IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX;
  829. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  830. $permittedFields[] = self::USER_FIELD_PASSWORD;
  831. $permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL;
  832. if (
  833. $this->config->getSystemValue('force_language', false) === false ||
  834. $this->groupManager->isAdmin($currentLoggedInUser->getUID()) ||
  835. $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID())
  836. ) {
  837. $permittedFields[] = self::USER_FIELD_LANGUAGE;
  838. }
  839. if (
  840. $this->config->getSystemValue('force_locale', false) === false ||
  841. $this->groupManager->isAdmin($currentLoggedInUser->getUID()) ||
  842. $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID())
  843. ) {
  844. $permittedFields[] = self::USER_FIELD_LOCALE;
  845. $permittedFields[] = self::USER_FIELD_FIRST_DAY_OF_WEEK;
  846. }
  847. $permittedFields[] = IAccountManager::PROPERTY_PHONE;
  848. $permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
  849. $permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
  850. $permittedFields[] = IAccountManager::PROPERTY_TWITTER;
  851. $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
  852. $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
  853. $permittedFields[] = IAccountManager::PROPERTY_ROLE;
  854. $permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
  855. $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
  856. $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
  857. $permittedFields[] = IAccountManager::PROPERTY_BIRTHDATE;
  858. $permittedFields[] = IAccountManager::PROPERTY_PRONOUNS;
  859. $permittedFields[] = IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX;
  860. $permittedFields[] = IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX;
  861. $permittedFields[] = IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX;
  862. $permittedFields[] = IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX;
  863. $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX;
  864. $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX;
  865. $permittedFields[] = IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX;
  866. $permittedFields[] = IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX;
  867. $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX;
  868. $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX;
  869. $permittedFields[] = IAccountManager::PROPERTY_BIRTHDATE . self::SCOPE_SUFFIX;
  870. $permittedFields[] = IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX;
  871. $permittedFields[] = IAccountManager::PROPERTY_PRONOUNS . self::SCOPE_SUFFIX;
  872. // If admin they can edit their own quota and manager
  873. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  874. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID());
  875. if ($isAdmin || $isDelegatedAdmin) {
  876. $permittedFields[] = self::USER_FIELD_QUOTA;
  877. $permittedFields[] = self::USER_FIELD_MANAGER;
  878. }
  879. } else {
  880. // Check if admin / subadmin
  881. $subAdminManager = $this->groupManager->getSubAdmin();
  882. if (
  883. $this->groupManager->isAdmin($currentLoggedInUser->getUID()) ||
  884. $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()) && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')
  885. || $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  886. ) {
  887. // They have permissions over the user
  888. if (
  889. $targetUser->getBackend() instanceof ISetDisplayNameBackend
  890. || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
  891. ) {
  892. $permittedFields[] = self::USER_FIELD_DISPLAYNAME;
  893. $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
  894. }
  895. $permittedFields[] = IAccountManager::PROPERTY_EMAIL;
  896. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  897. $permittedFields[] = self::USER_FIELD_PASSWORD;
  898. $permittedFields[] = self::USER_FIELD_LANGUAGE;
  899. $permittedFields[] = self::USER_FIELD_LOCALE;
  900. $permittedFields[] = self::USER_FIELD_FIRST_DAY_OF_WEEK;
  901. $permittedFields[] = IAccountManager::PROPERTY_PHONE;
  902. $permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
  903. $permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
  904. $permittedFields[] = IAccountManager::PROPERTY_TWITTER;
  905. $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
  906. $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
  907. $permittedFields[] = IAccountManager::PROPERTY_ROLE;
  908. $permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
  909. $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
  910. $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
  911. $permittedFields[] = IAccountManager::PROPERTY_PRONOUNS;
  912. $permittedFields[] = self::USER_FIELD_QUOTA;
  913. $permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL;
  914. $permittedFields[] = self::USER_FIELD_MANAGER;
  915. } else {
  916. // No rights
  917. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  918. }
  919. }
  920. // Check if permitted to edit this field
  921. if (!in_array($key, $permittedFields)) {
  922. throw new OCSException('', 113);
  923. }
  924. // Process the edit
  925. switch ($key) {
  926. case self::USER_FIELD_DISPLAYNAME:
  927. case IAccountManager::PROPERTY_DISPLAYNAME:
  928. try {
  929. $targetUser->setDisplayName($value);
  930. } catch (InvalidArgumentException $e) {
  931. throw new OCSException($e->getMessage(), 101);
  932. }
  933. break;
  934. case self::USER_FIELD_QUOTA:
  935. $quota = $value;
  936. if ($quota !== 'none' && $quota !== 'default') {
  937. if (is_numeric($quota)) {
  938. $quota = (float)$quota;
  939. } else {
  940. $quota = \OCP\Util::computerFileSize($quota);
  941. }
  942. if ($quota === false) {
  943. throw new OCSException($this->l10n->t('Invalid quota value: %1$s', [$value]), 101);
  944. }
  945. if ($quota === -1) {
  946. $quota = 'none';
  947. } else {
  948. $maxQuota = (int)$this->config->getAppValue('files', 'max_quota', '-1');
  949. if ($maxQuota !== -1 && $quota > $maxQuota) {
  950. throw new OCSException($this->l10n->t('Invalid quota value. %1$s is exceeding the maximum quota', [$value]), 101);
  951. }
  952. $quota = \OCP\Util::humanFileSize($quota);
  953. }
  954. }
  955. // no else block because quota can be set to 'none' in previous if
  956. if ($quota === 'none') {
  957. $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
  958. if (!$allowUnlimitedQuota) {
  959. throw new OCSException($this->l10n->t('Unlimited quota is forbidden on this instance'), 101);
  960. }
  961. }
  962. $targetUser->setQuota($quota);
  963. break;
  964. case self::USER_FIELD_MANAGER:
  965. $targetUser->setManagerUids([$value]);
  966. break;
  967. case self::USER_FIELD_PASSWORD:
  968. try {
  969. if (strlen($value) > IUserManager::MAX_PASSWORD_LENGTH) {
  970. throw new OCSException($this->l10n->t('Invalid password value'), 101);
  971. }
  972. if (!$targetUser->canChangePassword()) {
  973. throw new OCSException($this->l10n->t('Setting the password is not supported by the users backend'), 112);
  974. }
  975. $targetUser->setPassword($value);
  976. } catch (HintException $e) { // password policy error
  977. throw new OCSException($e->getMessage(), 107);
  978. }
  979. break;
  980. case self::USER_FIELD_LANGUAGE:
  981. $languagesCodes = $this->l10nFactory->findAvailableLanguages();
  982. if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
  983. throw new OCSException($this->l10n->t('Invalid language'), 101);
  984. }
  985. $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
  986. break;
  987. case self::USER_FIELD_LOCALE:
  988. if (!$this->l10nFactory->localeExists($value)) {
  989. throw new OCSException($this->l10n->t('Invalid locale'), 101);
  990. }
  991. $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
  992. break;
  993. case self::USER_FIELD_FIRST_DAY_OF_WEEK:
  994. $intValue = (int)$value;
  995. if ($intValue < -1 || $intValue > 6) {
  996. throw new OCSException($this->l10n->t('Invalid first day of week'), 101);
  997. }
  998. if ($intValue === -1) {
  999. $this->config->deleteUserValue($targetUser->getUID(), 'core', AUserData::USER_FIELD_FIRST_DAY_OF_WEEK);
  1000. } else {
  1001. $this->config->setUserValue($targetUser->getUID(), 'core', AUserData::USER_FIELD_FIRST_DAY_OF_WEEK, $value);
  1002. }
  1003. break;
  1004. case self::USER_FIELD_NOTIFICATION_EMAIL:
  1005. $success = false;
  1006. if ($value === '' || filter_var($value, FILTER_VALIDATE_EMAIL)) {
  1007. try {
  1008. $targetUser->setPrimaryEMailAddress($value);
  1009. $success = true;
  1010. } catch (InvalidArgumentException $e) {
  1011. $this->logger->info(
  1012. 'Cannot set primary email, because provided address is not verified',
  1013. [
  1014. 'app' => 'provisioning_api',
  1015. 'exception' => $e,
  1016. ]
  1017. );
  1018. }
  1019. }
  1020. if (!$success) {
  1021. throw new OCSException('', 101);
  1022. }
  1023. break;
  1024. case IAccountManager::PROPERTY_EMAIL:
  1025. if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
  1026. $targetUser->setEMailAddress($value);
  1027. } else {
  1028. throw new OCSException('', 101);
  1029. }
  1030. break;
  1031. case IAccountManager::COLLECTION_EMAIL:
  1032. if (filter_var($value, FILTER_VALIDATE_EMAIL) && $value !== $targetUser->getSystemEMailAddress()) {
  1033. $userAccount = $this->accountManager->getAccount($targetUser);
  1034. $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  1035. if ($mailCollection->getPropertyByValue($value)) {
  1036. throw new OCSException('', 101);
  1037. }
  1038. $mailCollection->addPropertyWithDefaults($value);
  1039. $this->accountManager->updateAccount($userAccount);
  1040. } else {
  1041. throw new OCSException('', 101);
  1042. }
  1043. break;
  1044. case IAccountManager::PROPERTY_PHONE:
  1045. case IAccountManager::PROPERTY_ADDRESS:
  1046. case IAccountManager::PROPERTY_WEBSITE:
  1047. case IAccountManager::PROPERTY_TWITTER:
  1048. case IAccountManager::PROPERTY_FEDIVERSE:
  1049. case IAccountManager::PROPERTY_ORGANISATION:
  1050. case IAccountManager::PROPERTY_ROLE:
  1051. case IAccountManager::PROPERTY_HEADLINE:
  1052. case IAccountManager::PROPERTY_BIOGRAPHY:
  1053. case IAccountManager::PROPERTY_BIRTHDATE:
  1054. case IAccountManager::PROPERTY_PRONOUNS:
  1055. $userAccount = $this->accountManager->getAccount($targetUser);
  1056. try {
  1057. $userProperty = $userAccount->getProperty($key);
  1058. if ($userProperty->getValue() !== $value) {
  1059. try {
  1060. $userProperty->setValue($value);
  1061. if ($userProperty->getName() === IAccountManager::PROPERTY_PHONE) {
  1062. $this->knownUserService->deleteByContactUserId($targetUser->getUID());
  1063. }
  1064. } catch (InvalidArgumentException $e) {
  1065. throw new OCSException('Invalid ' . $e->getMessage(), 101);
  1066. }
  1067. }
  1068. } catch (PropertyDoesNotExistException $e) {
  1069. $userAccount->setProperty($key, $value, IAccountManager::SCOPE_PRIVATE, IAccountManager::NOT_VERIFIED);
  1070. }
  1071. try {
  1072. $this->accountManager->updateAccount($userAccount);
  1073. } catch (InvalidArgumentException $e) {
  1074. throw new OCSException('Invalid ' . $e->getMessage(), 101);
  1075. }
  1076. break;
  1077. case IAccountManager::PROPERTY_PROFILE_ENABLED:
  1078. $userAccount = $this->accountManager->getAccount($targetUser);
  1079. try {
  1080. $userProperty = $userAccount->getProperty($key);
  1081. if ($userProperty->getValue() !== $value) {
  1082. $userProperty->setValue($value);
  1083. }
  1084. } catch (PropertyDoesNotExistException $e) {
  1085. $userAccount->setProperty($key, $value, IAccountManager::SCOPE_LOCAL, IAccountManager::NOT_VERIFIED);
  1086. }
  1087. $this->accountManager->updateAccount($userAccount);
  1088. break;
  1089. case IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX:
  1090. case IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX:
  1091. case IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX:
  1092. case IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX:
  1093. case IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX:
  1094. case IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX:
  1095. case IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX:
  1096. case IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX:
  1097. case IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX:
  1098. case IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX:
  1099. case IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX:
  1100. case IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX:
  1101. case IAccountManager::PROPERTY_BIRTHDATE . self::SCOPE_SUFFIX:
  1102. case IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX:
  1103. case IAccountManager::PROPERTY_PRONOUNS . self::SCOPE_SUFFIX:
  1104. $propertyName = substr($key, 0, strlen($key) - strlen(self::SCOPE_SUFFIX));
  1105. $userAccount = $this->accountManager->getAccount($targetUser);
  1106. $userProperty = $userAccount->getProperty($propertyName);
  1107. if ($userProperty->getScope() !== $value) {
  1108. try {
  1109. $userProperty->setScope($value);
  1110. $this->accountManager->updateAccount($userAccount);
  1111. } catch (InvalidArgumentException $e) {
  1112. throw new OCSException('Invalid ' . $e->getMessage(), 101);
  1113. }
  1114. }
  1115. break;
  1116. default:
  1117. throw new OCSException('', 113);
  1118. }
  1119. return new DataResponse();
  1120. }
  1121. /**
  1122. * Wipe all devices of a user
  1123. *
  1124. * @param string $userId ID of the user
  1125. *
  1126. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1127. *
  1128. * @throws OCSException
  1129. *
  1130. * 200: Wiped all user devices successfully
  1131. */
  1132. #[PasswordConfirmationRequired]
  1133. #[NoAdminRequired]
  1134. public function wipeUserDevices(string $userId): DataResponse {
  1135. /** @var IUser $currentLoggedInUser */
  1136. $currentLoggedInUser = $this->userSession->getUser();
  1137. $targetUser = $this->userManager->get($userId);
  1138. if ($targetUser === null) {
  1139. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1140. }
  1141. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  1142. throw new OCSException('', 101);
  1143. }
  1144. // If not permitted
  1145. $subAdminManager = $this->groupManager->getSubAdmin();
  1146. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  1147. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID());
  1148. if (!$isAdmin && !($isDelegatedAdmin && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  1149. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1150. }
  1151. $this->remoteWipe->markAllTokensForWipe($targetUser);
  1152. return new DataResponse();
  1153. }
  1154. /**
  1155. * Delete a user
  1156. *
  1157. * @param string $userId ID of the user
  1158. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1159. * @throws OCSException
  1160. *
  1161. * 200: User deleted successfully
  1162. */
  1163. #[PasswordConfirmationRequired]
  1164. #[NoAdminRequired]
  1165. public function deleteUser(string $userId): DataResponse {
  1166. $currentLoggedInUser = $this->userSession->getUser();
  1167. $targetUser = $this->userManager->get($userId);
  1168. if ($targetUser === null) {
  1169. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1170. }
  1171. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  1172. throw new OCSException('', 101);
  1173. }
  1174. // If not permitted
  1175. $subAdminManager = $this->groupManager->getSubAdmin();
  1176. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  1177. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID());
  1178. if (!$isAdmin && !($isDelegatedAdmin && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  1179. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1180. }
  1181. // Go ahead with the delete
  1182. if ($targetUser->delete()) {
  1183. return new DataResponse();
  1184. } else {
  1185. throw new OCSException('', 101);
  1186. }
  1187. }
  1188. /**
  1189. * Disable a user
  1190. *
  1191. * @param string $userId ID of the user
  1192. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1193. * @throws OCSException
  1194. *
  1195. * 200: User disabled successfully
  1196. */
  1197. #[PasswordConfirmationRequired]
  1198. #[NoAdminRequired]
  1199. public function disableUser(string $userId): DataResponse {
  1200. return $this->setEnabled($userId, false);
  1201. }
  1202. /**
  1203. * Enable a user
  1204. *
  1205. * @param string $userId ID of the user
  1206. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1207. * @throws OCSException
  1208. *
  1209. * 200: User enabled successfully
  1210. */
  1211. #[PasswordConfirmationRequired]
  1212. #[NoAdminRequired]
  1213. public function enableUser(string $userId): DataResponse {
  1214. return $this->setEnabled($userId, true);
  1215. }
  1216. /**
  1217. * @param string $userId
  1218. * @param bool $value
  1219. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1220. * @throws OCSException
  1221. */
  1222. private function setEnabled(string $userId, bool $value): DataResponse {
  1223. $currentLoggedInUser = $this->userSession->getUser();
  1224. $targetUser = $this->userManager->get($userId);
  1225. if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
  1226. throw new OCSException('', 101);
  1227. }
  1228. // If not permitted
  1229. $subAdminManager = $this->groupManager->getSubAdmin();
  1230. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  1231. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID());
  1232. if (!$isAdmin && !($isDelegatedAdmin && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  1233. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1234. }
  1235. // enable/disable the user now
  1236. $targetUser->setEnabled($value);
  1237. return new DataResponse();
  1238. }
  1239. /**
  1240. * @NoSubAdminRequired
  1241. *
  1242. * Get a list of groups the user belongs to
  1243. *
  1244. * @param string $userId ID of the user
  1245. * @return DataResponse<Http::STATUS_OK, array{groups: string[]}, array{}>
  1246. * @throws OCSException
  1247. *
  1248. * 200: Users groups returned
  1249. */
  1250. #[NoAdminRequired]
  1251. public function getUsersGroups(string $userId): DataResponse {
  1252. $loggedInUser = $this->userSession->getUser();
  1253. $targetUser = $this->userManager->get($userId);
  1254. if ($targetUser === null) {
  1255. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1256. }
  1257. $isAdmin = $this->groupManager->isAdmin($loggedInUser->getUID());
  1258. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($loggedInUser->getUID());
  1259. if ($targetUser->getUID() === $loggedInUser->getUID() || $isAdmin || $isDelegatedAdmin) {
  1260. // Self lookup or admin lookup
  1261. return new DataResponse([
  1262. 'groups' => $this->groupManager->getUserGroupIds($targetUser)
  1263. ]);
  1264. } else {
  1265. $subAdminManager = $this->groupManager->getSubAdmin();
  1266. // Looking up someone else
  1267. if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
  1268. // Return the group that the method caller is subadmin of for the user in question
  1269. /** @var IGroup[] $getSubAdminsGroups */
  1270. $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
  1271. foreach ($getSubAdminsGroups as $key => $group) {
  1272. $getSubAdminsGroups[$key] = $group->getGID();
  1273. }
  1274. /** @var string[] $groups */
  1275. $groups = array_intersect(
  1276. $getSubAdminsGroups,
  1277. $this->groupManager->getUserGroupIds($targetUser)
  1278. );
  1279. return new DataResponse(['groups' => $groups]);
  1280. } else {
  1281. // Not permitted
  1282. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1283. }
  1284. }
  1285. }
  1286. /**
  1287. * Add a user to a group
  1288. *
  1289. * @param string $userId ID of the user
  1290. * @param string $groupid ID of the group
  1291. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1292. * @throws OCSException
  1293. *
  1294. * 200: User added to group successfully
  1295. */
  1296. #[PasswordConfirmationRequired]
  1297. #[NoAdminRequired]
  1298. public function addToGroup(string $userId, string $groupid = ''): DataResponse {
  1299. if ($groupid === '') {
  1300. throw new OCSException('', 101);
  1301. }
  1302. $group = $this->groupManager->get($groupid);
  1303. $targetUser = $this->userManager->get($userId);
  1304. if ($group === null) {
  1305. throw new OCSException('', 102);
  1306. }
  1307. if ($targetUser === null) {
  1308. throw new OCSException('', 103);
  1309. }
  1310. // If they're not an admin, check they are a subadmin of the group in question
  1311. $loggedInUser = $this->userSession->getUser();
  1312. $subAdminManager = $this->groupManager->getSubAdmin();
  1313. $isAdmin = $this->groupManager->isAdmin($loggedInUser->getUID());
  1314. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($loggedInUser->getUID());
  1315. if (!$isAdmin && !($isDelegatedAdmin && $groupid !== 'admin') && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
  1316. throw new OCSException('', 104);
  1317. }
  1318. // Add user to group
  1319. $group->addUser($targetUser);
  1320. return new DataResponse();
  1321. }
  1322. /**
  1323. * Remove a user from a group
  1324. *
  1325. * @param string $userId ID of the user
  1326. * @param string $groupid ID of the group
  1327. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1328. * @throws OCSException
  1329. *
  1330. * 200: User removed from group successfully
  1331. */
  1332. #[PasswordConfirmationRequired]
  1333. #[NoAdminRequired]
  1334. public function removeFromGroup(string $userId, string $groupid): DataResponse {
  1335. $loggedInUser = $this->userSession->getUser();
  1336. if ($groupid === null || trim($groupid) === '') {
  1337. throw new OCSException('', 101);
  1338. }
  1339. $group = $this->groupManager->get($groupid);
  1340. if ($group === null) {
  1341. throw new OCSException('', 102);
  1342. }
  1343. $targetUser = $this->userManager->get($userId);
  1344. if ($targetUser === null) {
  1345. throw new OCSException('', 103);
  1346. }
  1347. // If they're not an admin, check they are a subadmin of the group in question
  1348. $subAdminManager = $this->groupManager->getSubAdmin();
  1349. $isAdmin = $this->groupManager->isAdmin($loggedInUser->getUID());
  1350. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($loggedInUser->getUID());
  1351. if (!$isAdmin && !($isDelegatedAdmin && $groupid !== 'admin') && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
  1352. throw new OCSException('', 104);
  1353. }
  1354. // Check they aren't removing themselves from 'admin' or their 'subadmin; group
  1355. if ($targetUser->getUID() === $loggedInUser->getUID()) {
  1356. if ($isAdmin || $isDelegatedAdmin) {
  1357. if ($group->getGID() === 'admin') {
  1358. throw new OCSException($this->l10n->t('Cannot remove yourself from the admin group'), 105);
  1359. }
  1360. } else {
  1361. // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
  1362. throw new OCSException($this->l10n->t('Cannot remove yourself from this group as you are a sub-admin'), 105);
  1363. }
  1364. } elseif (!($isAdmin || $isDelegatedAdmin)) {
  1365. /** @var IGroup[] $subAdminGroups */
  1366. $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
  1367. $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
  1368. return $subAdminGroup->getGID();
  1369. }, $subAdminGroups);
  1370. $userGroups = $this->groupManager->getUserGroupIds($targetUser);
  1371. $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
  1372. if (count($userSubAdminGroups) <= 1) {
  1373. // Subadmin must not be able to remove a user from all their subadmin groups.
  1374. throw new OCSException($this->l10n->t('Not viable to remove user from the last group you are sub-admin of'), 105);
  1375. }
  1376. }
  1377. // Remove user from group
  1378. $group->removeUser($targetUser);
  1379. return new DataResponse();
  1380. }
  1381. /**
  1382. * Make a user a subadmin of a group
  1383. *
  1384. * @param string $userId ID of the user
  1385. * @param string $groupid ID of the group
  1386. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1387. * @throws OCSException
  1388. *
  1389. * 200: User added as group subadmin successfully
  1390. */
  1391. #[AuthorizedAdminSetting(settings:Users::class)]
  1392. #[PasswordConfirmationRequired]
  1393. public function addSubAdmin(string $userId, string $groupid): DataResponse {
  1394. $group = $this->groupManager->get($groupid);
  1395. $user = $this->userManager->get($userId);
  1396. // Check if the user exists
  1397. if ($user === null) {
  1398. throw new OCSException($this->l10n->t('User does not exist'), 101);
  1399. }
  1400. // Check if group exists
  1401. if ($group === null) {
  1402. throw new OCSException($this->l10n->t('Group does not exist'), 102);
  1403. }
  1404. // Check if trying to make subadmin of admin group
  1405. if ($group->getGID() === 'admin') {
  1406. throw new OCSException($this->l10n->t('Cannot create sub-admins for admin group'), 103);
  1407. }
  1408. $subAdminManager = $this->groupManager->getSubAdmin();
  1409. // We cannot be subadmin twice
  1410. if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
  1411. return new DataResponse();
  1412. }
  1413. // Go
  1414. $subAdminManager->createSubAdmin($user, $group);
  1415. return new DataResponse();
  1416. }
  1417. /**
  1418. * Remove a user from the subadmins of a group
  1419. *
  1420. * @param string $userId ID of the user
  1421. * @param string $groupid ID of the group
  1422. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1423. * @throws OCSException
  1424. *
  1425. * 200: User removed as group subadmin successfully
  1426. */
  1427. #[AuthorizedAdminSetting(settings:Users::class)]
  1428. #[PasswordConfirmationRequired]
  1429. public function removeSubAdmin(string $userId, string $groupid): DataResponse {
  1430. $group = $this->groupManager->get($groupid);
  1431. $user = $this->userManager->get($userId);
  1432. $subAdminManager = $this->groupManager->getSubAdmin();
  1433. // Check if the user exists
  1434. if ($user === null) {
  1435. throw new OCSException($this->l10n->t('User does not exist'), 101);
  1436. }
  1437. // Check if the group exists
  1438. if ($group === null) {
  1439. throw new OCSException($this->l10n->t('Group does not exist'), 101);
  1440. }
  1441. // Check if they are a subadmin of this said group
  1442. if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
  1443. throw new OCSException($this->l10n->t('User is not a sub-admin of this group'), 102);
  1444. }
  1445. // Go
  1446. $subAdminManager->deleteSubAdmin($user, $group);
  1447. return new DataResponse();
  1448. }
  1449. /**
  1450. * Get the groups a user is a subadmin of
  1451. *
  1452. * @param string $userId ID if the user
  1453. * @return DataResponse<Http::STATUS_OK, string[], array{}>
  1454. * @throws OCSException
  1455. *
  1456. * 200: User subadmin groups returned
  1457. */
  1458. #[AuthorizedAdminSetting(settings:Users::class)]
  1459. public function getUserSubAdminGroups(string $userId): DataResponse {
  1460. $groups = $this->getUserSubAdminGroupsData($userId);
  1461. return new DataResponse($groups);
  1462. }
  1463. /**
  1464. * Resend the welcome message
  1465. *
  1466. * @param string $userId ID if the user
  1467. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1468. * @throws OCSException
  1469. *
  1470. * 200: Resent welcome message successfully
  1471. */
  1472. #[PasswordConfirmationRequired]
  1473. #[NoAdminRequired]
  1474. public function resendWelcomeMessage(string $userId): DataResponse {
  1475. $currentLoggedInUser = $this->userSession->getUser();
  1476. $targetUser = $this->userManager->get($userId);
  1477. if ($targetUser === null) {
  1478. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1479. }
  1480. // Check if admin / subadmin
  1481. $subAdminManager = $this->groupManager->getSubAdmin();
  1482. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  1483. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID());
  1484. if (
  1485. !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  1486. && !($isAdmin || $isDelegatedAdmin)
  1487. ) {
  1488. // No rights
  1489. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1490. }
  1491. $email = $targetUser->getEMailAddress();
  1492. if ($email === '' || $email === null) {
  1493. throw new OCSException($this->l10n->t('Email address not available'), 101);
  1494. }
  1495. try {
  1496. if ($this->config->getUserValue($targetUser->getUID(), 'core', 'lostpassword')) {
  1497. $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, true);
  1498. } else {
  1499. $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
  1500. }
  1501. $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
  1502. } catch (\Exception $e) {
  1503. $this->logger->error(
  1504. "Can't send new user mail to $email",
  1505. [
  1506. 'app' => 'settings',
  1507. 'exception' => $e,
  1508. ]
  1509. );
  1510. throw new OCSException($this->l10n->t('Sending email failed'), 102);
  1511. }
  1512. return new DataResponse();
  1513. }
  1514. }