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

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