/**
  * @test
  */
 public function testGetOROTypeUserByUser()
 {
     $userValueObject = new User(1, User::TYPE_ORO);
     $user = new OroUser();
     $this->oroUserManager->expects($this->once())->method('findUserBy')->with($this->equalTo(array('id' => $userValueObject->getId())))->will($this->returnValue($user));
     $this->diamanteUserService->getByUser($userValueObject);
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function loadUserByOAuthUserResponse(UserResponseInterface $response)
 {
     if (!$this->cm->get('oro_sso.enable_google_sso')) {
         throw new \Exception('SSO is not enabled');
     }
     $username = $response->getUsername();
     if ($username === null) {
         throw new BadCredentialsException('Bad credentials');
     }
     if (!$this->isEmailEnabledForOauth($response->getEmail())) {
         throw new EmailDomainNotAllowedException('Bad credentials');
     }
     $user = $this->userManager->findUserBy([$this->getOAuthProperty($response) => $username]);
     if (!$user) {
         $user = $this->userManager->findUserByEmail($response->getEmail());
         if ($user) {
             $user->setGoogleId($username);
             $this->userManager->updateUser($user);
         }
     }
     if (!$user || !$user->isEnabled()) {
         throw new BadCredentialsException('Bad credentials');
     }
     return $user;
 }
 /**
  * @dataProvider parametersProvider
  *
  * @param array $arguments
  * @param string $result
  */
 public function testParameters(array $arguments, $result)
 {
     $command = $this->application->find($arguments['command']);
     $commandTester = new CommandTester($command);
     $commandTester->execute($arguments);
     $businessUnit = isset($arguments['--user-business-unit']) && isset($this->businessUnits[$arguments['--user-business-unit']]) ? $this->businessUnits[$arguments['--user-business-unit']] : null;
     if (!empty($result)) {
         $this->assertStringStartsWith($result, $commandTester->getDisplay());
         return;
     }
     $this->assertEmpty($commandTester->getDisplay());
     /** @var User $user */
     $user = $this->userManager->findUserByUsername($arguments['--user-name']);
     $this->assertNotEmpty($user);
     if ($businessUnit) {
         $this->assertSame($user->getOrganization(), $businessUnit->getOrganization());
         $this->assertContains($businessUnit, $user->getBusinessUnits());
     }
     $this->assertTrue($user->isEnabled());
     $this->assertEquals($arguments['--user-name'], $user->getUsername());
     $this->assertEquals($arguments['--user-email'], $user->getEmail());
     $this->assertEquals($arguments['--user-firstname'], $user->getFirstName());
     $this->assertEquals($arguments['--user-lastname'], $user->getLastName());
     $userOrganizations = $user->getOrganizations();
     foreach ($arguments['--user-organizations'] as $organizationName) {
         $this->assertContains($this->organizations[$organizationName], $userOrganizations);
     }
 }
Example #4
0
 /**
  * Set status as current
  *
  * @param User   $user
  * @param Status $status
  * @param bool   $reloadUser
  */
 public function setCurrentStatus(User $user, Status $status = null, $reloadUser = true)
 {
     $user->setCurrentStatus($status);
     $this->um->updateUser($user);
     if ($reloadUser) {
         $this->um->reloadUser($user);
     }
 }
Example #5
0
 /**
  * Initialize all supporting entities
  */
 protected function initSupportingEntities()
 {
     $this->contactGroups = $this->contactManager->getRepository('OroCRMContactBundle:Group')->findAll();
     $this->contactSources = $this->contactManager->getRepository('OroCRMContactBundle:Source')->findAll();
     $userStorageManager = $this->userManager->getStorageManager();
     $this->users = $userStorageManager->getRepository('OroUserBundle:User')->findAll();
     $this->countries = $userStorageManager->getRepository('OroAddressBundle:Country')->findAll();
     $this->organization = $this->organizationManager->getRepository('OroOrganizationBundle:Organization')->getFirst();
 }
Example #6
0
 /**
  * @param User   $user
  * @param Status $status
  * @param bool   $updateCurrentStatus
  */
 protected function onSuccess(User $user, Status $status, $updateCurrentStatus)
 {
     $status->setUser($user);
     $this->em->persist($status);
     if ($updateCurrentStatus) {
         $user->setCurrentStatus($status);
         $this->um->updateUser($user);
         $this->um->reloadUser($user);
     }
     $this->em->flush();
 }
 /**
  * @param string $author
  *
  * @return string
  */
 protected function normalizeAuthor($author)
 {
     if (!isset($this->authorCache[$author])) {
         $user = $this->userManager->findUserByUsername($author);
         if (null === $user) {
             $userName = sprintf('%s - %s', $author, $this->translator->trans('Removed user'));
         } else {
             $userName = sprintf('%s %s - %s', $user->getFirstName(), $user->getLastName(), $user->getEmail());
         }
         $this->authorCache[$author] = $userName;
     }
     return $this->authorCache[$author];
 }
Example #8
0
 /**
  * Load default administrator
  *
  * @param ObjectManager $manager
  * @throws \RuntimeException
  */
 public function load(ObjectManager $manager)
 {
     $adminRole = $manager->getRepository('OroUserBundle:Role')->findOneBy(['role' => LoadRolesData::ROLE_ADMINISTRATOR]);
     if (!$adminRole) {
         throw new \RuntimeException('Administrator role should exist.');
     }
     if ($this->isUserWithRoleExist($manager, $adminRole)) {
         return;
     }
     $businessUnit = $manager->getRepository('OroOrganizationBundle:BusinessUnit')->findOneBy(['name' => LoadOrganizationAndBusinessUnitData::MAIN_BUSINESS_UNIT]);
     $organization = $this->getReference('default_organization');
     $adminUser = $this->userManager->createUser();
     $adminUser->setUsername(self::DEFAULT_ADMIN_USERNAME)->setEmail(self::DEFAULT_ADMIN_EMAIL)->setEnabled(true)->setOwner($businessUnit)->setPlainPassword(md5(uniqid(mt_rand(), true)))->addRole($adminRole)->addBusinessUnit($businessUnit)->setOrganization($organization)->addOrganization($organization);
     $this->userManager->updateUser($adminUser);
 }
 /**
  * {@inheritdoc}
  */
 protected function convertValue($value)
 {
     if (!isset($this->cachedResults[$value['author']])) {
         $user = $this->userManager->findUserByUsername($value['author']);
         if (null === $user) {
             $result = sprintf('%s - %s', $value['author'], $this->translator->trans('Removed user'));
         } else {
             $result = sprintf('%s %s - %s', $user->getFirstName(), $user->getLastName(), $user->getEmail());
         }
         if (!empty($value['context'])) {
             $result .= sprintf(' (%s)', $value['context']);
         }
         $this->cachedResults[$value['author']] = $result;
     }
     return $this->cachedResults[$value['author']];
 }
 /**
  * @param Message $message
  * @param Ticket $ticket
  */
 private function processWatchers(Message $message, $ticket)
 {
     if (!$ticket) {
         return;
     }
     /** @var Message\MessageRecipient $recipient */
     foreach ($message->getRecipients() as $recipient) {
         $email = $recipient->getEmail();
         if ($email == $this->configManager->get(self::EMAIL_NOTIFIER_CONFIG_PATH)) {
             continue;
         }
         $diamanteUser = $this->diamanteUserRepository->findUserByEmail($email);
         $oroUser = $this->oroUserManager->findUserByEmail($email);
         if ($oroUser) {
             $user = new User($oroUser->getId(), User::TYPE_ORO);
         } elseif ($diamanteUser) {
             $user = new User($diamanteUser->getId(), User::TYPE_DIAMANTE);
         } else {
             $diamanteUser = $this->diamanteUserFactory->create($email, $recipient->getFirstName(), $recipient->getLastName());
             $this->diamanteUserRepository->store($diamanteUser);
             $user = new User($diamanteUser->getId(), User::TYPE_DIAMANTE);
         }
         $this->watchersService->addWatcher($ticket, $user);
     }
 }
 /**
  * @param mixed $user
  * @param TokenInterface $token
  * @throws \InvalidArgumentException
  */
 protected function setUser($user, TokenInterface $token)
 {
     if (!$user) {
         return;
     }
     $userId = filter_var($user, FILTER_VALIDATE_INT);
     if ($userId) {
         $userEntity = $this->registry->getRepository('OroUserBundle:User')->find($userId);
     } else {
         $userEntity = $this->userManager->findUserByUsernameOrEmail($user);
     }
     if ($userEntity) {
         $token->setUser($userEntity);
     } else {
         throw new \InvalidArgumentException(sprintf('Can\'t find user with identifier %s', $user));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('firstName', 'text', ['required' => true, 'label' => 'orob2b.account.accountuser.first_name.label'])->add('lastName', 'text', ['required' => true, 'label' => 'orob2b.account.accountuser.last_name.label'])->add('email', 'email', ['required' => true, 'label' => 'orob2b.account.accountuser.email.label']);
     $builder->add('plainPassword', 'repeated', ['type' => 'password', 'first_options' => ['label' => 'orob2b.account.accountuser.password.label'], 'second_options' => ['label' => 'orob2b.account.accountuser.password_confirmation.label'], 'invalid_message' => 'orob2b.account.message.password_mismatch', 'required' => true, 'validation_groups' => ['create']]);
     $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
         /** @var AccountUser $accountUser */
         $accountUser = $event->getData();
         if (!$accountUser->getOwner()) {
             $userId = $this->configManager->get('oro_b2b_account.default_account_owner');
             /** @var User $user */
             $user = $this->userManager->getRepository()->find($userId);
             if ($user) {
                 $accountUser->setOwner($user);
             }
         }
     });
 }
