From 3464be96391f5c2a335b6d76f26bec6aefe619ad Mon Sep 17 00:00:00 2001 From: Sujith H Date: Wed, 24 Jul 2019 16:39:42 +0530 Subject: [PATCH] Move user creation logic to a separate service in core Move user creation logic to a separate service in core. Signed-off-by: Sujith H --- css/setpassword.css | 23 - js/setpassword.js | 83 --- lib/Controller/UsersController.php | 397 ++---------- templates/new_user/email-html.php | 36 -- templates/new_user/email-plain_text.php | 10 - templates/new_user/resendtokenbymail.php | 33 - templates/new_user/setpassword.php | 44 -- templates/new_user/tokensendnotify.php | 2 - tests/unit/UsersControllerTest.php | 791 +---------------------- 9 files changed, 76 insertions(+), 1343 deletions(-) delete mode 100644 css/setpassword.css delete mode 100644 js/setpassword.js delete mode 100644 templates/new_user/email-html.php delete mode 100644 templates/new_user/email-plain_text.php delete mode 100644 templates/new_user/resendtokenbymail.php delete mode 100644 templates/new_user/setpassword.php delete mode 100644 templates/new_user/tokensendnotify.php diff --git a/css/setpassword.css b/css/setpassword.css deleted file mode 100644 index 69c1342..0000000 --- a/css/setpassword.css +++ /dev/null @@ -1,23 +0,0 @@ -#reset-password p { - position: relative; -} - -.text-center { - text-align: center; -} - -#submit { - width: 100%; -} - -#password { - width: 100%; -} - -#retypepassword { - width: 100%; -} - -#message { - width: 94%; -} diff --git a/js/setpassword.js b/js/setpassword.js deleted file mode 100644 index 330eb61..0000000 --- a/js/setpassword.js +++ /dev/null @@ -1,83 +0,0 @@ -(function () { - var SetPassword = { - init : function() { - $('#set-password #submit').click(this.onClickSetPassword); - }, - - onClickSetPassword : function(event){ - var passwordObj = $('#password'); - var retypePasswordObj = $('#retypepassword'); - passwordObj.parent().removeClass('shake'); - event.preventDefault(); - if (passwordObj.val() === retypePasswordObj.val()) { - $.post( - passwordObj.parents('form').attr('action'), - {password: passwordObj.val()} - ).done(function (result) { - OCA.UserManagement.SetPassword._resetDone(result); - }).fail(function (result) { - OCA.UserManagement.SetPassword._onSetPasswordFail(result); - }); - } else { - //Password mismatch happened - passwordObj.val(''); - retypePasswordObj.val(''); - passwordObj.parent().addClass('shake'); - $('#message').addClass('warning'); - $('#message').text('Passwords do not match'); - $('#message').show(); - passwordObj.focus(); - } - }, - - _onSetPasswordFail: function(result) { - var responseObj = JSON.parse(result.responseText); - var errorObject = $('#error-message'); - var showErrorMessage = false; - - var errorMessage; - errorMessage = responseObj.message; - - if (!errorMessage) { - errorMessage = t('core', 'Failed to set password. Please contact your administrator.'); - } - - errorObject.text(errorMessage); - errorObject.show(); - $('#submit').prop('disabled', true); - }, - - _resetDone : function(result){ - if (result && result.status === 'success') { - var getRootPath = OC.getRootPath(); - if (getRootPath === '') { - /** - * If owncloud is not run inside subfolder, the getRootPath - * will return empty string - */ - getRootPath = "/"; - } - OC.redirect(getRootPath); - } - } - }; - - if (!OCA.UserManagement) { - OCA.UserManagement = {}; - } - OCA.UserManagement.SetPassword = SetPassword; -})(); - -$(document).ready(function () { - OCA.UserManagement.SetPassword.init(); - $('#password').keypress(function () { - /* - The warning message should be shown only during password mismatch. - Else it should not. - */ - if (($('#password').val().length >= 0) && ($('#retypepassword').val().length === 0)) { - $('#message').removeClass('warning'); - $('#message').text(''); - } - }); -}); diff --git a/lib/Controller/UsersController.php b/lib/Controller/UsersController.php index 9e13390..8e6cc08 100644 --- a/lib/Controller/UsersController.php +++ b/lib/Controller/UsersController.php @@ -32,6 +32,7 @@ namespace OCA\UserManagement\Controller; use OC\AppFramework\Http; +use OC\User\Service\CreateUserService; use OC\User\User; use OCA\UserManagement\Exception\InvalidUserTokenException; use OCA\UserManagement\Exception\UserTokenException; @@ -56,6 +57,9 @@ use OCP\Mail\IMailer; use OCP\IAvatarManager; use OCP\Security\ISecureRandom; +use OCP\User\Exceptions\CannotCreateUserException; +use OCP\User\Exceptions\InvalidEmailException; +use OCP\User\Exceptions\UserAlreadyExistsException; use OCP\Util; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -69,6 +73,8 @@ class UsersController extends Controller { private $l10n; /** @var IUserSession */ private $userSession; + /** @var CreateUserService */ + private $createUserService; /** @var bool */ private $isAdmin; /** @var IUserManager */ @@ -125,6 +131,7 @@ public function __construct($appName, IUserManager $userManager, IGroupManager $groupManager, IUserSession $userSession, + CreateUserService $createUserService, IConfig $config, ISecureRandom $secureRandom, IL10N $l10n, @@ -140,6 +147,7 @@ public function __construct($appName, $this->userManager = $userManager; $this->groupManager = $groupManager; $this->userSession = $userSession; + $this->createUserService = $createUserService; $this->config = $config; $this->l10n = $l10n; $this->secureRandom = $secureRandom; @@ -353,40 +361,6 @@ public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backe return new DataResponse($users); } - /** - * @param string $userId - * @param string $email - */ - private function generateTokenAndSendMail($userId, $email) { - $token = $this->secureRandom->generate(21, - ISecureRandom::CHAR_DIGITS, - ISecureRandom::CHAR_LOWER, ISecureRandom::CHAR_UPPER); - $this->config->setUserValue($userId, 'owncloud', - 'lostpassword', $this->timeFactory->getTime() . ':' . $token); - - // data for the mail template - $mailData = [ - 'username' => $userId, - 'url' => $this->urlGenerator->linkToRouteAbsolute('user_management.Users.setPasswordForm', ['userId' => $userId, 'token' => $token]) - ]; - - $mail = new TemplateResponse('user_management', 'new_user/email-html', $mailData, 'blank'); - $mailContent = $mail->render(); - - $mail = new TemplateResponse('user_management', 'new_user/email-plain_text', $mailData, 'blank'); - $plainTextMailContent = $mail->render(); - - $subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]); - - $message = $this->mailer->createMessage(); - $message->setTo([$email => $userId]); - $message->setSubject($subject); - $message->setHtmlBody($mailContent); - $message->setPlainBody($plainTextMailContent); - $message->setFrom([$this->fromMailAddress => $this->defaults->getName()]); - $this->mailer->send($message); - } - /** * @NoAdminRequired * @@ -397,343 +371,60 @@ private function generateTokenAndSendMail($userId, $email) { * @return DataResponse */ public function create($username, $password, array $groups= [], $email='') { - if ($email !== '' && !$this->mailer->validateMailAddress($email)) { - return new DataResponse( - [ - 'message' => (string)$this->l10n->t('Invalid mail address') - ], - Http::STATUS_UNPROCESSABLE_ENTITY - ); - } - - $currentUser = $this->userSession->getUser(); - - if (!$this->isAdmin) { - if (!empty($groups)) { - foreach ($groups as $key => $group) { - $groupObject = $this->groupManager->get($group); - if ($groupObject === null) { - unset($groups[$key]); - continue; - } - - if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) { - unset($groups[$key]); + try { + $user = $this->createUserService->createUser(['username' => $username, 'password' => $password, 'email' => $email]); + if ($user instanceof User) { + $preFailedGroups = []; + $currentUser = $this->userSession->getUser(); + if ($currentUser !== null) { + if (!$this->groupManager->isAdmin($currentUser->getUID())) { + /** + * If the user is not an admin, then we restrict groups which + * are part of the subadmin, other groups should be removed. + */ + foreach ($groups as $key => $group) { + $groupObject = $this->groupManager->get($group); + if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) { + $preFailedGroups[] = $groups[$key]; + unset($groups[$key]); + } + } } } - } - - if (empty($groups)) { - $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($currentUser); - // New class returns IGroup[] so convert back - $gids = []; - foreach ($groups as $group) { - $gids[] = $group->getGID(); + $failedGroups = $this->createUserService->addUserToGroups($user, $groups); + $failedGroups = \array_merge($failedGroups, $preFailedGroups); + if (\count($failedGroups) > 0) { + $this->log->error("The user " . $username . " was not added to the groups" . \implode(',', $failedGroups) . ".", ['app' => 'settings']); } - $groups = $gids; - } - } - - if ($this->userManager->userExists($username)) { - return new DataResponse( - [ - 'message' => (string)$this->l10n->t('A user with that name already exists.') - ], - Http::STATUS_CONFLICT - ); - } - - try { - if (($password === '') && ($email !== '')) { - /** - * Generate a random password as we are going to have this - * use one time. The new user has to reset it using the link - * from email. - */ - $event = new GenericEvent(); - $this->eventDispatcher->dispatch('OCP\User::createPassword', $event); - if ($event->hasArgument('password')) { - $password = $event->getArgument('password'); - } else { - $password = $this->secureRandom->generate(20); - } - } - $user = $this->userManager->createUser($username, $password); - } catch (\Exception $exception) { - $message = $exception->getMessage(); - if (!$message) { - $message = $this->l10n->t('Unable to create user.'); + $userGroups = $this->groupManager->getUserGroupIds($user); + return new DataResponse( + $this->formatUserForIndex($user, $userGroups), + Http::STATUS_CREATED + ); } + } catch (CannotCreateUserException $e) { return new DataResponse( [ - 'message' => (string) $message, + 'message' => (string)$this->l10n->t($e->getMessage()) ], Http::STATUS_FORBIDDEN ); - } - - if ($user instanceof User) { - if ($groups !== null) { - foreach ($groups as $groupName) { - $group = $this->groupManager->get($groupName); - - if (empty($group)) { - $group = $this->groupManager->createGroup($groupName); - } - $group->addUser($user); - } - } - /** - * Send new user mail only if a mail is set - */ - if ($email !== '') { - $user->setEMailAddress($email); - try { - $this->generateTokenAndSendMail($username, $email); - } catch (\Exception $e) { - $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']); - } - } - // fetch users groups - $userGroups = $this->groupManager->getUserGroupIds($user); - + } catch (InvalidEmailException $e) { return new DataResponse( - $this->formatUserForIndex($user, $userGroups), - Http::STATUS_CREATED - ); - } - - return new DataResponse( - [ - 'message' => (string)$this->l10n->t('Unable to create user.') - ], - Http::STATUS_FORBIDDEN - ); - } - - /** - * Set password for user using link - * - * @PublicPage - * @NoCSRFRequired - * @NoAdminRequired - * @NoSubadminRequired - * - * @param string $token - * @param string $userId - * @return TemplateResponse - */ - public function setPasswordForm($token, $userId) { - try { - $this->checkPasswordSetToken($token, $userId); - } catch (UserTokenException $e) { - if ($e instanceof UserTokenExpiredException) { - return new TemplateResponse( - 'user_management', 'new_user/resendtokenbymail', - [ - 'link' => $this->urlGenerator->linkToRouteAbsolute('user_management.Users.resendToken', ['userId' => $userId]) - ], 'guest' - ); - } - $this->log->logException($e, ['app' => 'user_management']); - return new TemplateResponse( - 'core', 'error', [ - "errors" => [["error" => $e->getMessage()]] - ], 'guest' - ); - } - - return new TemplateResponse( - 'user_management', 'new_user/setpassword', - [ - 'link' => $this->urlGenerator->linkToRouteAbsolute('user_management.Users.setPassword', ['userId' => $userId, 'token' => $token]) - ], 'guest' - ); - } - - /** - * @param string $token - * @param string $userId - * @return null - * @throws InvalidUserTokenException - * @throws UserTokenExpiredException - * @throws UserTokenMismatchException - */ - private function checkPasswordSetToken($token, $userId) { - $user = $this->userManager->get($userId); - - $splittedToken = \explode(':', $this->config->getUserValue($userId, 'owncloud', 'lostpassword', null)); - if (\count($splittedToken) !== 2) { - $this->config->deleteUserValue($userId, 'owncloud', 'lostpassword'); - throw new InvalidUserTokenException($this->l10n->t('The token provided is invalid.')); - } - - //The value 43200 = 60*60*12 = 1/2 day - if ($splittedToken[0] < ($this->timeFactory->getTime() - (int)$this->config->getAppValue('user_management', 'token_expire_time', '43200')) || - $user->getLastLogin() > $splittedToken[0]) { - $this->config->deleteUserValue($userId, 'owncloud', 'lostpassword'); - throw new UserTokenExpiredException($this->l10n->t('The token provided had expired.')); - } - - if (!\hash_equals($splittedToken[1], $token)) { - throw new UserTokenMismatchException($this->l10n->t('The token provided is invalid.')); - } - } - - /** - * @PublicPage - * @NoCSRFRequired - * @NoAdminRequired - * @NoSubadminRequired - * - * @param $userId - * @return TemplateResponse - */ - public function resendToken($userId) { - $user = $this->userManager->get($userId); + 'message' => (string)$this->l10n->t($e->getMessage()) - if ($user === null) { - $this->log->error('User: ' . $userId . ' does not exist', ['app' => 'user_management']); - return new TemplateResponse( - 'core', 'error', - [ - "errors" => [["error" => $this->l10n->t('Failed to create activation link. Please contact your administrator.')]] ], - 'guest' + Http::STATUS_UNPROCESSABLE_ENTITY ); - } - - if ($user->getEMailAddress() === null) { - $this->log->error('Email address not set for: ' . $userId, ['app' => 'user_management']); - return new TemplateResponse( - 'core', 'error', + } catch (UserAlreadyExistsException $e) { + return new DataResponse( [ - "errors" => [["error" => $this->l10n->t('Failed to create activation link. Please contact your administrator.', [$userId])]] + 'message' => (string)$this->l10n->t($e->getMessage()) ], - 'guest' - ); - } - - try { - $this->generateTokenAndSendMail($user->getUID(), $user->getEMailAddress()); - } catch (\Exception $e) { - $this->log->error("Can't send new user mail to " . $user->getEMailAddress() . ": " . $e->getMessage(), ['app' => 'user_management']); - return new TemplateResponse( - 'core', 'error', - [ - "errors" => [[ - "error" => $this->l10n->t('Can\'t send email to the user. Contact your administrator.')]] - ], 'guest' - ); - } - - return new TemplateResponse( - 'user_management', 'new_user/tokensendnotify', [], 'guest' - ); - } - - /** - * @PublicPage - * @NoAdminRequired - * @NoSubadminRequired - * @NoCSRFRequired - * - * @param $token - * @param $userId - * @param $password - * @return JSONResponse - */ - public function setPassword($token, $userId, $password) { - $user = $this->userManager->get($userId); - - if ($user === null) { - $this->log->error('User: ' . $userId . ' does not exist.', ['app' => 'user_management']); - return new JSONResponse( - [ - 'status' => 'error', - 'message' => $this->l10n->t('Failed to set password. Please contact the administrator.', [$userId]), - 'type' => 'usererror' - ], Http::STATUS_NOT_FOUND - ); - } - - try { - $this->checkPasswordSetToken($token, $userId); - - try { - if (!$user->setPassword($password)) { - $this->log->error('The password can not be set for user: ' . $userId); - return new JSONResponse( - [ - 'status' => 'error', - 'message' => $this->l10n->t('Failed to set password. Please contact your administrator.', [$userId]), - 'type' => 'passwordsetfailed' - ], Http::STATUS_FORBIDDEN - ); - } - } catch (\Exception $e) { - $this->log->error('The password can not be set for user: '. $userId); - return new JSONResponse( - [ - 'status' => 'error', - 'message' => $e->getMessage(), - 'type' => 'passwordsetfailed' - ], Http::STATUS_FORBIDDEN - ); - } - - \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', ['uid' => $userId, 'password' => $password]); - \OC_User::unsetMagicInCookie(); - } catch (UserTokenException $e) { - $this->log->logException($e, ['app' => 'user_management']); - return new JSONResponse( - [ - 'status' => 'error', - 'message' => $e->getMessage(), - 'type' => 'tokenfailure' - ], Http::STATUS_UNAUTHORIZED - ); - } - - try { - $this->sendNotificationMail($userId); - } catch (\Exception $e) { - $this->log->logException($e, ['app' => 'user_management']); - return new JSONResponse( - [ - 'status' => 'error', - 'message' => $this->l10n->t('Failed to send email. Please contact your administrator.'), - 'type' => 'emailsendfailed' - ], Http::STATUS_INTERNAL_SERVER_ERROR + Http::STATUS_CONFLICT ); } - - return new JSONResponse(['status' => 'success']); - } - - /** - * @param $userId - * @throws \Exception - */ - protected function sendNotificationMail($userId) { - $user = $this->userManager->get($userId); - $email = $user->getEMailAddress(); - - if ($email !== '') { - $tmpl = new \OC_Template('core', 'lostpassword/notify'); - $msg = $tmpl->fetchPage(); - $tmplAlt = new \OC_Template('core', 'lostpassword/altnotify'); - $msgAlt = $tmplAlt->fetchPage(); - - $message = $this->mailer->createMessage(); - $message->setTo([$email => $userId]); - $message->setSubject($this->l10n->t('%s password changed successfully', [$this->defaults->getName()])); - $message->setPlainBody($msgAlt); - $message->setHtmlBody($msg); - $message->setFrom([$this->fromMailAddress => $this->defaults->getName()]); - $this->mailer->send($message); - } } /** diff --git a/templates/new_user/email-html.php b/templates/new_user/email-html.php deleted file mode 100644 index 716755d..0000000 --- a/templates/new_user/email-html.php +++ /dev/null @@ -1,36 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - -
  - <?php p($theme->getName()); ?> -
 
  - t('Hey there,

just letting you know that you now have an %s account.

Your username: %s
Please set the password by accessing it: Here

', [$theme->getName(), $_['username'], $_['url']])); - - // TRANSLATORS term at the end of a mail - p($l->t('Cheers!')); - ?> -
 
 --
- getName()); ?> - - getSlogan()); ?> -
getBaseUrl());?> -
 
