public function __invoke(Request $request) { if ($this->container->hasParameter('partkeepr.auth.allow_password_change') && $this->container->getParameter('partkeepr.auth.allow_password_change') === false) { throw new PasswordChangeNotAllowedException(); } $user = $this->userService->getUser(); if (!$request->request->has('oldpassword') && !$request->request->has('newpassword')) { throw new \Exception('old password and new password need to be specified'); } $FOSUser = $this->userManager->findUserByUsername($user->getUsername()); if ($FOSUser !== null) { $encoder = $this->encoderFactory->getEncoder($FOSUser); $encoded_pass = $encoder->encodePassword($request->request->get('oldpassword'), $FOSUser->getSalt()); if ($FOSUser->getPassword() != $encoded_pass) { throw new OldPasswordWrongException(); } $this->userManipulator->changePassword($user->getUsername(), $request->request->get('newpassword')); } else { if ($user->isLegacy()) { if ($user->getPassword() !== md5($request->request->get('oldpassword'))) { throw new OldPasswordWrongException(); } $user->setNewPassword($request->request->get('newpassword')); $this->userService->syncData($user); } else { throw new \Exception('Cannot change password for LDAP users'); } } $user->setPassword(''); $user->setNewPassword(''); return $user; }
/** * Syncronizes the data of the given user with the FOSRestBundle * * @throws \Exception If the password was not set * * @param $user */ public function syncData(User $user) { if ($user->getProvider()->getType() !== self::BUILTIN_PROVIDER) { return; } $FOSUser = $this->userManager->findUserByUsername($user->getUsername()); if ($FOSUser === null) { if ($user->getNewPassword() == "") { throw new \Exception("Password must be set"); } $FOSUser = $this->userManipulator->create($user->getUsername(), $user->getNewPassword(), "", true, false); $user->setLegacy(false); } if ($user->getNewPassword() != "") { $this->userManipulator->changePassword($user->getUsername(), $user->getNewPassword()); } $FOSUser->setEmail($user->getEmail()); $FOSUser->setEnabled($user->isActive()); }
/** * @expectedException \InvalidArgumentException */ public function testChangePasswordWithInvalidUsername() { $userManagerMock = $this->createMock('FOS\\UserBundle\\Model\\UserManagerInterface'); $invalidusername = '******'; $password = '******'; $userManagerMock->expects($this->once())->method('findUserByUsername')->will($this->returnValue(null))->with($this->equalTo($invalidusername)); $userManagerMock->expects($this->never())->method('updateUser'); $manipulator = new UserManipulator($userManagerMock); $manipulator->changePassword($invalidusername, $password); }