/** * {@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(); }
/** * @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(); }
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()); }
/** * @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; }
/** * {@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(); }
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')); }
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); }
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)); }
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()); }
/** * 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 testNewCookie() { $request1 = Request::create('/', 'GET', [], ['language' => 'en']); $request1->attributes->set('_route', 'ma27_api_key_authentication.request'); $user = User::create('Ma27', '123456', '*****@*****.**'); $user->setLocale('de'); $event = new FilterResponseEvent($this->getKernel(), $request1, KernelInterface::MASTER_REQUEST, Response::create('{"apiKey":"12345"}')); $repo = $this->getMockWithoutInvokingTheOriginalConstructor(UserRepository::class); $repo->expects($this->once())->method('findOneBy')->willReturn($user); $listener = new LanguageCookieFixerListener($repo); $listener->onResponseFilter($event); $cookie = $event->getResponse()->headers->getCookies()[0]; $this->assertSame($cookie->getName(), 'language'); $this->assertSame($cookie->getValue(), 'de'); }
/** * @When I try to persist the following user: * * @param TableNode $table */ public function persistUser(TableNode $table) { $row = $table->getRow(1); $user = User::create($row[0], $row[1], $row[2], new PhpPasswordHasher()); $this->getEntityManager()->getRepository('Account:User')->save($user); $this->user = $user; }
/** * 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]; }
/** * @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'); }
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')); }
/** * @Given the database is not empty */ public function ensureNonEmptyDatabase() { $user = User::create('testuser', '123456', '*****@*****.**', new PhpPasswordHasher()); $this->getEntityManager()->persist($user); $this->getEntityManager()->flush(); }
/** * @expectedException \LogicException * @expectedExceptionMessage Only approved users can be locked! */ public function testTransitionFromNewToLocked() { $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher()); $user->performStateTransition(User::STATE_LOCKED); }