/**
  * @expectedException \Ma27\ApiKeyAuthenticationBundle\Exception\CredentialException
  * @expectedExceptionMessage BACKEND_AUTH_NON_APPROVED
  */
 public function testUserIsNonApprovedAndLocked()
 {
     $user = new User();
     $user->lock();
     $hook = new IncompleteUserCheckListener();
     $hook->validateUserOnAuthentication(new OnAuthenticationEvent($user));
 }
 /**
  * {@inheritdoc}
  */
 public function checkApprovalByUser(User $user)
 {
     if (!$this->lookupKeyInRedisDatabase($user->getActivationKey())) {
         // the associated model will be loaded through lazy loading (doctrine sends a call to the db using a proxy for the model).
         // this is because the model representing parts of the approval process must be hydrated through
         // doctrine's complex hydration algorithm. In case of issues with redis, this data can be used
         // as backup, but the hydration of one-to-one relations is slow, so redis will be used by default.
         return !$user->getPendingActivation()->isActivationExpired();
     }
     return true;
 }
Exemplo n.º 3
0
 /**
  * @Given the following users exist:
  */
 public function theFollowingUsersExist(TableNode $table)
 {
     /** @var \Ma27\ApiKeyAuthenticationBundle\Model\Password\PasswordHasherInterface $hasher */
     $hasher = $this->getContainer()->get('ma27_api_key_authentication.password.strategy');
     $em = $this->getEntityManager();
     $userRole = $em->getRepository('Account:Role')->findOneBy(['role' => 'ROLE_USER']);
     $adminRole = $em->getRepository('Account:Role')->findOneBy(['role' => 'ROLE_ADMIN']);
     foreach ($table->getHash() as $row) {
         $user = User::create($row['username'], $hasher->generateHash($row['password']), $row['email']);
         if (isset($row['user_id'])) {
             // there are cases where the user id should be known
             $r = new \ReflectionProperty(User::class, 'id');
             $r->setAccessible(true);
             $r->setValue($user, $row['user_id']);
         }
         if (isset($row['activation_date'])) {
             $user->getPendingActivation()->setActivationDate(new \DateTime($row['activation_date']));
         }
         if (!(isset($row['is_non_activated']) && $row['is_non_activated'] === 'true')) {
             $user->setState(User::STATE_APPROVED);
             // roles only allowed for approved users
             $user->addRole($userRole);
             if (isset($row['is_admin']) && $row['is_admin'] === 'true') {
                 $user->addRole($adminRole);
             }
         } else {
             if (isset($row['activation_key'])) {
                 $user->setActivationKey($row['activation_key']);
             }
         }
         $em->persist($user);
     }
     $em->flush();
 }
Exemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     $passwordHasher = new PhpPasswordHasher();
     $userRole = $manager->getRepository('Account:Role')->findOneBy(['role' => 'ROLE_USER']);
     $user1 = User::create('Ma27', '72aM', '*****@*****.**', $passwordHasher);
     $user1->performStateTransition(User::STATE_APPROVED);
     $user1->addRole($userRole);
     $user1->updateLastAction();
     $user1->modifyUserLocale('de');
     $user2 = User::create('benbieler', 'releibneb', '*****@*****.**', $passwordHasher);
     $user2->performStateTransition(User::STATE_APPROVED);
     $user2->addRole($userRole);
     $user2->updateLastAction();
     $locked = User::create('anonymus', 'sumynona', '*****@*****.**', $passwordHasher);
     $locked->performStateTransition(User::STATE_APPROVED);
     $locked->addRole($userRole);
     $locked->performStateTransition(User::STATE_LOCKED);
     $locked->updateLastAction();
     $user2->addFollowing($user1);
     $user1->addFollowing($user2);
     $user1->addFollowing($manager->getRepository('Account:User')->findOneBy(['username' => 'admin']));
     /** @var User $userModel */
     foreach ([$user1, $user2, $locked] as $userModel) {
         $manager->persist($userModel);
     }
     $manager->flush();
 }
 public function testAddUser()
 {
     $event = new NotificationInput();
     $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher());
     $event->addUser($user);
     $this->assertCount(1, $event->getUsers());
     $this->assertSame($user, $event->getUsers()[0]);
 }
 public function testUpdateLastActionAfterLogin()
 {
     $listener = new UpdateLatestActivationListener();
     $user = User::create('Ma27', 'foo', '*****@*****.**', new PhpPasswordHasher());
     $dateTime = new \DateTime('-5 minutes');
     $user->updateLastAction();
     $listener->updateOnLogin(new OnAuthenticationEvent($user));
     $this->assertGreaterThan($dateTime->getTimestamp(), $user->getLastAction()->getTimestamp());
 }
 /**
  * @expectedException \Ma27\ApiKeyAuthenticationBundle\Exception\CredentialException
  * @expectedExceptionMessage BACKEND_AUTH_BLOCKED
  */
 public function testAccountIsTemporaryBlocked()
 {
     $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher());
     $user->performStateTransition(User::STATE_APPROVED);
     $provider = $this->getMock(BlockedAccountReadInterface::class);
     $provider->expects($this->once())->method('isAccountTemporaryBlocked')->with($user->getId())->willReturn(true);
     $hook = new IncompleteUserCheckListener($provider);
     $hook->validateUserOnAuthentication(new OnAuthenticationEvent($user));
 }
 public function testTemplateArgumentReplacesTemplateMapConfiguration()
 {
     $channel = $this->getMock(NotificationChannelInterface::class);
     $channel->expects(self::once())->method('publish');
     $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher());
     $class = 'AppBundle\\Model\\Core\\Handler\\SecretHandler';
     $event = new NotificationInput();
     $event->setLanguage('en')->addParameter('foo', 'bar')->addUser($user);
     $notificator = new ChannelDelegatingNotificator([], ['mail' => $channel]);
     $notificator->publishNotification($class, $event, ['mail'], 'AppBundle:Email/Secret:data');
     self::assertSame('AppBundle:Email/Secret:data', $event->getTemplateSource());
 }
 public function testUpdate()
 {
     $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher());
     $userRepository = $this->getMock(UserWriteRepositoryInterface::class);
     $userRepository->expects($this->once())->method('save')->with($user);
     $handler = new LocaleSwitcherHandler($userRepository);
     $dto = new LocaleSwitcherDTO();
     $this->assertSame('en', $user->getLocale());
     $dto->locale = 'de';
     $dto->user = $user;
     $handler($dto);
     $this->assertSame('de', $user->getLocale());
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     /* @var \Doctrine\ORM\EntityManager $manager */
     $this->checkEntityManager($manager);
     $passwordHasher = new PhpPasswordHasher();
     $roleRepository = $manager->getRepository('Account:Role');
     $userRole = $roleRepository->findOneBy(['role' => 'ROLE_USER']);
     $adminRole = $roleRepository->findOneBy(['role' => 'ROLE_ADMIN']);
     $admin = new User();
     $admin->setState(User::STATE_APPROVED);
     $admin->setUsername('admin');
     $admin->setPassword($passwordHasher->generateHash('123456'));
     $admin->setEmail('*****@*****.**');
     $admin->addRole($adminRole);
     $admin->addRole($userRole);
     $admin->setLastAction(new \DateTime());
     $manager->persist($admin);
     $manager->flush();
 }
Exemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     $passwordHasher = new PhpPasswordHasher();
     $roleRepository = $manager->getRepository('Account:Role');
     $userRole = $roleRepository->findOneBy(['role' => 'ROLE_USER']);
     $adminRole = $roleRepository->findOneBy(['role' => 'ROLE_ADMIN']);
     $admin = User::create('admin', '123456', '*****@*****.**', $passwordHasher);
     $admin->performStateTransition(User::STATE_APPROVED);
     $admin->addRole($adminRole);
     $admin->addRole($userRole);
     $admin->updateLastAction();
     $manager->persist($admin);
     $manager->flush();
 }
 /**
  * @Given there's an activation key stored in redis
  */
 public function thereSAnActivationKeyStoredInRedis()
 {
     /** @var \AppBundle\Model\User\Registration\Generator\ActivationKeyCodeGeneratorInterface $key */
     $key = $this->getContainer()->get('app.user.registration.activation_key_generator')->generate();
     $activation = new PendingActivation();
     $activation->setActivationDate(new \DateTime());
     $user = User::create('Ma27-2', '123456', '*****@*****.**');
     $user->setPendingActivation($activation);
     $user->setActivationKey($key);
     $this->getEntityManager()->persist($user);
     $this->getEntityManager()->flush();
     $this->getContainer()->get('app.redis.cluster.approval')->attachNewApproval($key);
     $this->key = $key;
 }
 protected function createValidator()
 {
     $repository = $this->getMock(ObjectRepository::class);
     $repository->expects($this->any())->method('findOneBy')->with(['username' => 'Ma27'])->willReturn($this->returnValue(User::create('Ma27', 'foo', '*****@*****.**', new PhpPasswordHasher())));
     $classMetadata = $this->getMockWithoutInvokingTheOriginalConstructor(ClassMetadata::class);
     $classMetadata->expects($this->any())->method('hasField')->willReturn(true);
     $classMetadata->isEmbeddedClass = false;
     $classMetadata->isMappedSuperclass = false;
     $manager = $this->getMock(ObjectManager::class);
     $manager->expects($this->any())->method('getRepository')->willReturn($repository);
     $manager->expects($this->any())->method('getClassMetadata')->willReturn($classMetadata);
     $mockRegistry = $this->getMock(ManagerRegistry::class);
     $mockRegistry->expects($this->any())->method('getManagerForClass')->willReturn($manager);
     return new UniquePropertyValidator($mockRegistry);
 }
 public function testSendMail()
 {
     $defaultEmail = '*****@*****.**';
     $event = new MailerEvent();
     $event->addUser(User::create('Ma27', '123456', '*****@*****.**'));
     $event->addUser(User::create('benbieler', '123456', '*****@*****.**'));
     $event->setTemplateSource('AppBundle:emails:test');
     $mailer = $this->getMockWithoutInvokingTheOriginalConstructor(\Swift_Mailer::class);
     $templatingEngine = $this->getMockWithoutInvokingTheOriginalConstructor(TwigEngine::class);
     $templatingEngine->expects($this->at(0))->method('render')->with('AppBundle:emails:test.txt.twig', [])->willReturn('Notifications');
     $templatingEngine->expects($this->at(1))->method('render')->with('AppBundle:emails:test.html.twig', [])->willReturn('<b>Notifications</b>');
     $translator = $this->getMock(TranslatorInterface::class);
     $translator->expects($this->once())->method('trans')->with('NOTIFICATIONS_SUBJECT', [], 'notifications')->willReturn('Sententiaregum Notifications');
     $listener = new MailListener($mailer, $translator, $templatingEngine, $defaultEmail);
     $listener->onMailEvent($event);
 }
 public function testConfigureData()
 {
     $trait = $this->getMockForTrait(NotificatableTrait::class);
     $publisher = $this->getMock(NotificatorInterface::class);
     $class = get_class($trait);
     $publisher->expects($this->once())->method('publishNotification')->willReturnCallback(function (string $className, NotificationInput $event, array $channels) use($class) {
         self::assertSame($className, $class);
         self::assertCount(1, $event->getUsers());
         self::assertNull($event->getLanguage());
         self::assertCount(1, $event->getParameters());
         self::assertSame('bar', $event->getParameters()['foo']);
         self::assertSame($channels, ['mail']);
         $user = $event->getUsers()[0];
         self::assertSame('Ma27', $user->getUsername());
     });
     $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher());
     $trait->setNotificator($publisher);
     $trait->notify(['foo' => 'bar'], [$user], ['mail']);
 }
 public function testNotifyOnMultipleAuthAttempts()
 {
     $user = User::create('Ma27', '123456', '*****@*****.**');
     $user->addFailedAuthenticationWithIp('127.0.0.1');
     $user->addFailedAuthenticationWithIp('127.0.0.1');
     $entityManager = $this->getMock(EntityManagerInterface::class);
     $entityManager->expects($this->once())->method('persist')->with($user);
     $entityManager->expects($this->once())->method('flush');
     $eventDispatcher = $this->getMock(EventDispatcherInterface::class);
     $eventDispatcher->expects($this->once())->method('dispatch');
     $request = Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1']);
     $stack = new RequestStack();
     $stack->push($request);
     $tracer = $this->getMock(IpTracingServiceInterface::class, ['getIpLocationData']);
     $tracer->expects($this->any())->method('getIpLocationData')->willReturn(new IpLocation('127.0.0.1', 'Germany', 'Bavaria', 'Munich', 48, 11));
     $listener = new CredentialNotifyListener($entityManager, $eventDispatcher, $stack, $tracer);
     $listener->onFailedAuthentication(new OnInvalidCredentialsEvent($user));
     $this->assertFalse($user->exceedsIpFailedAuthAttemptMaximum('127.0.0.1'));
 }
