UsersController.php 30 KB

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