UsersController.php 46 KB

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