-
diff --git a/templates/new_user/email-plain_text.php b/templates/new_user/email-plain_text.php deleted file mode 100644 index 21daeed..0000000 --- a/templates/new_user/email-plain_text.php +++ /dev/null @@ -1,10 +0,0 @@ -t("Hey there,\n\njust letting you know that you now have an %s account.\n\nYour username: %s\nAccess it: %s\n\n", [$theme->getName(), $_['username'], $_['url']])); - -// TRANSLATORS term at the end of a mail -p($l->t("Cheers!")); -?> - - -- -getName() . ' - ' . $theme->getSlogan()); ?> -getBaseUrl()); diff --git a/templates/new_user/resendtokenbymail.php b/templates/new_user/resendtokenbymail.php deleted file mode 100644 index 0c6bedb..0000000 --- a/templates/new_user/resendtokenbymail.php +++ /dev/null @@ -1,33 +0,0 @@ - - * - * @copyright Copyright (c) 2018, ownCloud GmbH - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -?> - -
-
-

- -

- -
-
diff --git a/templates/new_user/setpassword.php b/templates/new_user/setpassword.php deleted file mode 100644 index 2f427e3..0000000 --- a/templates/new_user/setpassword.php +++ /dev/null @@ -1,44 +0,0 @@ - - * - * @copyright Copyright (c) 2018, ownCloud GmbH - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -style('user_management', 'setpassword'); -script('user_management', 'setpassword'); -?> - - -
-
-