Exemplo n.º 17
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     /* @var \Doctrine\ORM\EntityManager $manager */
     $this->checkEntityManager($manager);
     $passwordHasher = new PhpPasswordHasher();
     $userRole = $manager->getRepository('Account:Role')->findOneBy(['role' => 'ROLE_USER']);
     $user1 = new User();
     $user1->setState(User::STATE_APPROVED);
     $user1->setUsername('Ma27');
     $user1->setPassword($passwordHasher->generateHash('72aM'));
     $user1->setEmail('*****@*****.**');
     $user1->addRole($userRole);
     $user1->setLastAction(new \DateTime());
     $user1->setLocale('de');
     $user2 = new User();
     $user2->setState(User::STATE_APPROVED);
     $user2->setUsername('benbieler');
     $user2->setPassword($passwordHasher->generateHash('releibneb'));
     $user2->setEmail('*****@*****.**');
     $user2->addRole($userRole);
     $user2->setLastAction(new \DateTime());
     $locked = new User();
     $locked->setState(User::STATE_APPROVED);
     $locked->setUsername('anonymus');
     $locked->setPassword($passwordHasher->generateHash('sumynona'));
     $locked->setEmail('*****@*****.**');
     $locked->addRole($userRole);
     $locked->lock();
     $locked->setLastAction(new \DateTime());
     $user2->addFollowing($user1);
     $user1->addFollowing($user2);
     $user1->addFollowing($manager->getRepository('Account:User')->findOneBy(['username' => 'admin']));
     /** @var User $userModel */
     foreach ([$user1, $user2, $locked] as $userModel) {
         $manager->persist($userModel);
     }
     $manager->flush();
 }
 public function testNotifyOnMultipleAuthAttempts()
 {
     $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher());
     $user->addFailedAuthenticationWithIp('127.0.0.1');
     $user->addFailedAuthenticationWithIp('127.0.0.1');
     $entityManager = $this->getMock(EntityManagerInterface::class);
     $entityManager->expects($this->once())->method('persist')->with($user);
     $entityManager->expects($this->once())->method('flush');
     $request = Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1']);
     $stack = new RequestStack();
     $stack->push($request);
     $tracer = $this->getMock(IpTracingServiceInterface::class, ['getIpLocationData']);
     $tracer->expects($this->any())->method('getIpLocationData')->willReturn(new IpLocation('127.0.0.1', 'Germany', 'Bavaria', 'Munich', 48, 11));
     $provider = $this->getMock(BlockedAccountWriteProviderInterface::class);
     $provider->expects($this->once())->method('addTemporaryBlockedAccountID')->with($user->getId());
     $notificator = $this->getMock(NotificatorInterface::class);
     $notificator->expects(self::once())->method('publishNotification');
     $listener = new CredentialNotifyListener($entityManager, $stack, $tracer, $provider);
     $listener->setNotificator($notificator);
     $listener->onFailedAuthentication(new OnInvalidCredentialsEvent($user));
 }
 /**
  * Handles a the user creation.
  *
  * @param CreateUserDTO $userDTO
  *
  * @throws \OverflowException If the activation keycode generation failed.
  * @throws \LogicException
  */
 public function __invoke(CreateUserDTO $userDTO)
 {
     $user = User::create($userDTO->username, $userDTO->password, $userDTO->email, $this->hasher);
     $user->modifyUserLocale($userDTO->locale);
     $rounds = 0;
     $isUnique = false;
     $activationKey = null;
     while (!$isUnique) {
         ++$rounds;
         if ($rounds >= 200) {
             throw new \OverflowException('Cannot generate activation key!');
         }
         $activationKey = $this->keyGenerator->generate(255);
         $options = ['entity' => 'Account:User', 'field' => 'pendingActivation.key'];
         $isUnique = count($this->validator->validate($activationKey, new UniqueProperty($options))) === 0;
     }
     $user->storeUniqueActivationKeyForNonApprovedUser($activationKey);
     $this->userRepository->save($user);
     $this->notify(['activation_key' => $user->getPendingActivation()->getKey(), 'username' => $user->getUsername()], [$user], ['mail'], $user->getLocale());
     $userDTO->user = $user;
 }
 public function testUpdateOnlineUsers()
 {
     $provider = $this->getMock(OnlineUserIdDataProviderInterface::class);
     $provider->expects($this->once())->method('addUserId');
     $now = time();
     $request = Request::create('/');
     $request->server->set('REQUEST_TIME', $now);
     $requestStack = $this->getMock(RequestStack::class, ['getMasterRequest']);
     $requestStack->expects($this->once())->method('getMasterRequest')->willReturn($request);
     $user = User::create('Ma27', '123456', '*****@*****.**');
     $entityManager = $this->getMock(EntityManagerInterface::class);
     $entityManager->expects($this->once())->method('persist')->with($user);
     $entityManager->expects($this->once())->method('flush')->with($user);
     $token = $this->getMockWithoutInvokingTheOriginalConstructor(PreAuthenticatedToken::class);
     $token->expects($this->once())->method('getUser')->willReturn($user);
     $listener = new OnlineUsersUpdateListener($provider, $requestStack, $entityManager);
     $event = new OnFirewallAuthenticationEvent();
     $event->setToken($token);
     $listener->onFirewallLogin($event);
     $this->assertSame($now, $user->getLastAction()->getTimestamp());
 }
 public function testActivateAccount()
 {
     $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher());
     $user->performStateTransition(User::STATE_NEW);
     $user->storeUniqueActivationKeyForNonApprovedUser('key');
     $writeRepository = $this->getMock(UserWriteRepositoryInterface::class);
     $writeRepository->expects($this->once())->method('save')->with($user);
     $readRepository = $this->getMock(UserReadRepositoryInterface::class);
     $readRepository->expects($this->once())->method('findUserByUsernameAndActivationKey')->with('Ma27', 'key')->willReturn($user);
     $role = new Role('ROLE_USER');
     $roleRepository = $this->getMock(RoleReadRepositoryInterface::class);
     $roleRepository->expects($this->once())->method('determineDefaultRole')->willReturn($role);
     $handler = new ActivateAccountHandler($readRepository, $writeRepository, $roleRepository);
     $dto = new ActivateAccountDTO();
     $dto->username = '******';
     $dto->activationKey = 'key';
     $handler($dto);
     $this->assertTrue($user->hasRole($role));
     $this->assertSame(User::STATE_APPROVED, $user->getState());
     $this->assertNull($user->getPendingActivation());
 }
 public function testSendMail()
 {
     $defaultEmail = '*****@*****.**';
     $input = new NotificationInput();
     $input->addUser(User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher()));
     $input->addUser(User::create('benbieler', '123456', '*****@*****.**', new PhpPasswordHasher()));
     $input->setTemplateSource('AppBundle:emails:test');
     $mailer = $this->getMockWithoutInvokingTheOriginalConstructor(\Swift_Mailer::class);
     $mailer->expects(self::once())->method('send')->willReturnCallback(function (\Swift_Message $message) {
         self::assertSame($message->getTo(), ['*****@*****.**' => 'Ma27', '*****@*****.**' => 'benbieler']);
         self::assertSame($message->getFrom(), ['*****@*****.**' => 'Sententiaregum']);
     });
     $templatingEngine = $this->getMockWithoutInvokingTheOriginalConstructor(EngineInterface::class);
     $templatingEngine->expects(self::at(0))->method('render')->with('AppBundle:emails:test.txt.twig', ['locale' => 'en'])->willReturn('Notifications');
     $templatingEngine->expects(self::at(1))->method('render')->with('AppBundle:emails:test.html.twig', ['locale' => 'en'])->willReturn('<b>Notifications</b>');
     $translator = $this->getMock(TranslatorInterface::class);
     $translator->expects(self::once())->method('trans')->with('NOTIFICATIONS_SUBJECT', [], 'notifications')->willReturn('Sententiaregum Notifications');
     $translator->expects(self::once())->method('getLocale')->willReturn('en');
     $listener = new MailingChannel($mailer, $translator, $templatingEngine, $defaultEmail);
     $listener->publish($input);
 }
