You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

967 lines
29 KiB

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