UsersController.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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. * @UserRateThrottle(limit=5, period=60)
  576. *
  577. * @throws OCSException
  578. */
  579. public function editUserMultiValue(
  580. string $userId,
  581. string $collectionName,
  582. string $key,
  583. string $value
  584. ): DataResponse {
  585. $currentLoggedInUser = $this->userSession->getUser();
  586. if ($currentLoggedInUser === null) {
  587. throw new OCSException('', OCSController::RESPOND_UNAUTHORISED);
  588. }
  589. $targetUser = $this->userManager->get($userId);
  590. if ($targetUser === null) {
  591. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  592. }
  593. $subAdminManager = $this->groupManager->getSubAdmin();
  594. $isAdminOrSubadmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID())
  595. || $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser);
  596. $permittedFields = [];
  597. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  598. // Editing self (display, email)
  599. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  600. $permittedFields[] = IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX;
  601. } else {
  602. // Check if admin / subadmin
  603. if ($isAdminOrSubadmin) {
  604. // They have permissions over the user
  605. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  606. } else {
  607. // No rights
  608. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  609. }
  610. }
  611. // Check if permitted to edit this field
  612. if (!in_array($collectionName, $permittedFields)) {
  613. throw new OCSException('', 103);
  614. }
  615. switch ($collectionName) {
  616. case IAccountManager::COLLECTION_EMAIL:
  617. $userAccount = $this->accountManager->getAccount($targetUser);
  618. $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  619. $mailCollection->removePropertyByValue($key);
  620. if ($value !== '') {
  621. $mailCollection->addPropertyWithDefaults($value);
  622. $property = $mailCollection->getPropertyByValue($key);
  623. if ($isAdminOrSubadmin && $property) {
  624. // admin set mails are auto-verified
  625. $property->setLocallyVerified(IAccountManager::VERIFIED);
  626. }
  627. }
  628. $this->accountManager->updateAccount($userAccount);
  629. break;
  630. case IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX:
  631. $userAccount = $this->accountManager->getAccount($targetUser);
  632. $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  633. $targetProperty = null;
  634. foreach ($mailCollection->getProperties() as $property) {
  635. if ($property->getValue() === $key) {
  636. $targetProperty = $property;
  637. break;
  638. }
  639. }
  640. if ($targetProperty instanceof IAccountProperty) {
  641. try {
  642. $targetProperty->setScope($value);
  643. $this->accountManager->updateAccount($userAccount);
  644. } catch (InvalidArgumentException $e) {
  645. throw new OCSException('', 102);
  646. }
  647. } else {
  648. throw new OCSException('', 102);
  649. }
  650. break;
  651. default:
  652. throw new OCSException('', 103);
  653. }
  654. return new DataResponse();
  655. }
  656. /**
  657. * @NoAdminRequired
  658. * @NoSubAdminRequired
  659. * @PasswordConfirmationRequired
  660. * @UserRateThrottle(limit=50, period=600)
  661. *
  662. * edit users
  663. *
  664. * @param string $userId
  665. * @param string $key
  666. * @param string $value
  667. * @return DataResponse
  668. * @throws OCSException
  669. */
  670. public function editUser(string $userId, string $key, string $value): DataResponse {
  671. $currentLoggedInUser = $this->userSession->getUser();
  672. $targetUser = $this->userManager->get($userId);
  673. if ($targetUser === null) {
  674. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  675. }
  676. $permittedFields = [];
  677. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  678. // Editing self (display, email)
  679. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  680. if (
  681. $targetUser->getBackend() instanceof ISetDisplayNameBackend
  682. || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
  683. ) {
  684. $permittedFields[] = self::USER_FIELD_DISPLAYNAME;
  685. $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
  686. }
  687. $permittedFields[] = IAccountManager::PROPERTY_EMAIL;
  688. }
  689. $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX;
  690. $permittedFields[] = IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX;
  691. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  692. $permittedFields[] = self::USER_FIELD_PASSWORD;
  693. $permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL;
  694. if (
  695. $this->config->getSystemValue('force_language', false) === false ||
  696. $this->groupManager->isAdmin($currentLoggedInUser->getUID())
  697. ) {
  698. $permittedFields[] = self::USER_FIELD_LANGUAGE;
  699. }
  700. if (
  701. $this->config->getSystemValue('force_locale', false) === false ||
  702. $this->groupManager->isAdmin($currentLoggedInUser->getUID())
  703. ) {
  704. $permittedFields[] = self::USER_FIELD_LOCALE;
  705. }
  706. $permittedFields[] = IAccountManager::PROPERTY_PHONE;
  707. $permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
  708. $permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
  709. $permittedFields[] = IAccountManager::PROPERTY_TWITTER;
  710. $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
  711. $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
  712. $permittedFields[] = IAccountManager::PROPERTY_ROLE;
  713. $permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
  714. $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
  715. $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
  716. $permittedFields[] = IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX;
  717. $permittedFields[] = IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX;
  718. $permittedFields[] = IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX;
  719. $permittedFields[] = IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX;
  720. $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX;
  721. $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX;
  722. $permittedFields[] = IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX;
  723. $permittedFields[] = IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX;
  724. $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX;
  725. $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX;
  726. $permittedFields[] = IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX;
  727. // If admin they can edit their own quota
  728. if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  729. $permittedFields[] = self::USER_FIELD_QUOTA;
  730. }
  731. } else {
  732. // Check if admin / subadmin
  733. $subAdminManager = $this->groupManager->getSubAdmin();
  734. if (
  735. $this->groupManager->isAdmin($currentLoggedInUser->getUID())
  736. || $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  737. ) {
  738. // They have permissions over the user
  739. if (
  740. $targetUser->getBackend() instanceof ISetDisplayNameBackend
  741. || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
  742. ) {
  743. $permittedFields[] = self::USER_FIELD_DISPLAYNAME;
  744. $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
  745. }
  746. $permittedFields[] = IAccountManager::PROPERTY_EMAIL;
  747. $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
  748. $permittedFields[] = self::USER_FIELD_PASSWORD;
  749. $permittedFields[] = self::USER_FIELD_LANGUAGE;
  750. $permittedFields[] = self::USER_FIELD_LOCALE;
  751. $permittedFields[] = IAccountManager::PROPERTY_PHONE;
  752. $permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
  753. $permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
  754. $permittedFields[] = IAccountManager::PROPERTY_TWITTER;
  755. $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
  756. $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
  757. $permittedFields[] = IAccountManager::PROPERTY_ROLE;
  758. $permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
  759. $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
  760. $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
  761. $permittedFields[] = self::USER_FIELD_QUOTA;
  762. $permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL;
  763. } else {
  764. // No rights
  765. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  766. }
  767. }
  768. // Check if permitted to edit this field
  769. if (!in_array($key, $permittedFields)) {
  770. throw new OCSException('', 103);
  771. }
  772. // Process the edit
  773. switch ($key) {
  774. case self::USER_FIELD_DISPLAYNAME:
  775. case IAccountManager::PROPERTY_DISPLAYNAME:
  776. try {
  777. $targetUser->setDisplayName($value);
  778. } catch (InvalidArgumentException $e) {
  779. throw new OCSException($e->getMessage(), 101);
  780. }
  781. break;
  782. case self::USER_FIELD_QUOTA:
  783. $quota = $value;
  784. if ($quota !== 'none' && $quota !== 'default') {
  785. if (is_numeric($quota)) {
  786. $quota = (float) $quota;
  787. } else {
  788. $quota = \OCP\Util::computerFileSize($quota);
  789. }
  790. if ($quota === false) {
  791. throw new OCSException('Invalid quota value ' . $value, 102);
  792. }
  793. if ($quota === -1) {
  794. $quota = 'none';
  795. } else {
  796. $maxQuota = (int) $this->config->getAppValue('files', 'max_quota', '-1');
  797. if ($maxQuota !== -1 && $quota > $maxQuota) {
  798. throw new OCSException('Invalid quota value. ' . $value . ' is exceeding the maximum quota', 102);
  799. }
  800. $quota = \OCP\Util::humanFileSize($quota);
  801. }
  802. }
  803. // no else block because quota can be set to 'none' in previous if
  804. if ($quota === 'none') {
  805. $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
  806. if (!$allowUnlimitedQuota) {
  807. throw new OCSException('Unlimited quota is forbidden on this instance', 102);
  808. }
  809. }
  810. $targetUser->setQuota($quota);
  811. break;
  812. case self::USER_FIELD_PASSWORD:
  813. try {
  814. if (strlen($value) > IUserManager::MAX_PASSWORD_LENGTH) {
  815. throw new OCSException('Invalid password value', 102);
  816. }
  817. if (!$targetUser->canChangePassword()) {
  818. throw new OCSException('Setting the password is not supported by the users backend', 103);
  819. }
  820. $targetUser->setPassword($value);
  821. } catch (HintException $e) { // password policy error
  822. throw new OCSException($e->getMessage(), 103);
  823. }
  824. break;
  825. case self::USER_FIELD_LANGUAGE:
  826. $languagesCodes = $this->l10nFactory->findAvailableLanguages();
  827. if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
  828. throw new OCSException('Invalid language', 102);
  829. }
  830. $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
  831. break;
  832. case self::USER_FIELD_LOCALE:
  833. if (!$this->l10nFactory->localeExists($value)) {
  834. throw new OCSException('Invalid locale', 102);
  835. }
  836. $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
  837. break;
  838. case self::USER_FIELD_NOTIFICATION_EMAIL:
  839. $success = false;
  840. if ($value === '' || filter_var($value, FILTER_VALIDATE_EMAIL)) {
  841. try {
  842. $targetUser->setPrimaryEMailAddress($value);
  843. $success = true;
  844. } catch (InvalidArgumentException $e) {
  845. $this->logger->info(
  846. 'Cannot set primary email, because provided address is not verified',
  847. [
  848. 'app' => 'provisioning_api',
  849. 'exception' => $e,
  850. ]
  851. );
  852. }
  853. }
  854. if (!$success) {
  855. throw new OCSException('', 102);
  856. }
  857. break;
  858. case IAccountManager::PROPERTY_EMAIL:
  859. if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
  860. $targetUser->setEMailAddress($value);
  861. } else {
  862. throw new OCSException('', 102);
  863. }
  864. break;
  865. case IAccountManager::COLLECTION_EMAIL:
  866. if (filter_var($value, FILTER_VALIDATE_EMAIL) && $value !== $targetUser->getSystemEMailAddress()) {
  867. $userAccount = $this->accountManager->getAccount($targetUser);
  868. $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  869. foreach ($mailCollection->getProperties() as $property) {
  870. if ($property->getValue() === $value) {
  871. break;
  872. }
  873. }
  874. $mailCollection->addPropertyWithDefaults($value);
  875. $this->accountManager->updateAccount($userAccount);
  876. } else {
  877. throw new OCSException('', 102);
  878. }
  879. break;
  880. case IAccountManager::PROPERTY_PHONE:
  881. case IAccountManager::PROPERTY_ADDRESS:
  882. case IAccountManager::PROPERTY_WEBSITE:
  883. case IAccountManager::PROPERTY_TWITTER:
  884. case IAccountManager::PROPERTY_FEDIVERSE:
  885. case IAccountManager::PROPERTY_ORGANISATION:
  886. case IAccountManager::PROPERTY_ROLE:
  887. case IAccountManager::PROPERTY_HEADLINE:
  888. case IAccountManager::PROPERTY_BIOGRAPHY:
  889. $userAccount = $this->accountManager->getAccount($targetUser);
  890. try {
  891. $userProperty = $userAccount->getProperty($key);
  892. if ($userProperty->getValue() !== $value) {
  893. try {
  894. $userProperty->setValue($value);
  895. if ($userProperty->getName() === IAccountManager::PROPERTY_PHONE) {
  896. $this->knownUserService->deleteByContactUserId($targetUser->getUID());
  897. }
  898. } catch (InvalidArgumentException $e) {
  899. throw new OCSException('Invalid ' . $e->getMessage(), 102);
  900. }
  901. }
  902. } catch (PropertyDoesNotExistException $e) {
  903. $userAccount->setProperty($key, $value, IAccountManager::SCOPE_PRIVATE, IAccountManager::NOT_VERIFIED);
  904. }
  905. try {
  906. $this->accountManager->updateAccount($userAccount);
  907. } catch (InvalidArgumentException $e) {
  908. throw new OCSException('Invalid ' . $e->getMessage(), 102);
  909. }
  910. break;
  911. case IAccountManager::PROPERTY_PROFILE_ENABLED:
  912. $userAccount = $this->accountManager->getAccount($targetUser);
  913. try {
  914. $userProperty = $userAccount->getProperty($key);
  915. if ($userProperty->getValue() !== $value) {
  916. $userProperty->setValue($value);
  917. }
  918. } catch (PropertyDoesNotExistException $e) {
  919. $userAccount->setProperty($key, $value, IAccountManager::SCOPE_LOCAL, IAccountManager::NOT_VERIFIED);
  920. }
  921. $this->accountManager->updateAccount($userAccount);
  922. break;
  923. case IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX:
  924. case IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX:
  925. case IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX:
  926. case IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX:
  927. case IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX:
  928. case IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX:
  929. case IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX:
  930. case IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX:
  931. case IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX:
  932. case IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX:
  933. case IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX:
  934. case IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX:
  935. case IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX:
  936. $propertyName = substr($key, 0, strlen($key) - strlen(self::SCOPE_SUFFIX));
  937. $userAccount = $this->accountManager->getAccount($targetUser);
  938. $userProperty = $userAccount->getProperty($propertyName);
  939. if ($userProperty->getScope() !== $value) {
  940. try {
  941. $userProperty->setScope($value);
  942. $this->accountManager->updateAccount($userAccount);
  943. } catch (InvalidArgumentException $e) {
  944. throw new OCSException('Invalid ' . $e->getMessage(), 102);
  945. }
  946. }
  947. break;
  948. default:
  949. throw new OCSException('', 103);
  950. }
  951. return new DataResponse();
  952. }
  953. /**
  954. * @PasswordConfirmationRequired
  955. * @NoAdminRequired
  956. *
  957. * @param string $userId
  958. *
  959. * @return DataResponse
  960. *
  961. * @throws OCSException
  962. */
  963. public function wipeUserDevices(string $userId): DataResponse {
  964. /** @var IUser $currentLoggedInUser */
  965. $currentLoggedInUser = $this->userSession->getUser();
  966. $targetUser = $this->userManager->get($userId);
  967. if ($targetUser === null) {
  968. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  969. }
  970. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  971. throw new OCSException('', 101);
  972. }
  973. // If not permitted
  974. $subAdminManager = $this->groupManager->getSubAdmin();
  975. if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  976. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  977. }
  978. $this->remoteWipe->markAllTokensForWipe($targetUser);
  979. return new DataResponse();
  980. }
  981. /**
  982. * @PasswordConfirmationRequired
  983. * @NoAdminRequired
  984. *
  985. * @param string $userId
  986. * @return DataResponse
  987. * @throws OCSException
  988. */
  989. public function deleteUser(string $userId): DataResponse {
  990. $currentLoggedInUser = $this->userSession->getUser();
  991. $targetUser = $this->userManager->get($userId);
  992. if ($targetUser === null) {
  993. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  994. }
  995. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  996. throw new OCSException('', 101);
  997. }
  998. // If not permitted
  999. $subAdminManager = $this->groupManager->getSubAdmin();
  1000. if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  1001. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1002. }
  1003. // Go ahead with the delete
  1004. if ($targetUser->delete()) {
  1005. return new DataResponse();
  1006. } else {
  1007. throw new OCSException('', 101);
  1008. }
  1009. }
  1010. /**
  1011. * @PasswordConfirmationRequired
  1012. * @NoAdminRequired
  1013. *
  1014. * @param string $userId
  1015. * @return DataResponse
  1016. * @throws OCSException
  1017. * @throws OCSForbiddenException
  1018. */
  1019. public function disableUser(string $userId): DataResponse {
  1020. return $this->setEnabled($userId, false);
  1021. }
  1022. /**
  1023. * @PasswordConfirmationRequired
  1024. * @NoAdminRequired
  1025. *
  1026. * @param string $userId
  1027. * @return DataResponse
  1028. * @throws OCSException
  1029. * @throws OCSForbiddenException
  1030. */
  1031. public function enableUser(string $userId): DataResponse {
  1032. return $this->setEnabled($userId, true);
  1033. }
  1034. /**
  1035. * @param string $userId
  1036. * @param bool $value
  1037. * @return DataResponse
  1038. * @throws OCSException
  1039. */
  1040. private function setEnabled(string $userId, bool $value): DataResponse {
  1041. $currentLoggedInUser = $this->userSession->getUser();
  1042. $targetUser = $this->userManager->get($userId);
  1043. if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
  1044. throw new OCSException('', 101);
  1045. }
  1046. // If not permitted
  1047. $subAdminManager = $this->groupManager->getSubAdmin();
  1048. if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  1049. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1050. }
  1051. // enable/disable the user now
  1052. $targetUser->setEnabled($value);
  1053. return new DataResponse();
  1054. }
  1055. /**
  1056. * @NoAdminRequired
  1057. * @NoSubAdminRequired
  1058. *
  1059. * @param string $userId
  1060. * @return DataResponse
  1061. * @throws OCSException
  1062. */
  1063. public function getUsersGroups(string $userId): DataResponse {
  1064. $loggedInUser = $this->userSession->getUser();
  1065. $targetUser = $this->userManager->get($userId);
  1066. if ($targetUser === null) {
  1067. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1068. }
  1069. if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
  1070. // Self lookup or admin lookup
  1071. return new DataResponse([
  1072. 'groups' => $this->groupManager->getUserGroupIds($targetUser)
  1073. ]);
  1074. } else {
  1075. $subAdminManager = $this->groupManager->getSubAdmin();
  1076. // Looking up someone else
  1077. if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
  1078. // Return the group that the method caller is subadmin of for the user in question
  1079. /** @var IGroup[] $getSubAdminsGroups */
  1080. $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
  1081. foreach ($getSubAdminsGroups as $key => $group) {
  1082. $getSubAdminsGroups[$key] = $group->getGID();
  1083. }
  1084. $groups = array_intersect(
  1085. $getSubAdminsGroups,
  1086. $this->groupManager->getUserGroupIds($targetUser)
  1087. );
  1088. return new DataResponse(['groups' => $groups]);
  1089. } else {
  1090. // Not permitted
  1091. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1092. }
  1093. }
  1094. }
  1095. /**
  1096. * @PasswordConfirmationRequired
  1097. * @NoAdminRequired
  1098. *
  1099. * @param string $userId
  1100. * @param string $groupid
  1101. * @return DataResponse
  1102. * @throws OCSException
  1103. */
  1104. public function addToGroup(string $userId, string $groupid = ''): DataResponse {
  1105. if ($groupid === '') {
  1106. throw new OCSException('', 101);
  1107. }
  1108. $group = $this->groupManager->get($groupid);
  1109. $targetUser = $this->userManager->get($userId);
  1110. if ($group === null) {
  1111. throw new OCSException('', 102);
  1112. }
  1113. if ($targetUser === null) {
  1114. throw new OCSException('', 103);
  1115. }
  1116. // If they're not an admin, check they are a subadmin of the group in question
  1117. $loggedInUser = $this->userSession->getUser();
  1118. $subAdminManager = $this->groupManager->getSubAdmin();
  1119. if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
  1120. throw new OCSException('', 104);
  1121. }
  1122. // Add user to group
  1123. $group->addUser($targetUser);
  1124. return new DataResponse();
  1125. }
  1126. /**
  1127. * @PasswordConfirmationRequired
  1128. * @NoAdminRequired
  1129. *
  1130. * @param string $userId
  1131. * @param string $groupid
  1132. * @return DataResponse
  1133. * @throws OCSException
  1134. */
  1135. public function removeFromGroup(string $userId, string $groupid): DataResponse {
  1136. $loggedInUser = $this->userSession->getUser();
  1137. if ($groupid === null || trim($groupid) === '') {
  1138. throw new OCSException('', 101);
  1139. }
  1140. $group = $this->groupManager->get($groupid);
  1141. if ($group === null) {
  1142. throw new OCSException('', 102);
  1143. }
  1144. $targetUser = $this->userManager->get($userId);
  1145. if ($targetUser === null) {
  1146. throw new OCSException('', 103);
  1147. }
  1148. // If they're not an admin, check they are a subadmin of the group in question
  1149. $subAdminManager = $this->groupManager->getSubAdmin();
  1150. if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
  1151. throw new OCSException('', 104);
  1152. }
  1153. // Check they aren't removing themselves from 'admin' or their 'subadmin; group
  1154. if ($targetUser->getUID() === $loggedInUser->getUID()) {
  1155. if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
  1156. if ($group->getGID() === 'admin') {
  1157. throw new OCSException('Cannot remove yourself from the admin group', 105);
  1158. }
  1159. } else {
  1160. // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
  1161. throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
  1162. }
  1163. } elseif (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
  1164. /** @var IGroup[] $subAdminGroups */
  1165. $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
  1166. $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
  1167. return $subAdminGroup->getGID();
  1168. }, $subAdminGroups);
  1169. $userGroups = $this->groupManager->getUserGroupIds($targetUser);
  1170. $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
  1171. if (count($userSubAdminGroups) <= 1) {
  1172. // Subadmin must not be able to remove a user from all their subadmin groups.
  1173. throw new OCSException('Not viable to remove user from the last group you are SubAdmin of', 105);
  1174. }
  1175. }
  1176. // Remove user from group
  1177. $group->removeUser($targetUser);
  1178. return new DataResponse();
  1179. }
  1180. /**
  1181. * Creates a subadmin
  1182. *
  1183. * @PasswordConfirmationRequired
  1184. *
  1185. * @param string $userId
  1186. * @param string $groupid
  1187. * @return DataResponse
  1188. * @throws OCSException
  1189. */
  1190. public function addSubAdmin(string $userId, string $groupid): DataResponse {
  1191. $group = $this->groupManager->get($groupid);
  1192. $user = $this->userManager->get($userId);
  1193. // Check if the user exists
  1194. if ($user === null) {
  1195. throw new OCSException('User does not exist', 101);
  1196. }
  1197. // Check if group exists
  1198. if ($group === null) {
  1199. throw new OCSException('Group does not exist', 102);
  1200. }
  1201. // Check if trying to make subadmin of admin group
  1202. if ($group->getGID() === 'admin') {
  1203. throw new OCSException('Cannot create subadmins for admin group', 103);
  1204. }
  1205. $subAdminManager = $this->groupManager->getSubAdmin();
  1206. // We cannot be subadmin twice
  1207. if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
  1208. return new DataResponse();
  1209. }
  1210. // Go
  1211. $subAdminManager->createSubAdmin($user, $group);
  1212. return new DataResponse();
  1213. }
  1214. /**
  1215. * Removes a subadmin from a group
  1216. *
  1217. * @PasswordConfirmationRequired
  1218. *
  1219. * @param string $userId
  1220. * @param string $groupid
  1221. * @return DataResponse
  1222. * @throws OCSException
  1223. */
  1224. public function removeSubAdmin(string $userId, string $groupid): DataResponse {
  1225. $group = $this->groupManager->get($groupid);
  1226. $user = $this->userManager->get($userId);
  1227. $subAdminManager = $this->groupManager->getSubAdmin();
  1228. // Check if the user exists
  1229. if ($user === null) {
  1230. throw new OCSException('User does not exist', 101);
  1231. }
  1232. // Check if the group exists
  1233. if ($group === null) {
  1234. throw new OCSException('Group does not exist', 101);
  1235. }
  1236. // Check if they are a subadmin of this said group
  1237. if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
  1238. throw new OCSException('User is not a subadmin of this group', 102);
  1239. }
  1240. // Go
  1241. $subAdminManager->deleteSubAdmin($user, $group);
  1242. return new DataResponse();
  1243. }
  1244. /**
  1245. * Get the groups a user is a subadmin of
  1246. *
  1247. * @param string $userId
  1248. * @return DataResponse
  1249. * @throws OCSException
  1250. */
  1251. public function getUserSubAdminGroups(string $userId): DataResponse {
  1252. $groups = $this->getUserSubAdminGroupsData($userId);
  1253. return new DataResponse($groups);
  1254. }
  1255. /**
  1256. * @NoAdminRequired
  1257. * @PasswordConfirmationRequired
  1258. *
  1259. * resend welcome message
  1260. *
  1261. * @param string $userId
  1262. * @return DataResponse
  1263. * @throws OCSException
  1264. */
  1265. public function resendWelcomeMessage(string $userId): DataResponse {
  1266. $currentLoggedInUser = $this->userSession->getUser();
  1267. $targetUser = $this->userManager->get($userId);
  1268. if ($targetUser === null) {
  1269. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1270. }
  1271. // Check if admin / subadmin
  1272. $subAdminManager = $this->groupManager->getSubAdmin();
  1273. if (
  1274. !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  1275. && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())
  1276. ) {
  1277. // No rights
  1278. throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
  1279. }
  1280. $email = $targetUser->getEMailAddress();
  1281. if ($email === '' || $email === null) {
  1282. throw new OCSException('Email address not available', 101);
  1283. }
  1284. try {
  1285. $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
  1286. $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
  1287. } catch (\Exception $e) {
  1288. $this->logger->error(
  1289. "Can't send new user mail to $email",
  1290. [
  1291. 'app' => 'settings',
  1292. 'exception' => $e,
  1293. ]
  1294. );
  1295. throw new OCSException('Sending email failed', 102);
  1296. }
  1297. return new DataResponse();
  1298. }
  1299. }