UsersController.php 52 KB

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