/** * send * * @param ResetPassword $resetPassword * @param User $user * @param array $mailConfig * * @return mixed */ public function sendRestPasswordEmail(ResetPassword $resetPassword, User $user, $mailConfig) { $toEmail = $user->getEmail(); $fromEmail = $mailConfig['fromEmail']; $fromName = $mailConfig['fromName']; $subject = $mailConfig['subject']; $bodyTemplate = $mailConfig['body']; //Ignore blank emails if (!trim($toEmail)) { return; } $vars = ['name' => '', 'userId' => $user->getId(), 'url' => 'https://' . $_SERVER['HTTP_HOST'] . '/reset-password?fromPasswordResetEmail=1&id=' . $resetPassword->getResetId() . '&key=' . $resetPassword->getHashKey()]; foreach ($vars as $name => $value) { $bodyTemplate = str_replace('__' . $name . '__', $value, $bodyTemplate); // Handle BC $bodyTemplate = str_replace('{' . $name . '}', $value, $bodyTemplate); } try { $html = new MimePart($bodyTemplate); $html->type = "text/html"; $body = new MimeMessage(); $body->setParts([$html]); $message = new Message(); $message->setBody($body)->setFrom($fromEmail, $fromName)->setSubject($subject); foreach (explode(',', $toEmail) as $email) { $message->addTo(trim($email)); } $transport = new \Zend\Mail\Transport\Sendmail(); $transport->send($message); } catch (InvalidArgumentException $e) { // nothing } }
public function testGetUserProperty() { $key = 'propertyX'; $value = 'XXXXX'; $user = new User(); $user->setId('123'); $user->setProperty($key, 'XXXXX'); $newValue = $this->getUserPropertyService()->getUserProperty($user, $key); $this->assertEquals($value, $newValue, 'Property value did not come back.'); }
/** * getUserProperty * * @param User $user user * @param string $propertyNameSpace propertyNameSpace * @param null $dflt dflt * @param bool $refresh refresh * * @return mixed */ public function getUserProperty(User $user, $propertyNameSpace, $dflt = null, $refresh = false) { $property = $user->getProperty($propertyNameSpace, null); // if a property is not set, see try to get it from an event listener if ($property === null || $refresh) { // @event getUserProperty.pre - $this->getEventManager()->trigger('getUserProperty', $this, ['user' => $user, 'propertyNameSpace' => $propertyNameSpace]); } $property = $user->getProperty($propertyNameSpace, $dflt); return $property; }
public function buildUserAuthenticationServiceUserResult() { $user = new User(); $user->setId('123'); $responseCollection = $this->getMockBuilder('\\Zend\\EventManager\\ResponseCollection')->disableOriginalConstructor()->getMock(); $responseCollection->expects($this->any())->method('last')->will($this->returnValue($user)); $responseCollection->expects($this->any())->method('stopped')->will($this->returnValue(false)); $eventManager = $this->getMockBuilder('\\Zend\\EventManager\\EventManagerInterface')->disableOriginalConstructor()->getMock(); $eventManager->expects($this->any())->method('trigger')->will($this->returnValue($responseCollection)); $this->userAuthenticationServiceUserResult = new UserAuthenticationService($eventManager); }
/** * switchBack * * @param User $impersonatorUser * @param array $options * * @return Result * @throws \Exception */ public function switchBack(User $impersonatorUser, $options = []) { // Get current user $currentUserId = $this->rcmUserService->getCurrentUser()->getId(); $impersonatorUserId = $impersonatorUser->getId(); $result = new Result(); // Force login as $suUser $this->rcmUserService->getUserAuthService()->setIdentity($impersonatorUser); // log action $this->logAction($impersonatorUserId, $currentUserId, 'SU switched back', true); $result->setSuccess(true, 'SU switch back was successful'); return $result; }
/** * testConstruct * * @covers \RcmUser\User\Entity\ReadOnlyUser::__construct * @covers \RcmUser\User\Entity\ReadOnlyUser::populate * * @return void */ public function testConstruct() { $user = new User(); $user->setId('id'); $user->setUsername('username'); $user->setPassword('password'); $user->setState('disabled'); $user->setName('name'); $user->setEmail('*****@*****.**'); $user->setProperties(['A' => 'something']); return new ReadOnlyUser($user); }
/** * prepareUserUpdate * * @param User $requestUser requestUser * @param User $responseUser responseUser * @param User $existingUser existingUser * * @return Result */ public function prepareUserUpdate(User $requestUser, User $responseUser, User $existingUser) { // PASSWORD CHECKS $requestPassword = $requestUser->getPassword(); $existingPassword = $existingUser->getPassword(); //$hashedPassword = $existingPassword; // if password changed if ($existingPassword !== $requestPassword) { $hashedPassword = $this->getEncryptor()->create($requestPassword); $responseUser->setPassword($hashedPassword); } // STATE $requestState = $requestUser->getState(); $existingState = $existingUser->getState(); if ($requestState !== $existingState) { $responseUser->setState($requestState); } return new Result($responseUser); }
/** * switchBack * * @param User $impersonatorUser * @param array $options * * @return Result * @throws \Exception */ public function switchBack(User $impersonatorUser, $options = []) { if (!isset($options['suUserPassword'])) { throw new \Exception('suUserPassword required for AuthSwitcher'); } $suUserPassword = $options['suUserPassword']; // Get current user $currentUserId = $this->rcmUserService->getCurrentUser()->getId(); $impersonatorUserId = $impersonatorUser->getId(); $result = new Result(); $impersonatorUser->setPassword($suUserPassword); $authResult = $this->rcmUserService->authenticate($impersonatorUser); if (!$authResult->isValid()) { // ERROR // log action $this->logAction($impersonatorUserId, $currentUserId, 'SU attempted to switched back, provided incorrect credentials', true); $result->setSuccess(false, $authResult->getMessages()[0]); return $result; } // log action $this->logAction($impersonatorUserId, $currentUserId, 'SU switched back', true); $result->setSuccess(true, 'SU switch back was successful'); return $result; }
/** * prepareUserUpdate * * @param User $requestUser requestUser * @param User $responseUser responseUser * @param User $existingUser existingUser * * @return Result */ public function prepareUserUpdate(User $requestUser, User $responseUser, User $existingUser) { $responseUser->populate($requestUser); return new Result($responseUser); }
/** * populateFromObject * * @param UserInterface $object * * @return void * @throws RcmUserReadOnlyException */ public function populateFromObject(UserInterface $object) { if (!$this->locked) { return parent::populateFromObject($object); } throw new RcmUserReadOnlyException('Object is READ ONLY'); }
/** * parseDeletedUsername * * @param User $user user * * @return null|string */ public function parseDeletedUsername(User $user) { try { $usernameArr = json_decode($user->getUsername(), true); } catch (\Exception $e) { return null; } if (count($usernameArr) !== 3) { return null; } if ($usernameArr[1] !== $user->getId()) { return null; } return $usernameArr[2]; }
/** * canRemove * * @param User $user user * @param string $role role id * * @return bool */ public function canRemove(User $user, $role) { $id = $user->getId(); if (empty($id)) { return false; } return true; }
/** * canUpdate * * @param User $user user * * @return bool */ public function canUpdate(User $user) { $id = $user->getId(); if (empty($id)) { return false; } return true; }
/** * prepareUser * * @param User $user user * * @return User */ public function prepareUser(User $user) { if ($this->getObfuscatePassword()) { $user->setPassword(User::PASSWORD_OBFUSCATE); } return $user; }
public function testGetIdentity() { $result = $this->getRcmUserService()->getIdentity(); $this->assertInstanceOf('\\RcmUser\\User\\Entity\\User', $result, 'Did not return instance of Result.'); $result = $this->getRcmUserService()->getCurrentUser(); $this->assertInstanceOf('\\RcmUser\\User\\Entity\\User', $result, 'Did not return instance of Result.'); $hasIdentity = $this->getRcmUserService()->hasIdentity(); $this->assertTrue($hasIdentity, 'Did not return true.'); $this->getRcmUserService()->refreshIdentity(); $result = $this->getRcmUserService()->getIdentity(); $this->assertInstanceOf('\\RcmUser\\User\\Entity\\User', $result, 'Did not return instance of Result.'); $this->getRcmUserService()->setIdentity($result); $userException = null; try { $newUser = new User(); $newUser->setId('newguy'); $this->getRcmUserService()->setIdentity($newUser); } catch (\Exception $e) { $userException = $e; } $this->assertInstanceOf('\\Exception', $userException); }
/** * getUserProperty * * @param string $propertyId * @param null $default * * @return null */ public function getUserProperty($propertyId, $default = null) { return $this->suUser->getProperty($propertyId, $default); }
/** * testAuth * * @return void */ public function testAuth() { $userAdapter = $this->testBuildUserAdapter(); $user = new User('123'); $user->setPassword('badpass'); $userAdapter->setUser($user); $result = $userAdapter->authenticate(); $this->assertFalse($result->isValid(), 'Username not set should return false'); $user->setUsername('badusername'); $userAdapter->setUser($user); $result = $userAdapter->authenticate(); $this->assertFalse($result->isValid(), 'Bad username should return false'); $user->setUsername('testusername'); $userAdapter->setUser($user); $result = $userAdapter->authenticate(); $this->assertFalse($result->isValid(), 'Bad password should return false'); $user->setPassword('goodpass'); $userAdapter->setUser($user); $result = $userAdapter->authenticate(); $this->assertTrue($result->isValid(), 'Good password should return true'); }
/** * validateUser * * @param User $requestUser requestUser * @param InputFilterInterface $inputFilter inputFilter * * @return Result */ public function validateUser(User $requestUser, InputFilterInterface $inputFilter) { $validUser = new User(); $validUser->populate($requestUser); $inputFilter->setData($validUser); if ($inputFilter->isValid()) { $validUser->populate($inputFilter->getValues()); return new Result($validUser); } else { $result = new Result($validUser, Result::CODE_FAIL, 'User input not valid'); foreach ($inputFilter->getInvalidInput() as $error) { $msg = $error->getName() . ': '; $errs = $error->getMessages(); foreach ($errs as $key => $val) { $result->setMessage($msg .= "{$val} ({$key})"); } } return $result; } }
/** * testCase3 * * @param ServiceLocatorInterface $serviceLocator serviceLocator * @param array $params params * * @return string */ public static function testCase3(ServiceLocatorInterface $serviceLocator, $params = []) { $startTime = time(); $tester = new Tester($serviceLocator); $tester->testId = __FUNCTION__; $testUserId = null; $user = self::parseParam($params, 'user'); $password = self::parseParam($params, 'userPlainTextPassword', 'pass_testCase_3_word1'); $userRoles = self::parseParam($params, 'userRoles', ['admin']); // build new user if if (empty($user)) { $user = new User(); $user->setUsername('testCase_3'); $user->setPassword($password); $tester->addMessage("Create test user: "******"->buildUser result: " . json_encode($user, true)); $user = $tester->testCreateUser($user); if (empty($user)) { $tester->addMessage("TEST FAILED"); return $tester->getMessage(); } $testUserId = $user->getId(); } $resource = self::parseParam($params, 'resource', RcmUserAclResourceProvider::RESOURCE_ID_ROOT); $privilege = self::parseParam($params, 'privilege', ''); $user->setPassword($password); $tester->addMessage("Log in user: "******"TEST FAILED"); return $tester->getMessage(); } $tester->addMessage("Verify logged in: "); $user = $tester->rcmUserService->getIdentity(); if (empty($user->getId())) { $tester->addMessage("TEST FAILED"); return $tester->getMessage(); } $properties = $user->getProperty(UserRoleProperty::PROPERTY_KEY, 'NOT SET'); if ($properties === 'NOT SET') { $tester->addMessage("TEST FAILED"); return $tester->getMessage(); } $tester->addMessage("Current user roles: " . json_encode($properties, true)); /* ACL VALUES */ $tester->addMessage("ACL Roles: " . json_encode($tester->authorizeService->getAcl(RcmUserAclResourceProvider::RESOURCE_ID_ROOT, 'RcmUser')->getRoles(), true)); $tester->addMessage("ACL Resources: " . json_encode($tester->authorizeService->getAcl(RcmUserAclResourceProvider::RESOURCE_ID_ROOT, 'RcmUser')->getResources(), true)); /* ACL CHECK * /* RcmUser */ $tester->addMessage("ACL CHECK: rcmUserService->rcmUserIsAllowed({$resource}, {$privilege}) = " . json_encode($tester->rcmUserService->IsAllowed($resource, $privilege))); /* * $tester->addMessage( "ACL CHECK: viewHelper->rcmUserIsAllowed($resource, $privilege) = " . json_encode( $tester->rcmUserIsAllowed($resource, $privilege) ) ); $tester->addMessage( "ACL CHECK: ". "controllerPlugin->rcmUserIsAllowed($resource, $privilege) = " . json_encode( $tester->userController->rcmUserIsAllowed($resource, $privilege) ) ); /* */ // clean up user if we created it if ($testUserId !== null) { $tester->addMessage("Clean up test user:"******"TEST FAILED"); return $tester->getMessage(); } } $tester->addMessage("TEST SUCCESS: [" . __FUNCTION__ . "] Time to complete:" . (time() - $startTime) . "sec"); return $tester->getMessage(); }
/** * Merges values of the $user arg into this user if the values are not set * * @param User $user user * * @return void */ public function merge(User $user) { if ($this->getId() === null) { $this->setId($user->getId()); } if ($this->getUsername() === null) { $this->setUsername($user->getUsername()); } if ($this->getPassword() === null) { $this->setPassword($user->getPassword()); } if ($this->getState() === null) { $this->setState($user->getState()); } if ($this->getEmail() === null) { $this->setEmail($user->getEmail()); } if ($this->getName() === null) { $this->setName($user->getName()); } $properties = $user->getProperties(); foreach ($properties as $key => $property) { $userProperty = $this->getProperty($key); if (empty($userProperty)) { $this->setProperty($key, $property); } } }
/** * buildValidRoles * * @param User $user user * @param array $roles roles * * @return array */ public function buildValidRoles(User $user, $roles = []) { if (!empty($roles)) { return $roles; } $id = $user->getId(); if (empty($id)) { $roles = $this->getDefaultGuestRoleIds()->getData(); } else { $roles = $this->getDefaultUserRoleIds()->getData(); } return $roles; }
/** * getImpersonatorUser Get the admin user from the user if SUed * * @param User $user * * @return mixed|null */ public function getImpersonatorUser(User $user) { /** @var SuProperty $suProperty */ $suProperty = $user->getProperty(SuProperty::SU_PROPERTY); if (empty($suProperty)) { // ERROR return null; } $suUser = $suProperty->getUser(); if (empty($suUser)) { // ERROR return null; } return $suUser; }
/** * getUserRoles * * @param User|null $user user * * @return null */ public function getUserRoles($user) { if (!$user instanceof User) { return $this->getGuestRole(); } /** @var $userRoleProperty UserRoleProperty */ $userRoleProperty = $user->getProperty(UserRoleProperty::PROPERTY_KEY); if (!$userRoleProperty instanceof UserRoleProperty) { return []; } return $userRoleProperty->getRoles(); }
/** * buildUser * * @param array $data data * * @return void */ protected function buildUser($data) { $user = new User(); $user->populate($data, ['properties']); $properties = []; if (isset($data['properties'])) { $properties = $data['properties']; } if (isset($properties[UserRoleProperty::PROPERTY_KEY])) { $roles = $properties[UserRoleProperty::PROPERTY_KEY]; $userRoleProperty = new UserRoleProperty(); $userRoleProperty->populate($roles); $user->setProperty(UserRoleProperty::PROPERTY_KEY, $userRoleProperty); } return $user; }
/** * deleteUser * * @param User $requestUser requestUser * * @return mixed|Result */ public function deleteUser(User $requestUser) { /* <LOW_LEVEL_PREP> */ // require id $id = $requestUser->getId(); if (empty($id)) { return new Result(null, Result::CODE_FAIL, 'User Id required for update.'); } // check if exists $existingUserResult = $this->readUser($requestUser); if (!$existingUserResult->isSuccess()) { // ERROR return $existingUserResult; } $responseUser = new User(); $responseUser->populate($existingUserResult->getUser()); $requestUser = new ReadOnlyUser($requestUser); /* </LOW_LEVEL_PREP> */ /* @event beforeDeleteUser */ $results = $this->getEventManager()->trigger('beforeDeleteUser', $this, ['requestUser' => $requestUser, 'responseUser' => $responseUser], function ($result) { return !$result->isSuccess(); }); if ($results->stopped()) { return $results->last(); } /* @event deleteUser */ $results = $this->getEventManager()->trigger('deleteUser', $this, ['requestUser' => $requestUser, 'responseUser' => $responseUser], function ($result) { return !$result->isSuccess(); }); if ($results->stopped()) { $result = $results->last(); $this->getEventManager()->trigger('deleteUserFail', $this, ['result' => $result]); return $result; } $result = new Result($responseUser); /* @event deleteUserSuccess */ $this->getEventManager()->trigger('deleteUserSuccess', $this, ['result' => $result]); return $result; }
/** * testMerge * * @covers \RcmUser\User\Entity\User::merge * * @return void */ public function testMerge() { $userA = new User(); $userB = $this->getNewUser('B'); $userC = $this->getNewUser('C'); $userA->merge($userB); $this->assertEquals($userA, $userB, 'Merge to empty object not successful'); $userA->merge($userC); $this->assertNotEquals($userA, $userC, 'Merge to populated object not successful'); $userA->setId(null); $userA->merge($userC); $this->assertNotEquals($userA, $userC, 'Merge to populated single property not successful'); $this->assertEquals($userA->getId(), $userC->getId(), 'Merge to single property not successful'); }
protected function addUsers($username, $password, $fullname, $email) { $sm = $this->getServiceLocator(); /** @var \RcmUser\Service\RcmUserService $userService */ $userService = $sm->get('RcmUser\\Service\\RcmUserService'); /** @var \RcmUser\User\Service\UserRoleService $userRoleService */ $userRoleService = $sm->get('RcmUser\\User\\Service\\UserRoleService'); /** @var \RcmUser\Acl\Service\AclDataService $aclDataService */ $aclDataService = $sm->get('RcmUser\\Acl\\AclDataService'); $user = new User(); $user->setUsername($username); $user->setPassword($password); $user->setEmail($email); $user->setName($fullname); $user->setState('enabled'); $response = $userService->createUser($user); if (!$response->isSuccess()) { throw new \Exception(implode("<br />", $response->getMessages())); } $user = $response->getData(); $suRoleIdResponse = $aclDataService->getSuperAdminRoleId(); $suRoleId = $suRoleIdResponse->getData(); $suRole = new AclRole(); $suRole->setRoleId($suRoleId); $suRole->setDescription('Super Admin Role'); $response = $aclDataService->createRole($suRole); if (!$response->isSuccess()) { throw new \Exception(implode("<br />", $response->getMessages())); } $guestRoleIdResponse = $aclDataService->getGuestRoleId(); $guestRoleId = $guestRoleIdResponse->getData(); $guestRole = new AclRole(); $guestRole->setRoleId($guestRoleId); $guestRole->setDescription('Default Guest'); $response = $aclDataService->createRole($guestRole); if (!$response->isSuccess()) { throw new \Exception(implode("<br />", $response->getMessages())); } $response = $userRoleService->addRole($user, $suRoleId); if (!$response->isSuccess()) { throw new \Exception(implode("<br />", $response->getMessages())); } }
/** * read * * @param User $user user * * @return Result */ public function read(User $user) { $userId = $user->getId(); if (empty($userId)) { return new Result([], Result::CODE_FAIL, 'User id required to get user roles.'); } $query = $this->getEntityManager()->createQuery('SELECT userRole.roleId FROM ' . $this->getEntityClass() . ' userRole ' . 'INDEX BY userRole.roleId ' . 'WHERE userRole.userId = ?1'); $query->setParameter(1, $userId); $userRoles = $query->getResult(); $userAclRoles = []; foreach ($userRoles as $userRole) { $userAclRoles[] = $userRole['roleId']; } $message = ''; if (empty($userAclRoles)) { $message = 'No roles found'; } return new Result($userAclRoles, Result::CODE_SUCCESS, $message); }