Example #13
0
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage Expected Symfony\Component\Security\Core\Role\RoleInterface, \stdClass given
  */
 public function testNotSupportedRole()
 {
     $user = new User();
     $this->metadata->expects($this->once())->method('getAssociationTargetClass')->willReturn('\\stdClass');
     $this->om->expects($this->never())->method('persist')->with($this->equalTo($user));
     $this->om->expects($this->never())->method('flush');
     $repository = $this->getMockBuilder('Oro\\Bundle\\UserBundle\\Entity\\Repository\\UserApiRepository')->disableOriginalConstructor()->getMock();
     $this->om->expects($this->any())->method('getRepository')->will($this->returnValue($repository));
     $this->userManager->updateUser($user);
 }
 /**
  * @param User $user
  *
  * @return bool|OroUser
  */
 public function getOroUser(User $user)
 {
     $user = $this->getByUser($user);
     if ($user instanceof DiamanteUser) {
         $user = $this->oroUserManager->findUserByEmail($user->getEmail());
         if (!$user) {
             return false;
         }
     }
     return $user;
 }
Example #15
0
 /**
  * Process form
  *
  * @param  User $entity
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(User $entity)
 {
     if (in_array($this->request->getMethod(), ['POST', 'PUT'])) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             $entity->setPlainPassword($this->form->get('password')->getData());
             $entity->setPasswordChangedAt(new \DateTime());
             try {
                 $this->mailerProcessor->sendChangePasswordEmail($entity);
             } catch (\Exception $e) {
                 $this->form->addError(new FormError($this->translator->trans('oro.email.handler.unable_to_send_email')));
                 $this->logger->error('Email sending failed.', ['exception' => $e]);
                 return false;
             }
             $this->userManager->updateUser($entity);
             return true;
         }
     }
     return false;
 }
Example #16
0
 /**
  * Creates a user
  *
  * @param  string    $username
  * @param  string    $email
  * @param  string    $firstName
  * @param  string    $lastName
  * @param  \DateTime $birthday
  * @param  mixed     $role
  * @return User
  */
 private function createUser($username, $email, $firstName, $lastName, $birthday, $role)
 {
     /** @var $user User */
     $user = $this->userManager->createUser();
     $user->setEmail($email);
     $user->setUsername($username);
     $user->setFirstName($firstName);
     $user->setLastName($lastName);
     $user->setBirthday($birthday);
     $user->setOwner($this->getBusinessUnit('Acme, General'));
     $user->addBusinessUnit($this->getBusinessUnit('Acme, General'));
     $user->addRole($role);
     $user->setOrganization($this->organization);
     $user->addOrganization($this->organization);
     return $user;
 }
 /**
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage User test_user is not in organization test_organization
  */
 public function testUserNotInOrganization()
 {
     $username = '******';
     $user = new User();
     $user->setUsername($username);
     $organizationName = 'test_organization';
     $organization = new Organization();
     $organization->setName($organizationName);
     $organization->setEnabled(true);
     $event = $this->getEvent();
     /** @var \PHPUnit_Framework_MockObject_MockObject  $input */
     $input = $event->getInput();
     $input->expects($this->at(0))->method('getParameterOption')->with('--' . ConsoleContextListener::OPTION_USER)->will($this->returnValue($username));
     $input->expects($this->at(1))->method('getParameterOption')->with('--' . ConsoleContextListener::OPTION_ORGANIZATION)->will($this->returnValue($organizationName));
     $this->userManager->expects($this->once())->method('findUserByUsernameOrEmail')->with($username)->will($this->returnValue($user));
     $this->organizationRepository->expects($this->once())->method('findOneBy')->with(['name' => $organizationName])->will($this->returnValue($organization));
     $this->listener->onConsoleCommand($event);
 }
 /**
  * @param Notification $notification
  * @return void
  */
 public function notify(Notification $notification)
 {
     if (!$this->container->isScopeActive('request')) {
         $this->container->enterScope('request');
         $this->container->set('request', new Request(), 'request');
     }
     $ticket = $this->loadTicket($notification);
     $changeList = $this->postProcessChangesList($notification);
     foreach ($this->watchersService->getWatchers($ticket) as $watcher) {
         $userType = $watcher->getUserType();
         $user = User::fromString($userType);
         $isOroUser = $user->isOroUser();
         if ($isOroUser) {
             $loadedUser = $this->oroUserManager->findUserBy(['id' => $user->getId()]);
         } else {
             $loadedUser = $this->diamanteUserRepository->get($user->getId());
         }
         $message = $this->message($notification, $ticket, $isOroUser, $loadedUser->getEmail(), $changeList);
         $this->mailer->send($message);
         $reference = new MessageReference($message->getId(), $ticket);
         $this->messageReferenceRepository->store($reference);
     }
 }
