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.

UsersController.php 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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 (OCSException $e) {
  298. $this->logger->logException($e, [
  299. 'message' => 'Failed addUser attempt with ocs exeption.',
  300. 'level' => ILogger::ERROR,
  301. 'app' => 'ocs_api',
  302. ]);
  303. throw $e;
  304. } catch (\Exception $e) {
  305. $this->logger->logException($e, [
  306. 'message' => 'Failed addUser attempt with exception.',
  307. 'level' => ILogger::ERROR,
  308. 'app' => 'ocs_api',
  309. ]);
  310. throw new OCSException('Bad request', 101);
  311. }
  312. }
  313. /**
  314. * @NoAdminRequired
  315. * @NoSubAdminRequired
  316. *
  317. * gets user info
  318. *
  319. * @param string $userId
  320. * @return DataResponse
  321. * @throws OCSException
  322. */
  323. public function getUser(string $userId): DataResponse {
  324. $data = $this->getUserData($userId);
  325. // getUserData returns empty array if not enough permissions
  326. if (empty($data)) {
  327. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  328. }
  329. return new DataResponse($data);
  330. }
  331. /**
  332. * @NoAdminRequired
  333. * @NoSubAdminRequired
  334. *
  335. * gets user info from the currently logged in user
  336. *
  337. * @return DataResponse
  338. * @throws OCSException
  339. */
  340. public function getCurrentUser(): DataResponse {
  341. $user = $this->userSession->getUser();
  342. if ($user) {
  343. $data = $this->getUserData($user->getUID());
  344. // rename "displayname" to "display-name" only for this call to keep
  345. // the API stable.
  346. $data['display-name'] = $data['displayname'];
  347. unset($data['displayname']);
  348. return new DataResponse($data);
  349. }
  350. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  351. }
  352. /**
  353. * @NoAdminRequired
  354. * @NoSubAdminRequired
  355. */
  356. public function getEditableFields(): DataResponse {
  357. $permittedFields = [];
  358. // Editing self (display, email)
  359. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  360. $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
  361. $permittedFields[] = AccountManager::PROPERTY_EMAIL;
  362. }
  363. if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
  364. $federatedFileSharing = $this->federatedFileSharingFactory->get();
  365. $shareProvider = $federatedFileSharing->getFederatedShareProvider();
  366. if ($shareProvider->isLookupServerUploadEnabled()) {
  367. $permittedFields[] = AccountManager::PROPERTY_PHONE;
  368. $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
  369. $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
  370. $permittedFields[] = AccountManager::PROPERTY_TWITTER;
  371. }
  372. }
  373. return new DataResponse($permittedFields);
  374. }
  375. /**
  376. * @NoAdminRequired
  377. * @NoSubAdminRequired
  378. * @PasswordConfirmationRequired
  379. *
  380. * edit users
  381. *
  382. * @param string $userId
  383. * @param string $key
  384. * @param string $value
  385. * @return DataResponse
  386. * @throws OCSException
  387. */
  388. public function editUser(string $userId, string $key, string $value): DataResponse {
  389. $currentLoggedInUser = $this->userSession->getUser();
  390. $targetUser = $this->userManager->get($userId);
  391. if ($targetUser === null) {
  392. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  393. }
  394. $permittedFields = [];
  395. if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
  396. // Editing self (display, email)
  397. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  398. $permittedFields[] = 'display';
  399. $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
  400. $permittedFields[] = AccountManager::PROPERTY_EMAIL;
  401. }
  402. $permittedFields[] = 'password';
  403. if ($this->config->getSystemValue('force_language', false) === false ||
  404. $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  405. $permittedFields[] = 'language';
  406. }
  407. if ($this->config->getSystemValue('force_locale', false) === false ||
  408. $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  409. $permittedFields[] = 'locale';
  410. }
  411. if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
  412. $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
  413. $shareProvider = $federatedFileSharing->getFederatedShareProvider();
  414. if ($shareProvider->isLookupServerUploadEnabled()) {
  415. $permittedFields[] = AccountManager::PROPERTY_PHONE;
  416. $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
  417. $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
  418. $permittedFields[] = AccountManager::PROPERTY_TWITTER;
  419. }
  420. }
  421. // If admin they can edit their own quota
  422. if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  423. $permittedFields[] = 'quota';
  424. }
  425. } else {
  426. // Check if admin / subadmin
  427. $subAdminManager = $this->groupManager->getSubAdmin();
  428. if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  429. || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  430. // They have permissions over the user
  431. $permittedFields[] = 'display';
  432. $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
  433. $permittedFields[] = AccountManager::PROPERTY_EMAIL;
  434. $permittedFields[] = 'password';
  435. $permittedFields[] = 'language';
  436. $permittedFields[] = 'locale';
  437. $permittedFields[] = AccountManager::PROPERTY_PHONE;
  438. $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
  439. $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
  440. $permittedFields[] = AccountManager::PROPERTY_TWITTER;
  441. $permittedFields[] = 'quota';
  442. } else {
  443. // No rights
  444. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  445. }
  446. }
  447. // Check if permitted to edit this field
  448. if (!in_array($key, $permittedFields)) {
  449. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  450. }
  451. // Process the edit
  452. switch($key) {
  453. case 'display':
  454. case AccountManager::PROPERTY_DISPLAYNAME:
  455. $targetUser->setDisplayName($value);
  456. break;
  457. case 'quota':
  458. $quota = $value;
  459. if ($quota !== 'none' && $quota !== 'default') {
  460. if (is_numeric($quota)) {
  461. $quota = (float) $quota;
  462. } else {
  463. $quota = \OCP\Util::computerFileSize($quota);
  464. }
  465. if ($quota === false) {
  466. throw new OCSException('Invalid quota value '.$value, 103);
  467. }
  468. if ($quota === -1) {
  469. $quota = 'none';
  470. } else {
  471. $quota = \OCP\Util::humanFileSize($quota);
  472. }
  473. }
  474. $targetUser->setQuota($quota);
  475. break;
  476. case 'password':
  477. try {
  478. if (!$targetUser->canChangePassword()) {
  479. throw new OCSException('Setting the password is not supported by the users backend', 103);
  480. }
  481. $targetUser->setPassword($value);
  482. } catch (HintException $e) { // password policy error
  483. throw new OCSException($e->getMessage(), 103);
  484. }
  485. break;
  486. case 'language':
  487. $languagesCodes = $this->l10nFactory->findAvailableLanguages();
  488. if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
  489. throw new OCSException('Invalid language', 102);
  490. }
  491. $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
  492. break;
  493. case 'locale':
  494. if (!$this->l10nFactory->localeExists($value)) {
  495. throw new OCSException('Invalid locale', 102);
  496. }
  497. $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
  498. break;
  499. case AccountManager::PROPERTY_EMAIL:
  500. if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
  501. $targetUser->setEMailAddress($value);
  502. } else {
  503. throw new OCSException('', 102);
  504. }
  505. break;
  506. case AccountManager::PROPERTY_PHONE:
  507. case AccountManager::PROPERTY_ADDRESS:
  508. case AccountManager::PROPERTY_WEBSITE:
  509. case AccountManager::PROPERTY_TWITTER:
  510. $userAccount = $this->accountManager->getUser($targetUser);
  511. if ($userAccount[$key]['value'] !== $value) {
  512. $userAccount[$key]['value'] = $value;
  513. $this->accountManager->updateUser($targetUser, $userAccount);
  514. }
  515. break;
  516. default:
  517. throw new OCSException('', 103);
  518. }
  519. return new DataResponse();
  520. }
  521. /**
  522. * @PasswordConfirmationRequired
  523. * @NoAdminRequired
  524. *
  525. * @param string $userId
  526. * @return DataResponse
  527. * @throws OCSException
  528. */
  529. public function deleteUser(string $userId): DataResponse {
  530. $currentLoggedInUser = $this->userSession->getUser();
  531. $targetUser = $this->userManager->get($userId);
  532. if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
  533. throw new OCSException('', 101);
  534. }
  535. // If not permitted
  536. $subAdminManager = $this->groupManager->getSubAdmin();
  537. if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  538. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  539. }
  540. // Go ahead with the delete
  541. if ($targetUser->delete()) {
  542. return new DataResponse();
  543. } else {
  544. throw new OCSException('', 101);
  545. }
  546. }
  547. /**
  548. * @PasswordConfirmationRequired
  549. * @NoAdminRequired
  550. *
  551. * @param string $userId
  552. * @return DataResponse
  553. * @throws OCSException
  554. * @throws OCSForbiddenException
  555. */
  556. public function disableUser(string $userId): DataResponse {
  557. return $this->setEnabled($userId, false);
  558. }
  559. /**
  560. * @PasswordConfirmationRequired
  561. * @NoAdminRequired
  562. *
  563. * @param string $userId
  564. * @return DataResponse
  565. * @throws OCSException
  566. * @throws OCSForbiddenException
  567. */
  568. public function enableUser(string $userId): DataResponse {
  569. return $this->setEnabled($userId, true);
  570. }
  571. /**
  572. * @param string $userId
  573. * @param bool $value
  574. * @return DataResponse
  575. * @throws OCSException
  576. */
  577. private function setEnabled(string $userId, bool $value): DataResponse {
  578. $currentLoggedInUser = $this->userSession->getUser();
  579. $targetUser = $this->userManager->get($userId);
  580. if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
  581. throw new OCSException('', 101);
  582. }
  583. // If not permitted
  584. $subAdminManager = $this->groupManager->getSubAdmin();
  585. if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
  586. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  587. }
  588. // enable/disable the user now
  589. $targetUser->setEnabled($value);
  590. return new DataResponse();
  591. }
  592. /**
  593. * @NoAdminRequired
  594. * @NoSubAdminRequired
  595. *
  596. * @param string $userId
  597. * @return DataResponse
  598. * @throws OCSException
  599. */
  600. public function getUsersGroups(string $userId): DataResponse {
  601. $loggedInUser = $this->userSession->getUser();
  602. $targetUser = $this->userManager->get($userId);
  603. if ($targetUser === null) {
  604. throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
  605. }
  606. if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
  607. // Self lookup or admin lookup
  608. return new DataResponse([
  609. 'groups' => $this->groupManager->getUserGroupIds($targetUser)
  610. ]);
  611. } else {
  612. $subAdminManager = $this->groupManager->getSubAdmin();
  613. // Looking up someone else
  614. if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
  615. // Return the group that the method caller is subadmin of for the user in question
  616. /** @var IGroup[] $getSubAdminsGroups */
  617. $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
  618. foreach ($getSubAdminsGroups as $key => $group) {
  619. $getSubAdminsGroups[$key] = $group->getGID();
  620. }
  621. $groups = array_intersect(
  622. $getSubAdminsGroups,
  623. $this->groupManager->getUserGroupIds($targetUser)
  624. );
  625. return new DataResponse(['groups' => $groups]);
  626. } else {
  627. // Not permitted
  628. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  629. }
  630. }
  631. }
  632. /**
  633. * @PasswordConfirmationRequired
  634. * @NoAdminRequired
  635. *
  636. * @param string $userId
  637. * @param string $groupid
  638. * @return DataResponse
  639. * @throws OCSException
  640. */
  641. public function addToGroup(string $userId, string $groupid = ''): DataResponse {
  642. if ($groupid === '') {
  643. throw new OCSException('', 101);
  644. }
  645. $group = $this->groupManager->get($groupid);
  646. $targetUser = $this->userManager->get($userId);
  647. if ($group === null) {
  648. throw new OCSException('', 102);
  649. }
  650. if ($targetUser === null) {
  651. throw new OCSException('', 103);
  652. }
  653. // If they're not an admin, check they are a subadmin of the group in question
  654. $loggedInUser = $this->userSession->getUser();
  655. $subAdminManager = $this->groupManager->getSubAdmin();
  656. if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
  657. throw new OCSException('', 104);
  658. }
  659. // Add user to group
  660. $group->addUser($targetUser);
  661. return new DataResponse();
  662. }
  663. /**
  664. * @PasswordConfirmationRequired
  665. * @NoAdminRequired
  666. *
  667. * @param string $userId
  668. * @param string $groupid
  669. * @return DataResponse
  670. * @throws OCSException
  671. */
  672. public function removeFromGroup(string $userId, string $groupid): DataResponse {
  673. $loggedInUser = $this->userSession->getUser();
  674. if ($groupid === null || trim($groupid) === '') {
  675. throw new OCSException('', 101);
  676. }
  677. $group = $this->groupManager->get($groupid);
  678. if ($group === null) {
  679. throw new OCSException('', 102);
  680. }
  681. $targetUser = $this->userManager->get($userId);
  682. if ($targetUser === null) {
  683. throw new OCSException('', 103);
  684. }
  685. // If they're not an admin, check they are a subadmin of the group in question
  686. $subAdminManager = $this->groupManager->getSubAdmin();
  687. if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
  688. throw new OCSException('', 104);
  689. }
  690. // Check they aren't removing themselves from 'admin' or their 'subadmin; group
  691. if ($targetUser->getUID() === $loggedInUser->getUID()) {
  692. if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
  693. if ($group->getGID() === 'admin') {
  694. throw new OCSException('Cannot remove yourself from the admin group', 105);
  695. }
  696. } else {
  697. // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
  698. throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
  699. }
  700. } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
  701. /** @var IGroup[] $subAdminGroups */
  702. $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
  703. $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
  704. return $subAdminGroup->getGID();
  705. }, $subAdminGroups);
  706. $userGroups = $this->groupManager->getUserGroupIds($targetUser);
  707. $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
  708. if (count($userSubAdminGroups) <= 1) {
  709. // Subadmin must not be able to remove a user from all their subadmin groups.
  710. throw new OCSException('Not viable to remove user from the last group you are SubAdmin of', 105);
  711. }
  712. }
  713. // Remove user from group
  714. $group->removeUser($targetUser);
  715. return new DataResponse();
  716. }
  717. /**
  718. * Creates a subadmin
  719. *
  720. * @PasswordConfirmationRequired
  721. *
  722. * @param string $userId
  723. * @param string $groupid
  724. * @return DataResponse
  725. * @throws OCSException
  726. */
  727. public function addSubAdmin(string $userId, string $groupid): DataResponse {
  728. $group = $this->groupManager->get($groupid);
  729. $user = $this->userManager->get($userId);
  730. // Check if the user exists
  731. if ($user === null) {
  732. throw new OCSException('User does not exist', 101);
  733. }
  734. // Check if group exists
  735. if ($group === null) {
  736. throw new OCSException('Group does not exist', 102);
  737. }
  738. // Check if trying to make subadmin of admin group
  739. if ($group->getGID() === 'admin') {
  740. throw new OCSException('Cannot create subadmins for admin group', 103);
  741. }
  742. $subAdminManager = $this->groupManager->getSubAdmin();
  743. // We cannot be subadmin twice
  744. if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
  745. return new DataResponse();
  746. }
  747. // Go
  748. $subAdminManager->createSubAdmin($user, $group);
  749. return new DataResponse();
  750. }
  751. /**
  752. * Removes a subadmin from a group
  753. *
  754. * @PasswordConfirmationRequired
  755. *
  756. * @param string $userId
  757. * @param string $groupid
  758. * @return DataResponse
  759. * @throws OCSException
  760. */
  761. public function removeSubAdmin(string $userId, string $groupid): DataResponse {
  762. $group = $this->groupManager->get($groupid);
  763. $user = $this->userManager->get($userId);
  764. $subAdminManager = $this->groupManager->getSubAdmin();
  765. // Check if the user exists
  766. if ($user === null) {
  767. throw new OCSException('User does not exist', 101);
  768. }
  769. // Check if the group exists
  770. if ($group === null) {
  771. throw new OCSException('Group does not exist', 101);
  772. }
  773. // Check if they are a subadmin of this said group
  774. if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
  775. throw new OCSException('User is not a subadmin of this group', 102);
  776. }
  777. // Go
  778. $subAdminManager->deleteSubAdmin($user, $group);
  779. return new DataResponse();
  780. }
  781. /**
  782. * Get the groups a user is a subadmin of
  783. *
  784. * @param string $userId
  785. * @return DataResponse
  786. * @throws OCSException
  787. */
  788. public function getUserSubAdminGroups(string $userId): DataResponse {
  789. $groups = $this->getUserSubAdminGroupsData($userId);
  790. return new DataResponse($groups);
  791. }
  792. /**
  793. * @NoAdminRequired
  794. * @PasswordConfirmationRequired
  795. *
  796. * resend welcome message
  797. *
  798. * @param string $userId
  799. * @return DataResponse
  800. * @throws OCSException
  801. */
  802. public function resendWelcomeMessage(string $userId): DataResponse {
  803. $currentLoggedInUser = $this->userSession->getUser();
  804. $targetUser = $this->userManager->get($userId);
  805. if ($targetUser === null) {
  806. throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
  807. }
  808. // Check if admin / subadmin
  809. $subAdminManager = $this->groupManager->getSubAdmin();
  810. if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
  811. && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
  812. // No rights
  813. throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
  814. }
  815. $email = $targetUser->getEMailAddress();
  816. if ($email === '' || $email === null) {
  817. throw new OCSException('Email address not available', 101);
  818. }
  819. try {
  820. $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
  821. $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
  822. } catch(\Exception $e) {
  823. $this->logger->logException($e, [
  824. 'message' => "Can't send new user mail to $email",
  825. 'level' => ILogger::ERROR,
  826. 'app' => 'settings',
  827. ]);
  828. throw new OCSException('Sending email failed', 102);
  829. }
  830. return new DataResponse();
  831. }
  832. }