Exemplo n.º 23
0
 /**
  * Checks whether the current user follows a specific user.
  *
  * @param User $user
  *
  * @return bool
  */
 public function follows(User $user)
 {
     foreach ($this->following as $following) {
         if ($following->getUsername() === $user->getUsername()) {
             return true;
         }
     }
     return false;
 }
Exemplo n.º 24
0
 /**
  * Checks whether the current user follows a specific user.
  *
  * @param User $user
  *
  * @return bool
  */
 public function follows(User $user) : bool
 {
     return $this->following->exists(function ($index, User $following) use($user) {
         return $following->getId() === $user->getId();
     });
 }
 /**
  * Builds a new user and validates it.
  *
  * @param CreateUserDTO $userParameters
  *
  * @return mixed[]
  */
 private function buildAndValidateUserModelByDTO(CreateUserDTO $userParameters)
 {
     $violations = $this->validator->validate($userParameters);
     if (count($violations) > 0) {
         return ['valid' => false, 'violations' => $violations];
     }
     $newUser = User::create($userParameters->getUsername(), $this->hasher->generateHash($userParameters->getPassword()), $userParameters->getEmail());
     $newUser->setLocale($userParameters->getLocale());
     $newUser->setActivationKey($this->getUniqueActivationKey());
     return ['valid' => true, 'user' => $newUser];
 }
