You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UsersController.php 51KB

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