Example #19
0
 protected function initSupportingEntities()
 {
     $this->em = $this->container->get('doctrine.orm.entity_manager');
     $userStorageManager = $this->userManager->getStorageManager();
     $this->users = $userStorageManager->getRepository('OroUserBundle:User')->findAll();
 }
Example #20
0
 /**
  * Flush objects
  *
  * @return void
  */
 private function flush()
 {
     $this->userManager->getStorageManager()->flush();
 }
 protected function getUser()
 {
     return $this->userManager->createUser();
 }
 /**
  * @expectedException Symfony\Component\Security\Core\Exception\UsernameNotFoundException
  */
 public function testLoadUserByUsername()
 {
     $crit = ['username' => self::TEST_NAME];
     $this->repository->expects($this->once())->method('findOneBy')->with($this->equalTo($crit))->will($this->returnValue([]));
     $this->userManager->loadUserByUsername(self::TEST_NAME);
 }
 /**
  * @return \PHPUnit_Framework_MockObject_MockObject|ObjectRepository
  */
 protected function assertUserRepositoryCall()
 {
     $repository = $this->getMockBuilder('Oro\\Bundle\\UserBundle\\Entity\\Repository\\UserRepository')->disableOriginalConstructor()->getMock();
     $this->userManager->expects($this->once())->method('getRepository')->willReturn($repository);
     return $repository;
 }
