UsersController.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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 Joas Schilling <coding@schilljs.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author michag86 <micha_g@arcor.de>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Tom Needham <tom@owncloud.com>
  15. * @author John Molakvoæ <skjnldsv@protonmail.com>
  16. * @author Thomas Citharel <tcit@tcit.fr>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OCA\Provisioning_API\Controller;
  34. use OC\Accounts\AccountManager;
  35. use OC\HintException;
  36. use OC\Settings\Mailer\NewUserMailHelper;
  37. use OCA\Provisioning_API\FederatedFileSharingFactory;
  38. use OCP\App\IAppManager;
  39. use OCP\AppFramework\Http\DataResponse;
  40. use OCP\AppFramework\OCS\OCSException;
  41. use OCP\AppFramework\OCS\OCSForbiddenException;
  42. use OCP\IConfig;
  43. use OCP\IGroup;
  44. use OCP\IGroupManager;
  45. use OCP\ILogger;
  46. use OCP\IRequest;
  47. use OCP\IUser;
  48. use OCP\IUserManager;
  49. use OCP\IUserSession;
  50. use OCP\L10N\IFactory;
  51. use OCP\Security\ISecureRandom;
  52. class UsersController extends AUserData {
  53. /** @var IAppManager */
  54. private $appManager;
  55. /** @var ILogger */
  56. private $logger;
  57. /** @var IFactory */
  58. private $l10nFactory;
  59. /** @var NewUserMailHelper */
  60. private $newUserMailHelper;
  61. /** @var FederatedFileSharingFactory */
  62. private $federatedFileSharingFactory;
  63. /** @var ISecureRandom */
  64. private $secureRandom;
  65. /**
  66. * @param string $appName
  67. * @param IRequest $request
  68. * @param IUserManager $userManager
  69. * @param IConfig $config
  70. * @param IAppManager $appManager
  71. * @param IGroupManager $groupManager
  72. * @param IUserSession $userSession
  73. * @param AccountManager $accountManager
  74. * @param ILogger $logger
  75. * @param IFactory $l10nFactory
  76. * @param NewUserMailHelper $newUserMailHelper
  77. * @param FederatedFileSharingFactory $federatedFileSharingFactory
  78. * @param ISecureRandom $secureRandom
  79. */
  80. public function __construct(string $appName,
  81. IRequest $request,
  82. IUserManager $userManager,
  83. IConfig $config,
  84. IAppManager $appManager,
  85. IGroupManager $groupManager,
  86. IUserSession $userSession,
  87. AccountManager $accountManager,
  88. ILogger $logger,
  89. IFactory $l10nFactory,
  90. NewUserMailHelper $newUserMailHelper,
  91. FederatedFileSharingFactory $federatedFileSharingFactory,
  92. ISecureRandom $secureRandom) {
  93. parent::__construct($appName,
  94. $request,
  95. $userManager,
  96. $config,
  97. $groupManager,
  98. $userSession,
  99. $accountManager);
  100. $this->appManager = $appManager;
  101. $this->logger = $logger;
  102. $this->l10nFactory = $l10nFactory;
  103. $this->newUserMailHelper = $newUserMailHelper;
  104. $this->federatedFileSharingFactory = $federatedFileSharingFactory;
  105. $this->secureRandom = $secureRandom;
  106. }
  107. /**
  108. * @NoAdminRequired
  109. *
  110. * returns a list of users
  111. *
  112. * @param string $search
  113. * @param int $limit
  114. * @param int $offset
  115. * @return DataResponse
  116. */
  117. public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
  118. $user = $this->userSession->getUser();
  119. $users = [];
  120. // Admin? Or SubAdmin?
  121. $uid = $user->getUID();
  122. $subAdminManager = $this->groupManager->getSubAdmin();
  123. if ($this->groupManager->isAdmin($uid)){
  124. $users = $this->userManager->search($search, $limit, $offset);
  125. } else if ($subAdminManager->isSubAdmin($user)) {
  126. $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
  127. foreach ($subAdminOfGroups as $key => $group) {
  128. $subAdminOfGroups[$key] = $group->getGID();
  129. }
  130. $users = [];
  131. foreach ($subAdminOfGroups as $group) {
  132. $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
  133. }
  134. }
  135. $users = array_keys($users);
  136. return new DataResponse([
  137. 'users' => $users
  138. ]);
  139. }
  140. /**
  141. * @NoAdminRequired
  142. *
  143. * returns a list of users and their data
  144. */
  145. public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
  146. $currentUser = $this->userSession->getUser();
  147. $users = [];
  148. // Admin? Or SubAdmin?
  149. $uid = $currentUser->getUID();
  150. $subAdminManager = $this->groupManager->getSubAdmin();
  151. if ($this->groupManager->isAdmin($uid)){
  152. $users = $this->userManager->search($search, $limit, $offset);
  153. $users = array_keys($users);
  154. } else if ($subAdminManager->isSubAdmin($currentUser)) {
  155. $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
  156. foreach ($subAdminOfGroups as $key => $group) {
  157. $subAdminOfGroups[$key] = $group->getGID();
  158. }
  159. $users = [];
  160. foreach ($subAdminOfGroups as $group) {
  161. $users[] = array_keys($this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
  162. }
  163. $users = array_merge(...$users);
  164. }
  165. $usersDetails = [];
  166. foreach ($users as $userId) {
  167. $userId = (string) $userId;
  168. $userData = $this->getUserData($userId);
  169. // Do not insert empty entry
  170. if (!empty($userData)) {
  171. $usersDetails[$userId] = $userData;
  172. } else {
  173. // Logged user does not have permissions to see this user
  174. // only showing its id
  175. $usersDetails[$userId] = ['id' => $userId];
  176. }
  177. }
  178. return new DataResponse([
  179. 'users' => $usersDetails
  180. ]);
  181. }
  182. /**
  183. * @PasswordConfirmationRequired
  184. * @NoAdminRequired
  185. *
  186. * @param string $userid
  187. * @param string $password
  188. * @param string $displayName
  189. * @param string $email
  190. * @param array $groups
  191. * @param array $subadmin
  192. * @param string $quota
  193. * @param string $language
  194. * @return DataResponse
  195. * @throws OCSException
  196. */
  197. public function addUser(string $userid,
  198. string $password = '',
  199. string $displayName = '',
  200. string $email = '',
  201. array $groups = [],
  202. array $subadmin = [],
  203. string $quota = '',
  204. string $language = ''): DataResponse {
  205. $user = $this->userSession->getUser();
  206. $isAdmin = $this->groupManager->isAdmin($user->getUID());
  207. $subAdminManager = $this->groupManager->getSubAdmin();
  208. if ($this->userManager->userExists($userid)) {
  209. $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
  210. throw new OCSException('User already exists', 102);
  211. }
  212. if ($groups !== []) {
  213. foreach ($groups as $group) {
  214. if (!$this->groupManager->groupExists($group)) {
  215. throw new OCSException('group '.$group.' does not exist', 104);
  216. }
  217. if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
  218. throw new OCSException('insufficient privileges for group '. $group, 105);
  219. }
  220. }
  221. } else {
  222. if (!$isAdmin) {
  223. throw new OCSException('no group specified (required for subadmins)', 106);
  224. }
  225. }
  226. $subadminGroups = [];
  227. if ($subadmin !== []) {
  228. foreach ($subadmin as $groupid) {
  229. $group = $this->groupManager->get($groupid);
  230. // Check if group exists
  231. if ($group === null) {
  232. throw new OCSException('Subadmin group does not exist', 102);
  233. }
  234. // Check if trying to make subadmin of admin group
  235. if ($group->getGID() === 'admin') {
  236. throw new OCSException('Cannot create subadmins for admin group', 103);
  237. }
  238. // Check if has permission to promote subadmins
  239. if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
  240. throw new OCSForbiddenException('No permissions to promote subadmins');
  241. }
  242. $subadminGroups[] = $group;
  243. }
  244. }
  245. $generatePasswordResetToken = false;
  246. if ($password === '') {
  247. if ($email === '') {
  248. throw new OCSException('To send a password link to the user an email address is required.', 108);
  249. }
  250. $password = $this->secureRandom->generate(10);
  251. // Make sure we pass the password_policy
  252. $password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
  253. $generatePasswordResetToken = true;
  254. }
  255. try {
  256. $newUser = $this->userManager->createUser($userid, $password);
  257. $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
  258. foreach ($groups as $group) {
  259. $this->groupManager->get($group)->addUser($newUser);
  260. $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
  261. }
  262. foreach ($subadminGroups as $group) {
  263. $subAdminManager->createSubAdmin($newUser, $group);
  264. }
  265. if ($displayName !== '') {
  266. $this->editUser($userid, 'display', $displayName);
  267. }
  268. if ($quota !== '') {
  269. $this->editUser($userid, 'quota', $quota);
  270. }
  271. if ($language !== '') {
  272. $this->editUser($userid, 'language', $language);
  273. }
  274. // Send new user mail only if a mail is set
  275. if ($email !== '') {
  276. $newUser->setEMailAddress($email);
  277. try {
  278. $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
  279. $this->newUserMailHelper->sendMail($newUser, $emailTemplate);
  280. } catch (\Exception $e) {
  281. $this->logger->logException($e, [
  282. 'message' => "Can't send new user mail to $email",
  283. 'level' => ILogger::ERROR,
  284. 'app' => 'ocs_api',
  285. ]);
  286. throw new OCSException('Unable to send the invitation mail', 109);
  287. }
  288. }
  289. return new DataResponse();
  290. } catch (HintException $e ) {
  291. $this->logger->logException($e, [
  292. 'message' => 'Failed addUser attempt with hint exception.',
  293. 'level' => ILogger::WARN,
  294. 'app' => 'ocs_api',
  295. ]);
  296. throw new OCSException($e->getHint(), 107);
  297. } catch (\Exception $e) {
  298. $this->logger->logException($e, [
  299. 'message' => 'Failed addUser attempt with exception.',
  300. 'level' => ILogger::ERROR,
  301. 'app' => 'ocs_api',
  302. ]);
  303. throw new OCSException('Bad request', 101);
  304. }
  305. }
  306. /**
  307. * @NoAdminRequired
  308. * @NoSubAdminRequired
  309. *
  310. * gets user info
  311. *
  312. * @param string $userId
  313. * @return DataResponse
  314. * @throws OCSException
  315. */
  316. public function getUser(string $userId): DataResponse {
  317. $data = $this->getUserData($userId);
  318. // getUserData returns empty array if not enough permissions
  319. if (empty($data)) {
  320. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  321. }
  322. return new DataResponse($data);
  323. }
  324. /**
  325. * @NoAdminRequired
  326. * @NoSubAdminRequired
  327. *
  328. * gets user info from the currently logged in user
  329. *
  330. * @return DataResponse
  331. * @throws OCSException
  332. */
  333. public function getCurrentUser(): DataResponse {
  334. $user = $this->userSession->getUser();
  335. if ($user) {
  336. $data = $this->getUserData($user->getUID());
  337. // rename "displayname" to "display-name" only for this call to keep
  338. // the API stable.
  339. $data['display-name'] = $data['displayname'];
  340. unset($data['displayname']);
  341. return new DataResponse($data);
  342. }
  343. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  344. }
  345. /**
  346. * @NoAdminRequired
  347. * @NoSubAdminRequired
  348. */
  349. public function getEditableFields(): DataResponse {
  350. $permittedFields = [];
  351. // Editing self (display, email)
  352. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  353. $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
  354. $permittedFields[] = AccountManager::PROPERTY_EMAIL;
  355. }
  356. if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
  357. $federatedFileSharing = $this->federatedFileSharingFactory->get();
  358. $shareProvider = $federatedFileSharing->getFederatedShareProvider();
  359. if ($shareProvider->isLookupServerUploadEnabled()) {
  360. $permittedFields[] = AccountManager::PROPERTY_PHONE;
  361. $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
  362. $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
  363. $permittedFields[] = AccountManager::PROPERTY_TWITTER;
  364. }
  365. }
  366. return new DataResponse($permittedFields);
  367. }
  368. /**
  369. * @NoAdminRequired
  370. * @NoSubAdminRequired
  371. * @PasswordConfirmationRequired
  372. *
  373. * edit users
  374. *
  375. * @param string $userId
  376. * @param string $key
  377. * @param string $value
  378. * @return DataResponse
  379. * @throws OCSException
  380. */
  381. public function editUser(string $userId, string $key, string $value): DataResponse {
  382. $currentLoggedInUser = $this->userSession->getUser();
  383. $targetUser = $this->userManager->get($userId);
  384. if ($targetUser === null) {
  385. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  386. }
  387. $permittedFields = [];
  388. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  389. // Editing self (display, email)
  390. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  391. $permittedFields[] = 'display';
  392. $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
  393. $permittedFields[] = AccountManager::PROPERTY_EMAIL;
  394. }
  395. $permittedFields[] = 'password';
  396. if ($this->config->getSystemValue('force_language', false) === false ||
  397. $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  398. $permittedFields[] = 'language';
  399. }
  400. if ($this->config->getSystemValue('force_locale', false) === false ||
  401. $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  402. $permittedFields[] = 'locale';
  403. }
  404. if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
  405. $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
  406. $shareProvider = $federatedFileSharing->getFederatedShareProvider();
  407. if ($shareProvider->isLookupServerUploadEnabled()) {
  408. $permittedFields[] = AccountManager::PROPERTY_PHONE;
  409. $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
  410. $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
  411. $permittedFields[] = AccountManager::PROPERTY_TWITTER;
  412. }
  413. }
  414. // If admin they can edit their own quota
  415. if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  416. $permittedFields[] = 'quota';
  417. }
  418. } else {
  419. // Check if admin / subadmin
  420. $subAdminManager = $this->groupManager->getSubAdmin();
  421. if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  422. || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  423. // They have permissions over the user
  424. $permittedFields[] = 'display';
  425. $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
  426. $permittedFields[] = AccountManager::PROPERTY_EMAIL;
  427. $permittedFields[] = 'password';
  428. $permittedFields[] = 'language';
  429. $permittedFields[] = 'locale';
  430. $permittedFields[] = AccountManager::PROPERTY_PHONE;
  431. $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
  432. $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
  433. $permittedFields[] = AccountManager::PROPERTY_TWITTER;
  434. $permittedFields[] = 'quota';
  435. } else {
  436. // No rights
  437. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  438. }
  439. }
  440. // Check if permitted to edit this field
  441. if (!in_array($key, $permittedFields)) {
  442. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  443. }
  444. // Process the edit
  445. switch($key) {
  446. case 'display':
  447. case AccountManager::PROPERTY_DISPLAYNAME:
  448. $targetUser->setDisplayName($value);
  449. break;
  450. case 'quota':
  451. $quota = $value;
  452. if ($quota !== 'none' && $quota !== 'default') {
  453. if (is_numeric($quota)) {
  454. $quota = (float) $quota;
  455. } else {
  456. $quota = \OCP\Util::computerFileSize($quota);
  457. }
  458. if ($quota === false) {
  459. throw new OCSException('Invalid quota value '.$value, 103);
  460. }
  461. if ($quota === -1) {
  462. $quota = 'none';
  463. } else {
  464. $quota = \OCP\Util::humanFileSize($quota);
  465. }
  466. }
  467. $targetUser->setQuota($quota);
  468. break;
  469. case 'password':
  470. $targetUser->setPassword($value);
  471. break;
  472. case 'language':
  473. $languagesCodes = $this->l10nFactory->findAvailableLanguages();
  474. if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
  475. throw new OCSException('Invalid language', 102);
  476. }
  477. $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
  478. break;
  479. case 'locale':
  480. if (!$this->l10nFactory->localeExists($value)) {
  481. throw new OCSException('Invalid locale', 102);
  482. }
  483. $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
  484. break;
  485. case AccountManager::PROPERTY_EMAIL:
  486. if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
  487. $targetUser->setEMailAddress($value);
  488. } else {
  489. throw new OCSException('', 102);
  490. }
  491. break;
  492. case AccountManager::PROPERTY_PHONE:
  493. case AccountManager::PROPERTY_ADDRESS:
  494. case AccountManager::PROPERTY_WEBSITE:
  495. case AccountManager::PROPERTY_TWITTER:
  496. $userAccount = $this->accountManager->getUser($targetUser);
  497. if ($userAccount[$key]['value'] !== $value) {
  498. $userAccount[$key]['value'] = $value;
  499. $this->accountManager->updateUser($targetUser, $userAccount);
  500. }
  501. break;
  502. default:
  503. throw new OCSException('', 103);
  504. }
  505. return new DataResponse();
  506. }
  507. /**
  508. * @PasswordConfirmationRequired
  509. * @NoAdminRequired
  510. *
  511. * @param string $userId
  512. * @return DataResponse
  513. * @throws OCSException
  514. */
  515. public function deleteUser(string $userId): DataResponse {
  516. $currentLoggedInUser = $this->userSession->getUser();
  517. $targetUser = $this->userManager->get($userId);
  518. if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
  519. throw new OCSException('', 101);
  520. }
  521. // If not permitted
  522. $subAdminManager = $this->groupManager->getSubAdmin();
  523. if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  524. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  525. }
  526. // Go ahead with the delete
  527. if ($targetUser->delete()) {
  528. return new DataResponse();
  529. } else {
  530. throw new OCSException('', 101);
  531. }
  532. }
  533. /**
  534. * @PasswordConfirmationRequired
  535. * @NoAdminRequired
  536. *
  537. * @param string $userId
  538. * @return DataResponse
  539. * @throws OCSException
  540. * @throws OCSForbiddenException
  541. */
  542. public function disableUser(string $userId): DataResponse {
  543. return $this->setEnabled($userId, false);
  544. }
  545. /**
  546. * @PasswordConfirmationRequired
  547. * @NoAdminRequired
  548. *
  549. * @param string $userId
  550. * @return DataResponse
  551. * @throws OCSException
  552. * @throws OCSForbiddenException
  553. */
  554. public function enableUser(string $userId): DataResponse {
  555. return $this->setEnabled($userId, true);
  556. }
  557. /**
  558. * @param string $userId
  559. * @param bool $value
  560. * @return DataResponse
  561. * @throws OCSException
  562. */
  563. private function setEnabled(string $userId, bool $value): DataResponse {
  564. $currentLoggedInUser = $this->userSession->getUser();
  565. $targetUser = $this->userManager->get($userId);
  566. if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
  567. throw new OCSException('', 101);
  568. }
  569. // If not permitted
  570. $subAdminManager = $this->groupManager->getSubAdmin();
  571. if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  572. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  573. }
  574. // enable/disable the user now
  575. $targetUser->setEnabled($value);
  576. return new DataResponse();
  577. }
  578. /**
  579. * @NoAdminRequired
  580. * @NoSubAdminRequired
  581. *
  582. * @param string $userId
  583. * @return DataResponse
  584. * @throws OCSException
  585. */
  586. public function getUsersGroups(string $userId): DataResponse {
  587. $loggedInUser = $this->userSession->getUser();
  588. $targetUser = $this->userManager->get($userId);
  589. if ($targetUser === null) {
  590. throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
  591. }
  592. if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
  593. // Self lookup or admin lookup
  594. return new DataResponse([
  595. 'groups' => $this->groupManager->getUserGroupIds($targetUser)
  596. ]);
  597. } else {
  598. $subAdminManager = $this->groupManager->getSubAdmin();
  599. // Looking up someone else
  600. if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
  601. // Return the group that the method caller is subadmin of for the user in question
  602. /** @var IGroup[] $getSubAdminsGroups */
  603. $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
  604. foreach ($getSubAdminsGroups as $key => $group) {
  605. $getSubAdminsGroups[$key] = $group->getGID();
  606. }
  607. $groups = array_intersect(
  608. $getSubAdminsGroups,
  609. $this->groupManager->getUserGroupIds($targetUser)
  610. );
  611. return new DataResponse(['groups' => $groups]);
  612. } else {
  613. // Not permitted
  614. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  615. }
  616. }
  617. }
  618. /**
  619. * @PasswordConfirmationRequired
  620. * @NoAdminRequired
  621. *
  622. * @param string $userId
  623. * @param string $groupid
  624. * @return DataResponse
  625. * @throws OCSException
  626. */
  627. public function addToGroup(string $userId, string $groupid = ''): DataResponse {
  628. if ($groupid === '') {
  629. throw new OCSException('', 101);
  630. }
  631. $group = $this->groupManager->get($groupid);
  632. $targetUser = $this->userManager->get($userId);
  633. if ($group === null) {
  634. throw new OCSException('', 102);
  635. }
  636. if ($targetUser === null) {
  637. throw new OCSException('', 103);
  638. }
  639. // If they're not an admin, check they are a subadmin of the group in question
  640. $loggedInUser = $this->userSession->getUser();
  641. $subAdminManager = $this->groupManager->getSubAdmin();
  642. if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
  643. throw new OCSException('', 104);
  644. }
  645. // Add user to group
  646. $group->addUser($targetUser);
  647. return new DataResponse();
  648. }
  649. /**
  650. * @PasswordConfirmationRequired
  651. * @NoAdminRequired
  652. *
  653. * @param string $userId
  654. * @param string $groupid
  655. * @return DataResponse
  656. * @throws OCSException
  657. */
  658. public function removeFromGroup(string $userId, string $groupid): DataResponse {
  659. $loggedInUser = $this->userSession->getUser();
  660. if ($groupid === null || trim($groupid) === '') {
  661. throw new OCSException('', 101);
  662. }
  663. $group = $this->groupManager->get($groupid);
  664. if ($group === null) {
  665. throw new OCSException('', 102);
  666. }
  667. $targetUser = $this->userManager->get($userId);
  668. if ($targetUser === null) {
  669. throw new OCSException('', 103);
  670. }
  671. // If they're not an admin, check they are a subadmin of the group in question
  672. $subAdminManager = $this->groupManager->getSubAdmin();
  673. if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
  674. throw new OCSException('', 104);
  675. }
  676. // Check they aren't removing themselves from 'admin' or their 'subadmin; group
  677. if ($targetUser->getUID() === $loggedInUser->getUID()) {
  678. if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
  679. if ($group->getGID() === 'admin') {
  680. throw new OCSException('Cannot remove yourself from the admin group', 105);
  681. }
  682. } else {
  683. // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
  684. throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
  685. }
  686. } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
  687. /** @var IGroup[] $subAdminGroups */
  688. $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
  689. $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
  690. return $subAdminGroup->getGID();
  691. }, $subAdminGroups);
  692. $userGroups = $this->groupManager->getUserGroupIds($targetUser);
  693. $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
  694. if (count($userSubAdminGroups) <= 1) {
  695. // Subadmin must not be able to remove a user from all their subadmin groups.
  696. throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
  697. }
  698. }
  699. // Remove user from group
  700. $group->removeUser($targetUser);
  701. return new DataResponse();
  702. }
  703. /**
  704. * Creates a subadmin
  705. *
  706. * @PasswordConfirmationRequired
  707. *
  708. * @param string $userId
  709. * @param string $groupid
  710. * @return DataResponse
  711. * @throws OCSException
  712. */
  713. public function addSubAdmin(string $userId, string $groupid): DataResponse {
  714. $group = $this->groupManager->get($groupid);
  715. $user = $this->userManager->get($userId);
  716. // Check if the user exists
  717. if ($user === null) {
  718. throw new OCSException('User does not exist', 101);
  719. }
  720. // Check if group exists
  721. if ($group === null) {
  722. throw new OCSException('Group does not exist', 102);
  723. }
  724. // Check if trying to make subadmin of admin group
  725. if ($group->getGID() === 'admin') {
  726. throw new OCSException('Cannot create subadmins for admin group', 103);
  727. }
  728. $subAdminManager = $this->groupManager->getSubAdmin();
  729. // We cannot be subadmin twice
  730. if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
  731. return new DataResponse();
  732. }
  733. // Go
  734. if ($subAdminManager->createSubAdmin($user, $group)) {
  735. return new DataResponse();
  736. } else {
  737. throw new OCSException('Unknown error occurred', 103);
  738. }
  739. }
  740. /**
  741. * Removes a subadmin from a group
  742. *
  743. * @PasswordConfirmationRequired
  744. *
  745. * @param string $userId
  746. * @param string $groupid
  747. * @return DataResponse
  748. * @throws OCSException
  749. */
  750. public function removeSubAdmin(string $userId, string $groupid): DataResponse {
  751. $group = $this->groupManager->get($groupid);
  752. $user = $this->userManager->get($userId);
  753. $subAdminManager = $this->groupManager->getSubAdmin();
  754. // Check if the user exists
  755. if ($user === null) {
  756. throw new OCSException('User does not exist', 101);
  757. }
  758. // Check if the group exists
  759. if ($group === null) {
  760. throw new OCSException('Group does not exist', 101);
  761. }
  762. // Check if they are a subadmin of this said group
  763. if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
  764. throw new OCSException('User is not a subadmin of this group', 102);
  765. }
  766. // Go
  767. if ($subAdminManager->deleteSubAdmin($user, $group)) {
  768. return new DataResponse();
  769. } else {
  770. throw new OCSException('Unknown error occurred', 103);
  771. }
  772. }
  773. /**
  774. * Get the groups a user is a subadmin of
  775. *
  776. * @param string $userId
  777. * @return DataResponse
  778. * @throws OCSException
  779. */
  780. public function getUserSubAdminGroups(string $userId): DataResponse {
  781. $groups = $this->getUserSubAdminGroupsData($userId);
  782. return new DataResponse($groups);
  783. }
  784. /**
  785. * @NoAdminRequired
  786. * @PasswordConfirmationRequired
  787. *
  788. * resend welcome message
  789. *
  790. * @param string $userId
  791. * @return DataResponse
  792. * @throws OCSException
  793. */
  794. public function resendWelcomeMessage(string $userId): DataResponse {
  795. $currentLoggedInUser = $this->userSession->getUser();
  796. $targetUser = $this->userManager->get($userId);
  797. if ($targetUser === null) {
  798. throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
  799. }
  800. // Check if admin / subadmin
  801. $subAdminManager = $this->groupManager->getSubAdmin();
  802. if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  803. && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  804. // No rights
  805. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  806. }
  807. $email = $targetUser->getEMailAddress();
  808. if ($email === '' || $email === null) {
  809. throw new OCSException('Email address not available', 101);
  810. }
  811. try {
  812. $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
  813. $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
  814. } catch(\Exception $e) {
  815. $this->logger->logException($e, [
  816. 'message' => "Can't send new user mail to $email",
  817. 'level' => ILogger::ERROR,
  818. 'app' => 'settings',
  819. ]);
  820. throw new OCSException('Sending email failed', 102);
  821. }
  822. return new DataResponse();
  823. }
  824. }