Exemplo n.º 26
0
 public function testSerialization()
 {
     $user = User::create('Ma27', 'foo', '*****@*****.**');
     $user->setState(User::STATE_APPROVED);
     $user->addRole(new Role('ROLE_USER'));
     $user->isNewUserIp('33.33.33.33');
     $user->addFailedAuthenticationWithIp('127.0.0.1');
     $user->addFailedAuthenticationWithIp('127.0.0.1');
     $user->addFailedAuthenticationWithIp('127.0.0.1');
     $serialized = serialize($user);
     $newUser = unserialize($serialized);
     $this->assertSame('Ma27', $newUser->getUsername());
     $this->assertSame('foo', $newUser->getPassword());
     $this->assertSame('*****@*****.**', $newUser->getEmail());
     $this->assertInstanceOf(\DateTime::class, $newUser->getLastAction());
     $this->assertInstanceOf(\DateTime::class, $newUser->getRegistrationDate());
     $this->assertSame(User::STATE_APPROVED, $newUser->getState());
     $this->assertCount(1, $newUser->getRoles());
     $this->assertFalse($user->isNewUserIp('33.33.33.33'));
     $this->assertTrue($user->exceedsIpFailedAuthAttemptMaximum('127.0.0.1'));
 }
 /**
  * Creates a list that contains the ids of all users following a specific user.
  *
  * @param User $user
  *
  * @return int[]
  */
 public function getFollowingIdsByUser(User $user)
 {
     $qb = $this->_em->createQueryBuilder();
     $result = $qb->select('partial user.{id}')->distinct()->from('Account:User', 'user')->join('Account:User', 'current_user', Join::WITH, $qb->expr()->eq('current_user.id', ':user_id'))->where($qb->expr()->isMemberOf('user', 'current_user.following'))->setParameter(':user_id', $user->getId())->getQuery()->getResult(Query::HYDRATE_ARRAY);
     return array_column($result, 'id');
 }
Exemplo n.º 28
0
 /**
  * @Then I should see the user with id :arg1
  */
 public function iShouldSeeTheUserWithId($arg1)
 {
     Assertion::eq((int) $arg1, $this->user->getId());
 }
 /**
  * Fixes the language cookie if the user's language doesn't match the default one.
  *
  * @param User     $user
  * @param Request  $request
  * @param Response $response
  */
 private function fixCookie(User $user, Request $request, Response $response)
 {
     if ($request->cookies->get('language') === ($locale = $user->getLocale())) {
         return;
     }
     $response->headers->setCookie(new Cookie('language', $locale));
 }
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage Role "ROLE_USER" is not present!
  */
 public function testNoDefaultRole()
 {
     $key = md5(uniqid());
     $user = User::create('Ma27', '123456', '*****@*****.**');
     $repository = $this->getUserRepository();
     $repository->expects($this->once())->method('findUserByUsernameAndActivationKey')->with('Ma27', $key)->willReturn($user);
     $roleRepo = $this->getMockWithoutInvokingTheOriginalConstructor(EntityRepository::class);
     $roleRepo->expects($this->at(0))->method('findOneBy')->with(['role' => 'ROLE_USER']);
     $entityManager = $this->getMock(EntityManagerInterface::class);
     $readyUser = $user->setState(User::STATE_APPROVED);
     $entityManager->expects($this->never())->method('persist')->with($readyUser);
     $entityManager->expects($this->never())->method('flush')->with($readyUser);
     $registration = new TwoStepRegistrationApproach($entityManager, $this->getMock(ActivationKeyCodeGeneratorInterface::class), $this->getMock(ValidatorInterface::class), $this->getMock(EventDispatcherInterface::class), $this->getPasswordHasher(), new ChainSuggestor($entityManager), $this->getActivationProvider(), $repository, $roleRepo);
     $registration->approveByActivationKey($key, 'Ma27');
 }