- - - - -

- -
-
diff --git a/templates/new_user/tokensendnotify.php b/templates/new_user/tokensendnotify.php deleted file mode 100644 index 1317674..0000000 --- a/templates/new_user/tokensendnotify.php +++ /dev/null @@ -1,2 +0,0 @@ -t('Activation link was sent to an email address, if one was configured.')); diff --git a/tests/unit/UsersControllerTest.php b/tests/unit/UsersControllerTest.php index 36e1007..30295a7 100644 --- a/tests/unit/UsersControllerTest.php +++ b/tests/unit/UsersControllerTest.php @@ -10,6 +10,7 @@ namespace OCA\UserManagement\Test\Unit; +use OC\User\Service\CreateUserService; use OCA\UserManagement\Controller\UsersController; use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; @@ -34,6 +35,8 @@ use OC\User\User; use OC\Group\Group; use OCP\IGroup; +use OCP\User\Exceptions\CannotCreateUserException; +use OCP\User\Exceptions\InvalidEmailException; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\GenericEvent; use Test\TestCase; @@ -53,6 +56,8 @@ class UsersControllerTest extends TestCase { private $groupManager; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ private $userSession; + /** @var CreateUserService | \PHPUnit\Framework\MockObject\MockObject */ + private $createUserService; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ private $l10N; /** @var IAvatarManager | \PHPUnit\Framework\MockObject\MockObject */ @@ -87,6 +92,7 @@ protected function setUp() { ->disableOriginalConstructor()->getMock(); $this->userSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor()->getMock(); + $this->createUserService = $this->createMock(CreateUserService::class); $this->l10N = $this->getMockBuilder(IL10N::class) ->disableOriginalConstructor()->getMock(); $this->config = $this->getMockBuilder(IConfig::class) @@ -926,10 +932,10 @@ public function testCreateSuccessfulWithoutGroupAdmin() { ->method('getBackendClassName') ->will($this->returnValue('bar')); - $this->userManager + $this->createUserService ->expects($this->once()) ->method('createUser') - ->will($this->onConsecutiveCalls($user)); + ->will($this->returnValue($user)); $subadmin = $this->getMockBuilder(SubAdmin::class) ->disableOriginalConstructor() @@ -1000,25 +1006,13 @@ public function testCreateSuccessfulWithoutGroupSubAdmin() { ->disableOriginalConstructor()->getMock(); $subGroup1 = $this->getMockBuilder(IGroup::class) ->disableOriginalConstructor()->getMock(); - $subGroup1 - ->expects($this->once()) - ->method('addUser') - ->with($newUser); $subGroup2 = $this->getMockBuilder(IGroup::class) ->disableOriginalConstructor()->getMock(); - $subGroup2 - ->expects($this->once()) - ->method('addUser') - ->with($newUser); - $this->userManager + $this->createUserService ->expects($this->once()) ->method('createUser') ->will($this->returnValue($newUser)); - $this->groupManager - ->expects($this->exactly(2)) - ->method('get') - ->will($this->onConsecutiveCalls($subGroup1, $subGroup2)); $this->groupManager ->expects($this->once()) ->method('getUserGroupIds') @@ -1029,11 +1023,7 @@ public function testCreateSuccessfulWithoutGroupSubAdmin() { ->disableOriginalConstructor() ->getMock(); $subadmin - ->expects($this->at(0)) - ->method('getSubAdminsGroups') - ->will($this->returnValue([$subGroup1, $subGroup2])); - $subadmin - ->expects($this->at(1)) + ->expects($this->once()) ->method('getSubAdminsGroups') ->will($this->returnValue([])); $this->groupManager @@ -1095,30 +1085,13 @@ public function testCreateSuccessfulWithGroupAdmin() { ->will($this->returnValue('bar')); $existingGroup = $this->getMockBuilder(IGroup::class) ->disableOriginalConstructor()->getMock(); - $existingGroup - ->expects($this->once()) - ->method('addUser') - ->with($user); $newGroup = $this->getMockBuilder(IGroup::class) ->disableOriginalConstructor()->getMock(); - $newGroup - ->expects($this->once()) - ->method('addUser') - ->with($user); - $this->userManager + $this->createUserService ->expects($this->once()) ->method('createUser') ->will($this->onConsecutiveCalls($user)); - $this->groupManager - ->expects($this->exactly(2)) - ->method('get') - ->will($this->onConsecutiveCalls(null, $existingGroup)); - $this->groupManager - ->expects($this->once()) - ->method('createGroup') - ->with('NewGroup') - ->will($this->onConsecutiveCalls($newGroup)); $this->groupManager ->expects($this->once()) ->method('getUserGroupIds') @@ -1195,24 +1168,13 @@ public function testCreateSuccessfulWithGroupSubAdmin() { ->expects($this->any()) ->method('getGID') ->will($this->returnValue('SubGroup1')); - $subGroup1 - ->expects($this->once()) - ->method('addUser') - ->with($user); - $this->userManager + $this->createUserService ->expects($this->once()) ->method('createUser') ->will($this->returnValue($newUser)); $this->groupManager - ->expects($this->at(1)) - ->method('get') - ->with('SubGroup1') - ->will($this->returnValue($subGroup1)); - $this->groupManager - ->expects($this->at(5)) ->method('get') - ->with('SubGroup1') - ->will($this->returnValue($subGroup1)); + ->will($this->onConsecutiveCalls($subGroup1, $subGroup1)); $this->groupManager ->expects($this->once()) ->method('getUserGroupIds') @@ -1227,14 +1189,14 @@ public function testCreateSuccessfulWithGroupSubAdmin() { $subadmin = $this->getMockBuilder(SubAdmin::class) ->disableOriginalConstructor() ->getMock(); - $subadmin->expects($this->at(1)) - ->method('getSubAdminsGroups') - ->with($user) - ->will($this->returnValue([$subGroup1])); + $subadmin->method('isSubAdminofGroup') + ->willReturn(true); $subadmin->expects($this->at(2)) ->method('getSubAdminsGroups') ->with($newUser) ->will($this->returnValue([])); + $subadmin->method('isSubAdminofGroup') + ->will($this->onConsecutiveCalls(true, false)); $this->groupManager ->expects($this->any()) ->method('getSubAdmin') @@ -1277,9 +1239,9 @@ public function testCreateUnsuccessfulAdmin() { ->method('getUser') ->will($this->returnValue($user)); - $this->userManager + $this->createUserService ->method('createUser') - ->will($this->throwException(new \Exception())); + ->will($this->throwException(new CannotCreateUserException("Unable to create user."))); $expectedResponse = new DataResponse( [ @@ -1308,29 +1270,13 @@ public function testCreateUnsuccessfulSubAdmin() { ->method('getUser') ->will($this->returnValue($user)); - $this->userManager + $this->createUserService ->method('createUser') - ->will($this->throwException(new \Exception())); + ->will($this->throwException(new CannotCreateUserException("Unable to create user."))); - $subgroup1 = $this->getMockBuilder(IGroup::class) - ->disableOriginalConstructor() - ->getMock(); - $subgroup1->expects($this->once()) - ->method('getGID') - ->will($this->returnValue('SubGroup1')); - $subgroup2 = $this->getMockBuilder(IGroup::class) - ->disableOriginalConstructor() - ->getMock(); - $subgroup2->expects($this->once()) - ->method('getGID') - ->will($this->returnValue('SubGroup2')); $subadmin = $this->getMockBuilder(SubAdmin::class) ->disableOriginalConstructor() ->getMock(); - $subadmin->expects($this->once()) - ->method('getSubAdminsGroups') - ->with($user) - ->will($this->returnValue([$subgroup1, $subgroup2])); $this->groupManager ->expects($this->any()) ->method('getSubAdmin') @@ -1649,20 +1595,8 @@ public function testDestroyNotAccessibleToSubAdmin() { * test if an invalid mail result in a failure response */ public function testCreateUnsuccessfulWithInvalidEmailAdmin() { - $this->groupManager - ->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(true)); - - $user = $this->getMockBuilder(User::class) - ->disableOriginalConstructor()->getMock(); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('user')); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); + $this->createUserService->method('createUser') + ->will($this->throwException(new InvalidEmailException("Invalid mail address"))); $expectedResponse = new DataResponse([ 'message' => 'Invalid mail address', @@ -1697,16 +1631,8 @@ public function testCreateSuccessfulWithValidEmailAdmin() { $message = $this->getMockBuilder(Message::class) ->disableOriginalConstructor()->getMock(); - $message - ->expects($this->at(0)) - ->method('setTo') - ->with(['validMail@Adre.ss' => 'foo']); - $message - ->expects($this->at(1)) - ->method('setSubject') - ->with('Your ownCloud account was created'); $htmlBody = new Http\TemplateResponse( - 'user_management', + 'core', 'new_user/email-html', [ 'username' => 'foo', @@ -1714,12 +1640,8 @@ public function testCreateSuccessfulWithValidEmailAdmin() { ], 'blank' ); - $message - ->expects($this->at(2)) - ->method('setHtmlBody') - ->with($htmlBody->render()); $plainBody = new Http\TemplateResponse( - 'user_management', + 'core', 'new_user/email-plain_text', [ 'username' => 'foo', @@ -1727,24 +1649,6 @@ public function testCreateSuccessfulWithValidEmailAdmin() { ], 'blank' ); - $message - ->expects($this->at(3)) - ->method('setPlainBody') - ->with($plainBody->render()); - $message - ->expects($this->at(4)) - ->method('setFrom') - ->with(['no-reply@localhost' => 'ownCloud']); - - $this->mailer - ->expects($this->at(0)) - ->method('validateMailAddress') - ->with('validMail@Adre.ss') - ->will($this->returnValue(true)); - $this->mailer - ->expects($this->at(1)) - ->method('createMessage') - ->will($this->returnValue($message)); $user = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); @@ -1762,7 +1666,7 @@ public function testCreateSuccessfulWithValidEmailAdmin() { ->method('getBackendClassName') ->will($this->returnValue('bar')); - $this->userManager + $this->createUserService ->expects($this->once()) ->method('createUser') ->will($this->onConsecutiveCalls($user)); @@ -1783,10 +1687,6 @@ public function testCreateSuccessfulWithValidEmailAdmin() { } public function testCreateSuccessfulWithEmailAndUsername() { - $this->mailer->expects($this->once()) - ->method('validateMailAddress') - ->willReturn(true); - $iUser = $this->createMock(IUser::class); $this->userSession->method('getUser') @@ -1797,43 +1697,17 @@ public function testCreateSuccessfulWithEmailAndUsername() { ->method('isAdmin') ->will($this->returnValue(true)); - $this->userManager->expects($this->once()) - ->method('userExists') - ->willReturn(false); - - $this->eventDispatcher->expects($this->once()) - ->method('dispatch') - ->with('OCP\User::createPassword', new GenericEvent()); - $this->secureRandom->method('generate') ->willReturn('AsDfGh12345'); $targetUser = $this->createMock(User::class); $targetUser->method('getUID') ->willReturn('foobazz'); - $targetUser->expects($this->once()) - ->method('setEMailAddress') - ->with('validMail@Adre.ss'); - $this->userManager->expects($this->once()) + $this->createUserService->expects($this->once()) ->method('createUser') - ->with('foobazz', 'AsDfGh12345') ->willReturn($targetUser); - $message = $this->createMock(Message::class); - $message->expects($this->once()) - ->method('setTo') - ->with(['validMail@Adre.ss' => 'foobazz']); - $message->expects($this->once()) - ->method('setSubject') - ->with('Your account was created'); - - $this->mailer->expects($this->once()) - ->method('createMessage') - ->willReturn($message); - $this->mailer->expects($this->once()) - ->method('send') - ->with($message); $subadmin = $this->createMock(SubAdmin::class); $subadmin->expects($this->once()) ->method('getSubAdminsGroups') @@ -1846,495 +1720,6 @@ public function testCreateSuccessfulWithEmailAndUsername() { $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); } - public function testSetPasswordForm() { - $user = $this->createMock(IUser::class); - - $this->userManager->expects($this->once()) - ->method('get') - ->with('foo') - ->willReturn($user); - - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ1'); - $this->config->expects($this->once()) - ->method('getAppValue') - ->willReturn('43200'); - - $this->timeFactory->expects($this->once()) - ->method('getTime') - ->willReturn(44430); - - $this->urlGenerator->expects($this->once()) - ->method('linkToRouteAbsolute') - ->willReturn('http://localhost/apps/user_management/setpassword/form/1234/foo'); - $result = $this->createController()->setPasswordForm('fooBaZ1', 'foo'); - $this->assertEquals(new Http\TemplateResponse( - 'user_management', 'new_user/setpassword', - ['link' => 'http://localhost/apps/user_management/setpassword/form/1234/foo'], - 'guest'), $result); - } - - public function providesUserTokenExceptionData() { - return [ - ['invalid_token'], - ['expired_token'], - ['mismatch_token'] - ]; - } - - /** - * @dataProvider providesUserTokenExceptionData - */ - public function testSetPasswordFormExceptionResponse($tokenException) { - $user = $this->createMock(IUser::class); - - $this->userManager->expects($this->once()) - ->method('get') - ->with('foo') - ->willReturn($user); - - if ($tokenException === 'expired_token') { - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ1'); - $this->timeFactory->expects($this->once()) - ->method('getTime') - ->willReturn(44444); - - $this->urlGenerator->expects($this->once()) - ->method('linkToRouteAbsolute') - ->willReturn('http://localhost/apps/user_management/setpassword/form/1234/foo'); - - $result = $this->createController()->setPasswordForm('fooBaZ1', 'foo'); - $this->assertEquals( - new Http\TemplateResponse('user_management', 'new_user/resendtokenbymail', - ['link' => 'http://localhost/apps/user_management/setpassword/form/1234/foo'], - 'guest'), $result); - } elseif ($tokenException === 'mismatch_token') { - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ11'); - $this->timeFactory->expects($this->once()) - ->method('getTime') - ->willReturn(44430); - $this->config->expects($this->once()) - ->method('getAppValue') - ->willReturn('43200'); - $result = $this->createController()->setPasswordForm('fooBaZ1', 'foo'); - $this->assertEquals( - new Http\TemplateResponse( - 'core', 'error', - ['errors' => [['error' => 'The token provided is invalid.']]], 'guest'), $result - ); - } elseif ($tokenException === 'invalid_token') { - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn(''); - $result = $this->createController()->setPasswordForm('fooBaZ1', 'foo'); - $this->assertEquals( - new Http\TemplateResponse('core', 'error', - ['errors' => [["error" => 'The token provided is invalid.']]], 'guest'), $result); - } - } - - public function testResendToken() { - $user = $this->createMock(IUser::class); - $user->method('getEMailAddress') - ->willReturn('foo@bar.com'); - - $this->userManager->expects($this->once()) - ->method('get') - ->willReturn($user); - - $this->secureRandom->expects($this->once()) - ->method('generate') - ->willReturn('foOBaZ1'); - $this->urlGenerator->expects($this->once()) - ->method('linkToRouteAbsolute') - ->willReturn('http://localhost/setpassword/foOBaZ1/foo'); - - $message = $this->createMock(Message::class); - $message->expects($this->once()) - ->method('setTo') - ->willReturn($message); - $message->expects($this->once()) - ->method('setSubject') - ->willReturn($message); - $message->expects($this->once()) - ->method('setHtmlBody') - ->willReturn($message); - $message->expects($this->once()) - ->method('setPlainBody') - ->willReturn($message); - $message->expects($this->once()) - ->method('setFrom') - ->willReturn($message); - - $this->defaults->method('getName') - ->willReturn('ownCloud'); - - $this->mailer->expects($this->once()) - ->method('createMessage') - ->willReturn($message); - $this->mailer->expects($this->once()) - ->method('send') - ->with($message) - ->willReturn([]); - - $result = $this->createController()->resendToken('foo'); - $this->assertEquals( - new Http\TemplateResponse( - 'user_management', 'new_user/tokensendnotify', - [], 'guest'), $result); - } - - /** - * @param $conditionForException - */ - public function testResendTokenNullUserResponse() { - $result = $this->createController()->resendToken('foo'); - $this->assertEquals( - new Http\TemplateResponse( - 'core', 'error', - ["errors" => [["error" =>"Failed to create activation link. Please contact your administrator."]]], - 'guest'), $result); - } - - public function testResendTokenEmailNotSendResponse() { - $user = $this->createMock(IUser::class); - - $this->userManager->expects($this->once()) - ->method('get') - ->willReturn($user); - $result = $this->createController()->resendToken('foo'); - $this->assertEquals( - new Http\TemplateResponse( - 'core', 'error', - ["errors" => [["error" =>"Failed to create activation link. Please contact your administrator."]]], - 'guest'), $result); - } - - public function testResendTokenSendMailFailedResponse() { - $user = $this->createMock(IUser::class); - - $user->method('getEMailAddress') - ->willReturn('foo@bar.com'); - - $this->userManager->expects($this->once()) - ->method('get') - ->willReturn($user); - - $this->secureRandom->expects($this->once()) - ->method('generate') - ->willReturn('foOBaZ1'); - $this->urlGenerator->expects($this->once()) - ->method('linkToRouteAbsolute') - ->willReturn('http://localhost/setpassword/foOBaZ1/foo'); - - $message = $this->createMock(Message::class); - $message->expects($this->once()) - ->method('setTo') - ->willReturn($message); - $message->expects($this->once()) - ->method('setSubject') - ->willReturn($message); - $message->expects($this->once()) - ->method('setHtmlBody') - ->willReturn($message); - $message->expects($this->once()) - ->method('setPlainBody') - ->willReturn($message); - $message->expects($this->once()) - ->method('setFrom') - ->willReturn($message); - - $this->defaults->method('getName') - ->willReturn('ownCloud'); - - $this->mailer->expects($this->once()) - ->method('createMessage') - ->willReturn($message); - $this->mailer->expects($this->once()) - ->method('send') - ->with($message) - ->willThrowException(new \Exception('Mail can not be sent')); - $result = $this->createController()->resendToken('foo'); - $this->assertEquals( - new Http\TemplateResponse( - 'core', 'error', - ["errors" => [["error" =>"Can't send email to the user. Contact your administrator."]]], - 'guest'), $result); - } - - public function testSetPassword() { - $controller = $this->createController(); - $user = $this->createMock(IUser::class); - $user->expects($this->once()) - ->method('setPassword') - ->willReturn(true); - $user->expects($this->once()) - ->method('getEMailAddress') - ->willReturn('foo@bar.com'); - - $this->userManager->method('get') - ->with('foo') - ->willReturn($user); - - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ1'); - - $this->timeFactory->expects($this->once()) - ->method('getTime') - ->willReturn(44430); - $this->config->expects($this->once()) - ->method('getAppValue') - ->willReturn(43200); - - $fromMailAddress = $this->invokePrivate($controller, 'fromMailAddress', []); - $this->defaults->method('getName') - ->willReturn('ownCloud'); - - $message = $this->createMock(Message::class); - $message->expects($this->once()) - ->method('setTo') - ->willReturn($message); - $message->expects($this->once()) - ->method('setSubject') - ->willReturn($message); - $message->expects($this->once()) - ->method('setFrom') - ->with([$fromMailAddress => 'ownCloud']) - ->willReturn($message); - - $this->mailer->expects($this->once()) - ->method('createMessage') - ->willReturn($message); - $this->mailer->expects($this->once()) - ->method('send') - ->with($message) - ->willReturn([]); - - $result = $controller->setPassword('fooBaZ1', 'foo', '123'); - $this->assertEquals(new Http\JSONResponse(['status' => 'success']), $result); - $this->assertNotEquals($fromMailAddress, 'foo@bar.com'); - $this->assertEquals($fromMailAddress, 'no-reply@localhost'); - } - - /** - * @param $conditionForException - */ - public function testSetPasswordNullUserExcception() { - $result = $this->createController()->setPassword('fooBaZ1', 'foo', '123'); - $this->assertEquals( - new Http\JSONResponse( - [ - 'status' => 'error', - 'message' => 'Failed to set password. Please contact the administrator.', - 'type' => 'usererror' - ], Http::STATUS_NOT_FOUND - ), $result); - } - - public function testSetPasswordInvalidTokenExcception() { - $user = $this->createMock(IUser::class); - $this->userManager->method('get') - ->with('foo') - ->willReturn($user); - - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn(''); - - $result = $this->createController()->setPassword('fooBaZ1', 'foo', '123'); - $this->assertEquals(new Http\JSONResponse( - [ - 'status' => 'error', - 'message' => 'The token provided is invalid.', - 'type' => 'tokenfailure' - ], Http::STATUS_UNAUTHORIZED - ), $result); - } - - public function testSetPasswordPolicyException() { - $user = $this->createMock(IUser::class); - $user->method('setPassword') - ->willThrowException(new \Exception('Can not set user password, because password does not comply with policy.')); - $this->userManager->method('get') - ->with('foo') - ->willReturn($user); - - $this->config - ->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ1'); - $this->config - ->expects($this->once()) - ->method('getAppValue') - ->willReturn('43200'); - - $this->timeFactory - ->expects($this->once()) - ->method('getTime') - ->willReturn(44430); - $this->logger - ->expects($this->once()) - ->method('error') - ->with('The password can not be set for user: foo'); - - $expectedResult = new Http\JSONResponse( - [ - 'status' => 'error', - 'message' => 'Can not set user password, because password does not comply with policy.', - 'type' => 'passwordsetfailed', - ], Http::STATUS_FORBIDDEN - ); - $result = $this->createController()->setPassword('fooBaZ1', 'foo', '123'); - $this->assertEquals($expectedResult, $result); - } - - public function testSetPasswordExpiredTokenException() { - $user = $this->createMock(IUser::class); - - $this->userManager->method('get') - ->with('foo') - ->willReturn($user); - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ1'); - $this->timeFactory->expects($this->once()) - ->method('getTime') - ->willReturn(44444); - - $result = $this->createController()->setPassword('fooBaZ1', 'foo', '123'); - $this->assertEquals(new Http\JSONResponse( - [ - 'status' => 'error', - 'message' => 'The token provided had expired.', - 'type' => 'tokenfailure' - ], Http::STATUS_UNAUTHORIZED - ), $result); - } - - public function testSetPasswordMismatchTokenException() { - $user = $this->createMock(IUser::class); - - $this->userManager->method('get') - ->with('foo') - ->willReturn($user); - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ11'); - $this->config->expects($this->once()) - ->method('getAppValue') - ->willReturn('43200'); - $this->timeFactory->expects($this->once()) - ->method('getTime') - ->willReturn(44430); - - $result = $this->createController()->setPassword('fooBaZ1', 'foo', '123'); - $this->assertEquals(new Http\JSONResponse( - [ - 'status' => 'error', - 'message' => 'The token provided is invalid.', - 'type' => 'tokenfailure' - ], Http::STATUS_UNAUTHORIZED - ), $result); - } - - public function testSetPasswordSetFailed() { - $user = $this->createMock(IUser::class); - - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ1'); - - $this->timeFactory->expects($this->once()) - ->method('getTime') - ->willReturn(44430); - $this->config->expects($this->once()) - ->method('getAppValue') - ->willReturn('43200'); - - $this->userManager->method('get') - ->with('foo') - ->willReturn($user); - - $user->expects($this->once()) - ->method('setPassword') - ->with('123') - ->willReturn(false); - - $result = $this->createController()->setPassword('fooBaZ1', 'foo', '123'); - $this->assertEquals(new Http\JSONResponse( - [ - 'status' => 'error', - 'message' => 'Failed to set password. Please contact your administrator.', - 'type' => 'passwordsetfailed' - ], Http::STATUS_FORBIDDEN - ), $result); - } - - public function testSetPasswordSendMailFailed() { - $user = $this->createMock(IUser::class); - - $this->config->expects($this->once()) - ->method('getUserValue') - ->willReturn('1234:fooBaZ1'); - - $this->timeFactory->expects($this->once()) - ->method('getTime') - ->willReturn(44430); - $this->config->expects($this->once()) - ->method('getAppValue') - ->willReturn('43200'); - - $this->userManager->method('get') - ->with('foo') - ->willReturn($user); - - $user->expects($this->once()) - ->method('setPassword') - ->with('123') - ->willReturn(true); - $user->expects($this->once()) - ->method('getEMailAddress') - ->willReturn('foo@bar.com'); - - $message = $this->createMock(Message::class); - $message->expects($this->once()) - ->method('setTo') - ->willReturn($message); - $message->expects($this->once()) - ->method('setSubject') - ->willReturn($message); - $message->expects($this->once()) - ->method('setHtmlBody') - ->willReturn($message); - $message->expects($this->once()) - ->method('setPlainBody') - ->willReturn($message); - $message->expects($this->once()) - ->method('setFrom') - ->willReturn($message); - - $this->mailer->expects($this->once()) - ->method('createMessage') - ->willReturn($message); - $this->mailer->expects($this->once()) - ->method('send') - ->willThrowException(new \Exception('can not send mail')); - - $result = $this->createController()->setPassword('fooBaZ1', 'foo', '123'); - $this->assertEquals(new Http\JSONResponse( - [ - 'status' => 'error', - 'message' => 'Failed to send email. Please contact your administrator.', - 'type' => 'emailsendfailed' - ], Http::STATUS_INTERNAL_SERVER_ERROR - ), $result); - } private function mockUser($userId = 'foo', $displayName = 'M. Foo', $isEnabled = true, $lastLogin = 500, $home = '/home/foo', $backend = 'OC_User_Database') { $user = $this->getMockBuilder(User::class) @@ -2643,6 +2028,7 @@ public function testSetSelfEmailAddress($loginUser, $setUser, $emailAddress) { $userManager = $this->createMock(IUserManager::class); $groupManager = $this->createMock(IGroupManager::class); $userSession = $this->createMock(IUserSession::class); + $createUserService = $this->createMock(CreateUserService::class); $iConfig = $this->createMock(IConfig::class); $iSecureRandom = $this->createMock(ISecureRandom::class); $iL10 = $this->createMock(IL10N::class); @@ -2656,7 +2042,7 @@ public function testSetSelfEmailAddress($loginUser, $setUser, $emailAddress) { $iAvatarManager = $this->createMock(IAvatarManager::class); $eventDispatcher = $this->createMock(EventDispatcher::class); $userController = new UsersController($appName, $irequest, $userManager, $groupManager, - $userSession, $iConfig, $iSecureRandom, $iL10, $iLogger, $ocDefault, $iMailer, + $userSession, $createUserService, $iConfig, $iSecureRandom, $iL10, $iLogger, $ocDefault, $iMailer, $iTimeFactory, $urlGenerator, $appManager, $iAvatarManager, $eventDispatcher); $iUser = $this->createMock(IUser::class); @@ -2702,6 +2088,7 @@ public function testSetEmailAddressSendEmail($id, $mailaddress) { $userManager = $this->createMock(IUserManager::class); $groupManager = $this->createMock(IGroupManager::class); $userSession = $this->createMock(IUserSession::class); + $createUserService = $this->createMock(CreateUserService::class); $iConfig = $this->createMock(IConfig::class); $iSecureRandom = $this->createMock(ISecureRandom::class); $iL10 = $this->createMock(IL10N::class); @@ -2715,7 +2102,7 @@ public function testSetEmailAddressSendEmail($id, $mailaddress) { $iAvatarManager = $this->createMock(IAvatarManager::class); $eventDispatcher = $this->createMock(EventDispatcher::class); $userController = new UsersController($appName, $irequest, $userManager, $groupManager, - $userSession, $iConfig, $iSecureRandom, $iL10, $iLogger, $ocDefault, $iMailer, + $userSession, $createUserService, $iConfig, $iSecureRandom, $iL10, $iLogger, $ocDefault, $iMailer, $iTimeFactory, $urlGenerator, $appManager, $iAvatarManager, $eventDispatcher); $iUser = $this->createMock(IUser::class); @@ -3599,121 +2986,6 @@ public function testEnableNotAccessibleToSubAdmin() { $this->assertEquals($expectedResponse, $response); } - /** - * First create a user with wrong email id, - * then delete the user. Again create the same user with - * a proper email id. Later try to set the password for the - * user. The token of the user should not be deleted, if it - * is a mismatch. - */ - public function testInvalidTokenNotDeleted() { - $user = $this->createMock(IUser::class); - $user->expects($this->any()) - ->method('getUID') - ->willReturn('foo'); - $user->expects($this->any()) - ->method('delete') - ->willReturn(true); - - $adminUser = $this->createMock(IUser::class); - $adminUser->expects($this->any()) - ->method('getUID') - ->willReturn('admin'); - - $subAdmin = $this->createMock(SubAdmin::class); - $subAdmin->expects($this->any()) - ->method('getSubAdminsGroups') - ->willReturn([]); - $subAdmin->expects($this->any()) - ->method('isUserAccessible') - ->willReturn(true); - - $this->mailer->expects($this->any()) - ->method('validateMailAddress') - ->willReturn(true); - - $this->userSession->expects($this->any()) - ->method('getUser') - ->willReturn($adminUser); - - $this->groupManager->expects($this->any()) - ->method('getSubAdmin') - ->willReturn($subAdmin); - - $this->userManager->expects($this->any()) - ->method('userExists') - ->willReturn(false); - - $userInstance = $this->createMock(User::class); - $userInstance->expects($this->any()) - ->method('getUID') - ->willReturn('foo'); - - $this->userManager->expects($this->any()) - ->method('createUser') - ->willReturn($userInstance); - - $message = $this->createMock(Message::class); - $message->expects($this->any()) - ->method('setTo') - ->willReturn($message); - $message->expects($this->any()) - ->method('setSubject') - ->willReturn($message); - $message->expects($this->any()) - ->method('setHtmlBody') - ->willReturn($message); - $message->expects($this->any()) - ->method('setPlainBody') - ->willReturn($message); - $message->expects($this->any()) - ->method('setFrom') - ->willReturn($message); - - $this->mailer->expects($this->any()) - ->method('createMessage') - ->willReturn($message); - $this->mailer->expects($this->any()) - ->method('send') - ->with($message) - ->willReturn([]); - - //Create a user first - $usersController = $this->createController(); - $firstCreateResult = $usersController->create('foo', null, [], 'bar@bar.com'); - $this->assertEquals(Http::STATUS_CREATED, $firstCreateResult->getStatus()); - - $this->userManager->expects($this->any()) - ->method('get') - ->willReturn($user); - - //Now delete the user - $userDeleteResult = $usersController->destroy('foo'); - $deleteResponseData = $userDeleteResult->getData(); - $this->assertEquals('success', $deleteResponseData['status']); - $this->assertEquals('foo', $deleteResponseData['data']['username']); - $this->assertEquals(Http::STATUS_NO_CONTENT, $userDeleteResult->getStatus()); - - //Now create a new user with a different email id - $secondCreateResult = $usersController->create('foo', null, [], 'foo@bar.com'); - $this->assertEquals(Http::STATUS_CREATED, $secondCreateResult->getStatus()); - - /** - * Now when user tries to set the password, the token should not be deleted if - * it is a mismatch - */ - $this->config->expects($this->never()) - ->method('deleteUserValue'); - $this->config->expects($this->any()) - ->method('getUserValue') - ->willReturn('foo:AsDfGh12345'); - $result = $usersController->setPassword('AsDfGh1234', 'foo', 'foobar'); - $this->assertEquals(Http::STATUS_UNAUTHORIZED, $result->getStatus()); - $this->assertEquals('error', $result->getData()['status']); - $this->assertEquals('The token provided is invalid.', $result->getData()['message']); - $this->assertEquals('tokenfailure', $result->getData()['type']); - } - /** * @return UsersController */ @@ -3724,6 +2996,7 @@ private function createController() { $this->userManager, $this->groupManager, $this->userSession, + $this->createUserService, $this->config, $this->secureRandom, $this->l10N,