Example #24
0
 /**
  * Finds a user by username.
  * This method is meant to be an extension point for possible child classes.
  *
  * @param  string    $username
  * @return User|null
  */
 protected function findUser($username)
 {
     return $this->userManager->findUserByUsernameOrEmail($username);
 }
Example #25
0
 /**
  * @param UserInterface $user
  * @param string        $field
  * @param mixed         $data
  *
  * @throws \InvalidArgumentException
  */
 protected function setData(UserInterface $user, $field, $data)
 {
     switch ($field) {
         case 'username':
             $user->setUsername($data);
             break;
         case 'name_prefix':
             $user->setNamePrefix($data);
             break;
         case 'first_name':
             $user->setFirstName($data);
             break;
         case 'middle_name':
             $user->setMiddleName($data);
             break;
         case 'last_name':
             $user->setLastName($data);
             break;
         case 'name_suffix':
             $user->setNameSuffix($data);
             break;
         case 'email':
             $user->setEmail($data);
             break;
         case 'password':
             $user->setPlainPassword($data);
             $this->userManager->updatePassword($user);
             break;
         case 'birthday':
             $user->setBirthday(new \DateTime($data, \DateTime::ISO8601));
             break;
         case 'email_notifications':
             $user->setEmailNotifications($data);
             break;
         case 'catalog_locale':
             $user->setCatalogLocale($this->findLocale($data));
             break;
         case 'user_locale':
             $user->setUiLocale($this->findLocale($data));
             break;
         case 'catalog_scope':
             $user->setCatalogScope($this->findChannel($data));
             break;
         case 'default_tree':
             $user->setDefaultTree($this->findCategory($data));
             break;
         case 'roles':
             foreach ($data as $code) {
                 $role = $this->findRole($code);
                 $user->addRole($role);
             }
             break;
         case 'groups':
             foreach ($data as $code) {
                 $role = $this->findGroup($code);
                 $user->addGroup($role);
             }
             break;
         case 'api_key':
             if (null === ($api = $user->getApi())) {
                 $api = new UserApi();
             }
             $api->setApiKey($data)->setUser($user);
             $user->setApi($api);
             break;
     }
 }
 public function testNotifyOroUser()
 {
     $ticketUniqueId = UniqueId::generate();
     $reporter = new UserAdapter(1, UserAdapter::TYPE_DIAMANTE);
     $assignee = new User();
     $assignee->setId(2);
     $assignee->setEmail('*****@*****.**');
     $author = new UserAdapter(1, UserAdapter::TYPE_DIAMANTE);
     $branch = new Branch('KEY', 'Name', 'Description');
     $ticket = new Ticket($ticketUniqueId, new TicketSequenceNumber(1), 'Subject', 'Description', $branch, $reporter, $assignee, new Source(Source::WEB), new Priority(Priority::PRIORITY_MEDIUM), new Status(Status::NEW_ONE));
     $notification = new TicketNotification((string) $ticketUniqueId, $author, 'Header', 'Subject', new \ArrayIterator(array('key' => 'value')), array('file.ext'));
     $message = new \Swift_Message();
     $this->watchersService->expects($this->once())->method('getWatchers')->will($this->returnValue([new WatcherList($ticket, 'oro_1')]));
     $this->oroUserManager->expects($this->once())->method('findUserBy')->with(['id' => 1])->will($this->returnValue($assignee));
     $this->configManager->expects($this->once())->method('get')->will($this->returnValue('*****@*****.**'));
     $this->nameFormatter->expects($this->once())->method('format')->with($this->diamanteUser)->will($this->returnValue('First Last'));
     $this->mailer->expects($this->once())->method('createMessage')->will($this->returnValue($message));
     $this->ticketRepository->expects($this->once())->method('getByUniqueId')->with($ticketUniqueId)->will($this->returnValue($ticket));
     $this->userService->expects($this->once())->method('getByUser')->with($this->equalTo($author))->will($this->returnValue($this->diamanteUser));
     $this->templateResolver->expects($this->any())->method('resolve')->will($this->returnValueMap(array(array($notification, TemplateResolver::TYPE_TXT, 'txt.template.html'), array($notification, TemplateResolver::TYPE_HTML, 'html.template.html'))));
     $optionsConstraint = $this->logicalAnd($this->arrayHasKey('changes'), $this->arrayHasKey('attachments'), $this->arrayHasKey('user'), $this->arrayHasKey('header'), $this->contains($notification->getChangeList()), $this->contains($notification->getAttachments()), $this->contains('First Last'), $this->contains($notification->getHeaderText()));
     $this->twig->expects($this->at(0))->method('render')->with('txt.template.html', $optionsConstraint)->will($this->returnValue('Rendered TXT template'));
     $this->twig->expects($this->at(1))->method('render')->with('html.template.html', $optionsConstraint)->will($this->returnValue('Rendered HTML template'));
     $this->mailer->expects($this->once())->method('send')->with($this->logicalAnd($this->isInstanceOf('\\Swift_Message'), $this->callback(function (\Swift_Message $other) use($notification) {
         $to = $other->getTo();
         return false !== strpos($other->getSubject(), $notification->getSubject()) && false !== strpos($other->getSubject(), 'KEY-1') && false !== strpos($other->getBody(), 'Rendered TXT template') && array_key_exists('*****@*****.**', $to) && $other->getHeaders()->has('References') && false !== strpos($other->getHeaders()->get('References'), '*****@*****.**') && false !== strpos($other->getHeaders()->get('References'), '*****@*****.**');
     })));
     $this->messageReferenceRepository->expects($this->once())->method('findAllByTicket')->with($ticket)->will($this->returnValue(array(new MessageReference('*****@*****.**', $ticket), new MessageReference('*****@*****.**', $ticket))));
     $this->messageReferenceRepository->expects($this->once())->method('store')->with($this->logicalAnd($this->isInstanceOf('\\Diamante\\DeskBundle\\Model\\Ticket\\EmailProcessing\\MessageReference')));
     $notifier = new EmailNotifier($this->container, $this->twig, $this->mailer, $this->templateResolver, $this->ticketRepository, $this->messageReferenceRepository, $this->userService, $this->nameFormatter, $this->diamanteUserRepository, $this->configManager, $this->oroUserManager, $this->watchersService, $this->senderHost);
     $notifier->notify($notification);
 }