UsersController.php 51 KB

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