UsersController.php 45 KB

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