1
0

UsersController.php 52 KB

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