/** * Creates a user by the new user entity * * @param User $user * * @return SimpleUserOverview */ public static function fromAggregateRootDetails(User $user) { $credentials = $user->getCredentials(); $identifier = $user->getId(); $profileData = $user->getSimpleProfile(); return new self($identifier, $credentials->getUsername(), $profileData->getEmail(), $profileData->getLocale()); }
/** * @expectedException \Sententiaregum\User\Application\Exception\FollowerException */ public function testLoadRandomUsersBecauseOfEmptyResult() { $this->user->follow(User::fromDTO(new CreateUserDTO('test', 'foo123', '*****@*****.**'))); $userRepository = $this->getMock(UserRepositoryInterface::class); $userRepository->expects($this->once())->method('findFollowingByFollowing')->will($this->returnValue([])); $service = new FollowerService($userRepository); $service->adviceFollowersByUser($this->user); }
/** * Builds a list that contains advices of users that can be followed by the current user * * @param User $user * @param integer $limit * * @return User[] */ public function adviceFollowersByUser(User $user, $limit = 5) { $followerRepository = $this->followerRepository; $currentFollowing = $user->getFollowing(); if (count($currentFollowing) === 0) { return $followerRepository->findUsersWithMostFollowers($limit, $user); } $advices = $followerRepository->findFollowingByFollowing($user, $limit); if (empty($advices)) { throw new FollowerException(); } return $advices; }
public function testPersistEntityWithRoles() { DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('foobar', '123456', '*****@*****.**', 'Ma27', 'en', ['ROLE_USER'])); $persisted = $this->repository->add($user); $this->assertCount(1, $persisted->getRoles()); }
/** * Builds a new analyse entity * * @param integer $dispatchTimes * * @return AuthenticationFailure */ private function buildEntity($dispatchTimes = 2) { $dispatcher = $this->getMock(EventDispatcher::class); $dispatcher->expects($this->exactly($dispatchTimes))->method('dispatch'); DomainEvents::setEventDispatcher($dispatcher); return new AuthenticationFailure(User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**'))); }
public function testReturnValidUser() { DomainEvents::setEventDispatcher(new EventDispatcher()); $tokenStorage = $this->getMock(TokenStorageInterface::class); $repository = $this->getMock(UserRepositoryInterface::class); $tokenStorage->expects($this->any())->method('getToken')->will($this->returnValue(new UsernamePasswordToken(new User('foo', 'bar'), 'ROLE_USER', 'unknown'))); $repository->expects($this->any())->method('findOneByName')->will($this->returnValue(SystemUser::fromDTO(new CreateUserDTO('foo', 'bar', '*****@*****.**')))); $fetcher = new UserFetcher($repository, $tokenStorage); $fetcher->resolve(); }
public function testSendNotificationAfterPasswordReset() { DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**')); $publisher = $this->getMock(BackendInterface::class); $publisher->expects($this->once())->method('createAndPublish')->with('sen_mailer', ['user' => $user, 'content' => 'notification.password_reset', 'parameters' => ['translation_defaults' => ['%new_password%' => 'new password']], 'override_locale' => true]); $event = new ResetPasswordEvent($user); $event->setNewRawPassword('new password'); $listener = new PasswordResetListener($publisher); $listener->onPasswordReset($event); }
public function testPublishEmail() { DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**'), (new UserActivation())->buildKeyCode(new ActivationKeyCodeGenerator())); $publisher = $this->getMock(BackendInterface::class); $publisher->expects($this->once())->method('createAndPublish')->with('sen_mailer', ['user' => $user, 'config_path' => 'SententiaregumApp:registration', 'parameters' => ['code' => $user->getActivation()->getKeyCode(), 'name' => 'Ma27'], 'override_locale' => true]); $event = new CreateUserEvent($user); $event->setActivationKey($user->getActivation()->getKeyCode()); $listener = new PostRegistrationListener($publisher); $listener->postUserRegistration($event); }
/** * {@inheritdoc} */ public function load(ObjectManager $manager) { $role = new Role('ROLE_USER'); $admin = new Role('ROLE_ADMIN'); $manager->persist($role); $manager->persist($admin); $user1 = new User(new Credentials('admin', '^special_password^'), new UserDetails('*****@*****.**', new \DateTime(), new \DateTime()), [], [$role, $admin]); $user2 = new User(new Credentials('Ma27', 'test-password'), new UserDetails('*****@*****.**', new \DateTime(), new \DateTime()), [$user1], [$role]); $user3 = new User(new Credentials('test', '123456'), new UserDetails('*****@*****.**', new \DateTime(), new \DateTime()), [$user1, $user2], [$role]); $user4 = new User(new Credentials('test2', '123456'), new UserDetails('*****@*****.**', new \DateTime(), new \DateTime()), [], [$role]); $user4->lock(); $user5 = new User(new Credentials('test3', '123456'), new UserDetails('*****@*****.**', new \DateTime(), new \DateTime()), [$user3], [$role]); $user6 = new User(new Credentials('test4', '123456'), new UserDetails('*****@*****.**', new \DateTime(), new \DateTime()), [$user5, $user3, $user1], [$role]); $activation = new UserActivation(); $activation->buildKeyCode(new ActivationKeyCodeGenerator()); $user7 = new User(new Credentials('unactivated', 'foo'), new UserDetails('*****@*****.**', new \DateTime('-3 days'), new \DateTime()), [], [], $activation); foreach ([$user1, $user2, $user3, $user4, $user5, $user6, $user7] as $entity) { $manager->persist($entity); } $manager->flush(); }
public function testActivateUser() { DomainEvents::setEventDispatcher(new EventDispatcher()); $generator = new ActivationKeyCodeGenerator(); $activation = new UserActivation(); $activation->buildKeyCode($generator); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**'), $activation); $userRepository = $this->getMock(UserRepositoryInterface::class); $userRepository->expects($this->once())->method('modify'); $service = new UserService($userRepository, $generator); $service->activateUser($user, new ActivateUserDTO($activation->getKeyCode())); }
public function testResetPassword() { $userRepository = $this->getMock(UserRepositoryInterface::class); $userRepository->expects($this->once())->method('modify'); $generator = new ActivationKeyCodeGenerator(); $service = new PasswordService($userRepository, $generator); DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**')); $service->resetPassword($user); $this->assertTrue($user->getCredentials()->getPassword()->isHashed()); $this->assertFalse($user->getCredentials()->getPassword()->compare('test-password')); }
public function testDeleteApiKey() { $serviceMock = $this->getMock(ApiKeyFactoryInterface::class); $serviceMock->expects($this->any())->method('generateKeyCode')->will($this->returnValue(new ApiKey('api key'))); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**')); $user->authenticateToken(new AuthDTO('Ma27', 'test-password'), $serviceMock); $userRepository = $this->getMock(UserRepositoryInterface::class); $userRepository->expects($this->once())->method('modify'); $service = new TokenService($userRepository, $serviceMock); $service->purgeToken($user); $this->assertNull($user->getToken()); }
public function testIsUserMarked() { $comment = new Comment(User::fromDTO(new CreateUserDTO('Ma27', '123456', '*****@*****.**')), 'foo!'); $user = User::fromDTO(new CreateUserDTO('foo', 'bar', '*****@*****.**')); $reflection = new \ReflectionProperty(User::class, 'identifier'); $reflection->setAccessible(true); $reflection->setValue($user, 1); $analyser = $this->getMock(ContentAnalyserInterface::class); $analyser->expects($this->any())->method('analyse')->will($this->returnValue(new PostMetadata([$user], [], []))); $comment->analyse($analyser); $this->assertTrue($comment->isMarked($user->getId())); }
public function testModifyUser() { /** @var BaseUserController $controller */ $controller = $this->getMockForAbstractClass(BaseUserController::class); $repository = $this->getServiceMockBuilder('sen.user.repository')->getMock(); $repository->expects($this->once())->method('modify'); $container = new Container(); $container->set('sen.user.repository', $repository); $controller->setContainer($container); DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**')); $this->callRestrictedMethod($controller, 'modifyUser', [$user]); }
/** * @dataProvider sortProvider */ public function testSortArrayCollection(array $items, array $expected) { DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('Ma27', '123456', '*****@*****.**')); $collection = new EntryCollection($items); $collection->sort($user); /** @var SortableInterface[] $result */ $result = $collection->toArray(); foreach ($expected as $expected => $key) { $this->assertArrayHasKey($key, $items); $this->assertArrayHasKey($expected, $result); $this->assertSame($items[$key], $result[$expected]); } }
public function testUpdate() { DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**')); $fetcher = $this->getMock(UserFetcherInterface::class); $fetcher->expects($this->once())->method('resolve')->will($this->returnValue($user)); $repository = $this->getMock(UserRepositoryInterface::class); $repository->expects($this->once())->method('modify'); $request = Request::create('/'); $time = time(); $request->server->set('REQUEST_TIME', $time); $listener = new LastActionUpdateEventListener($fetcher, $repository); $event = $this->createPostResponseEvent($request); $listener->onRequestTermination($event); }
public function testSendNotification() { DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**')); $publisher = $this->getMock(BackendInterface::class); $publisher->expects($this->once())->method('createAndPublish')->with('sen_mailer', ['override_locale' => true, 'user' => $user, 'content' => 'notification.auth.failures', 'parameters' => ['translation_defaults' => ['%times%' => 2]]]); $hook = new AuthenticationReportListener($publisher); $entity = new AuthenticationFailure($user); $entity->updateReport(); $entity->updateReport(); $entityReport = $entity->createReport(); $event = new AuthenticationAttemptEvent($user); $event->setReport($entityReport); $hook->onAuthenticationFailure($event); }
/** * @dataProvider getCredentialSet */ public function testTokenAuthentication($apiKey, $providerKey) { DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('username', 'password', '*****@*****.**')); $token = $this->getMock(TokenInterface::class); $token->expects($this->any())->method('getCredentials')->will($this->returnValue($apiKey)); $mock = $this->getMock(UserRepositoryInterface::class); $mock->expects($this->once())->method('findOneByApiKey')->willReturn($user); $provider = new UserProvider($mock); $authenticator = new ApiKeyAuthenticator(); /** @var PreAuthenticatedToken $token */ $token = $authenticator->authenticateToken($token, $provider, $providerKey); $this->assertInstanceOf(PreAuthenticatedToken::class, $token); $this->assertSame($user->getCredentials()->getUsername(), $token->getUser()->getUsername()); $this->assertSame($user->getCredentials()->getPassword()->getHash(), $token->getUser()->getPassword()); $this->assertSame($apiKey, $token->getCredentials()); $this->assertSame($providerKey, $token->getProviderKey()); }
public function testExtractDataFromPostContent() { DomainEvents::setEventDispatcher(new EventDispatcher()); $userRepository = $this->getMock(UserRepositoryInterface::class); $userRepository->expects($this->at(0))->method('findOneByName')->with('foo')->will($this->returnValue(User::fromDTO(new CreateUserDTO('foo', '123456', '*****@*****.**')))); $userRepository->expects($this->at(1))->method('findOneByName')->with('bar')->will($this->returnValue(null)); $anaylser = new ContentAnalyser($userRepository); $postContent = <<<EOF hello word! this is a link: http://google.de and another: ftp://ftp.uni-bayreuth.de/ the user @foo is valid, but the user @bar not and of course a #hashtag EOF; $metadata = $anaylser->analyse($postContent); $this->assertInstanceOf(PostMetadata::class, $metadata); // users $this->assertCount(1, $metadata->getMarkedUsers()); $first = $metadata->getMarkedUsers()->toArray()[0]; $this->assertInstanceOf(User::class, $first); /** @var $first User */ $this->assertSame('foo', $first->getCredentials()->getUsername()); // tags $tags = $metadata->getHashtags(); $this->assertCount(1, $tags); $firstTag = $tags->toArray()[0]; /** @var $firstTag \Sententiaregum\Dashboard\Value\Hashtag */ $this->assertInstanceOf(Hashtag::class, $firstTag); $this->assertSame('hashtag', $firstTag->getName()); // urls $urls = $metadata->getLinks(); $this->assertCount(2, $urls); /** @var Link $second */ $second = $urls->toArray()[1]; $this->assertInstanceOf(Link::class, $second); $this->assertSame($second->getTarget(), 'ftp://ftp.uni-bayreuth.de/'); }
/** * Shares a post * * @param User $user * * @return $this * * @throws \LogicException If the author tries to share its own post * @throws \LogicException If the post is already shared by the user */ public function share(User $user) { if ($this->author->getId() === ($userId = $user->getId())) { throw new \LogicException('Author cannot share its own post!'); } if ($this->canBeShared($userId)) { throw new \LogicException(sprintf('The user "%d" has already shared this post!', $userId)); } $share = new SharedPost($user); $share->share(); $this->shares->add($share); return $this; }
/** * Creates a security user from the actual symfony user * * @param User $user * * @return SecurityUser */ private function toSecurityUser(User $user) { return new SecurityUser($user->getCredentials()->getUsername(), $user->getCredentials()->getPassword()->getHash(), $this->toSecurityRole($user->getRoles()), $user->getSimpleProfile()->isLocked()); }
/** * {@inheritdoc} */ public function findUsersWithMostFollowers($maxQueryResultLength = 5, User $exclude = null) { $qb = $this->getEntityManager()->createQueryBuilder(); $limit = (int) $maxQueryResultLength; $qb->select('user', 'COUNT(follower) AS HIDDEN followerCount')->from('SEN_User:User', 'user')->leftJoin('SEN_User:User', 'follower', Join::WITH, $qb->expr()->isMemberOf('user', 'follower.following'))->groupBy('followerCount')->orderBy('followerCount', 'DESC')->setMaxResults($limit); if (null !== $exclude) { $qb->where($qb->expr()->neq('user.credentials.username', ':excludeUsername'))->setParameter(':excludeUsername', $exclude->getCredentials()->getUsername()); } return $qb->getQuery()->getResult(); }
public function testPasswordReset() { $user = User::fromDTO(new CreateUserDTO('Ma27', '123456', '*****@*****.**')); $this->assertTrue($user->getCredentials()->getPassword()->compare('123456')); $user->resetPassword(new ActivationKeyCodeGenerator()); $this->assertFalse($user->getCredentials()->getPassword()->compare('123456')); }
public function testEqualCookie() { $checker = $this->getAuthorizationChecker(); $user = User::fromDTO(new CreateUserDTO('Ma27', 'foobar', '*****@*****.**')); $fetcher = $this->getResolver($user); $request = Request::create('/'); $request->attributes->set('_route', 'sen_user.request_api_key'); $request->cookies->set('locale', 'en'); $event = new FilterResponseEvent($this->getKernel(), $request, KernelInterface::MASTER_REQUEST, new Response('<h1>hello world!</h1>')); $listener = new ProfileLanguageListener($fetcher, $this->getMock(UserRepositoryInterface::class), $checker); $listener->checkLocaleAfterAuthentication($event); $response = $event->getResponse(); $cookies = $response->headers->getCookies(); $this->assertCount(0, $cookies); }
protected function assertSameUser(User $user1, UserInterface $user2) { foreach ([$user1->getCredentials()->getUsername() => $user2->getUsername(), $user1->getCredentials()->getPassword()->getHash() => $user2->getPassword()] as $expected => $actual) { $this->assertSame($expected, $actual); } }
/** * Activates a user * * @param User $user * @param ActivateUserDTO $keyCode */ public function activateUser(User $user, ActivateUserDTO $keyCode) { $user->activate($keyCode->getCode()); $this->userRepository->modify($user); }
public function testResolveUserFromService() { /** @var BaseController $controller */ $controller = $this->getMockForAbstractClass(BaseController::class); $userService = $this->getServiceMockBuilder('sen.user.service.user')->getMock(); DomainEvents::setEventDispatcher(new EventDispatcher()); $user = User::fromDTO(new CreateUserDTO('Ma27', 'test-password', '*****@*****.**')); $userService->expects($this->any())->method('getUserById')->will($this->returnValue($user)); $container = new Container(); $container->set('sen.user.service.user', $userService); $controller->setContainer($container); $this->assertSame($user, $this->callRestrictedMethod($controller, 'resolveUser', [1])); }
/** * Removes the user token * * @param User $user */ public function purgeToken(User $user) { $user->deleteToken(); $this->userRepository->modify($user); }
/** * Resets the password of a user * * @param User $user */ public function resetPassword(User $user) { $user->resetPassword($this->keyGenerator); $this->userRepository->modify($user); }
/** * @expectedException \LogicException * @expectedExceptionMessage The user "1" has already shared this post! */ public function testPostIsAlreadySharedByUser() { $user = User::fromDTO(new CreateUserDTO('Ma27', '123456', '*****@*****.**')); $reflection = new \ReflectionProperty(User::class, 'identifier'); $reflection->setAccessible(true); $reflection->setValue($user, 1); $post = new Post(User::fromDTO(new CreateUserDTO('foo', 'bar', '*****@*****.**')), 'content'); $post->share($user); $post->share($user); }