From 5f09650eef7bea52b7c54c074c0f873f96e53c86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 6 Feb 2015 15:18:54 +0100 Subject: add a real relation between user and entry --- src/Wallabag/CoreBundle/Entity/Entry.php | 41 +++++++++++++------------------- src/Wallabag/CoreBundle/Entity/User.php | 29 +++++++++++++++++++++- 2 files changed, 44 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index a00762ca..937213b4 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -81,13 +81,6 @@ class Entry */ private $updatedAt; - /** - * @var string - * - * @ORM\Column(name="user_id", type="decimal", precision=10, scale=0, nullable=true) - */ - private $userId; - /** * @var string * @@ -123,6 +116,19 @@ class Entry */ private $isPublic; + /** + * @ORM\ManyToOne(targetEntity="User", inversedBy="entries") + */ + private $user; + + /* + * @param User $user + */ + public function __construct(User $user) + { + $this->user = $user; + } + /** * Get id * @@ -263,26 +269,11 @@ class Entry } /** - * Set userId - * - * @param string $userId - * @return Entry - */ - public function setUserId($userId) - { - $this->userId = $userId; - - return $this; - } - - /** - * Get userId - * - * @return string + * @return User */ - public function getUserId() + public function getUser() { - return $this->userId; + return $this->user; } /** diff --git a/src/Wallabag/CoreBundle/Entity/User.php b/src/Wallabag/CoreBundle/Entity/User.php index 6abfd3ae..cfbd57f8 100644 --- a/src/Wallabag/CoreBundle/Entity/User.php +++ b/src/Wallabag/CoreBundle/Entity/User.php @@ -2,6 +2,7 @@ namespace Wallabag\CoreBundle\Entity; +use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\AdvancedUserInterface; @@ -78,10 +79,16 @@ class User implements AdvancedUserInterface, \Serializable */ private $updatedAt; + /** + * @ORM\OneToMany(targetEntity="Entry", mappedBy="user", cascade={"remove"}) + */ + private $entries; + public function __construct() { $this->isActive = true; - $this->salt = md5(uniqid(null, true)); + $this->salt = md5(uniqid(null, true)); + $this->entries = new ArrayCollection(); } /** @@ -231,6 +238,26 @@ class User implements AdvancedUserInterface, \Serializable return $this->updatedAt; } + /** + * @param Entry $entry + * + * @return User + */ + public function addEntry(Entry $entry) + { + $this->entries[] = $entry; + + return $this; + } + + /** + * @return ArrayCollection + */ + public function getEntries() + { + return $this->entries; + } + /** * @inheritDoc */ -- cgit v1.2.3 From 7812f508bcb68d9d0e1868fa568d7a435e7975b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Sat, 7 Feb 2015 22:32:21 +0100 Subject: create an Entry with a User in parameter --- src/Wallabag/CoreBundle/Controller/EntryController.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index 6326d31f..2dfe2f51 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -19,8 +19,9 @@ class EntryController extends Controller */ public function addEntryAction(Request $request) { - $entry = new Entry(); - $entry->setUserId(1); + $repository = $this->getDoctrine()->getRepository('WallabagCoreBundle:User'); + $user = $repository->find(1); + $entry = new Entry($user); $form = $this->createFormBuilder($entry) ->add('url', 'url') -- cgit v1.2.3 From d91691573f108422cc2080462af35ebd62dc93fb Mon Sep 17 00:00:00 2001 From: Jeremy Date: Sun, 8 Feb 2015 21:47:36 +0100 Subject: Add custom auth encoder & provider These custom classes allow Wallabag v2 to be compatible with Wallabag v1 salted password --- src/Wallabag/CoreBundle/Entity/User.php | 6 +- .../Encoder/WallabagPasswordEncoder.php | 88 +++++++++++++++++++++ .../Provider/WallabagAuthenticationProvider.php | 89 ++++++++++++++++++++++ 3 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php create mode 100644 src/Wallabag/CoreBundle/Security/Authentication/Provider/WallabagAuthenticationProvider.php (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/User.php b/src/Wallabag/CoreBundle/Entity/User.php index cfbd57f8..c83250c3 100644 --- a/src/Wallabag/CoreBundle/Entity/User.php +++ b/src/Wallabag/CoreBundle/Entity/User.php @@ -161,7 +161,11 @@ class User implements AdvancedUserInterface, \Serializable */ public function setPassword($password) { - $this->password = $password; + if (!$password && 0 === strlen($password)) { + return; + } + + $this->password = sha1($password.$this->getUsername().$this->getSalt()); return $this; } diff --git a/src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php b/src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php new file mode 100644 index 00000000..56f1affe --- /dev/null +++ b/src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php @@ -0,0 +1,88 @@ +algorithm = $algorithm; + $this->encodeHashAsBase64 = $encodeHashAsBase64; + $this->iterations = $iterations; + } + + public function setUsername($username) + { + $this->username = $username; + } + + /** + * {@inheritdoc} + */ + public function encodePassword($raw, $salt) + { + if (null === $this->username) { + throw new \LogicException('We can not check the password without a username.'); + } + + if ($this->isPasswordTooLong($raw)) { + throw new BadCredentialsException('Invalid password.'); + } + + if (!in_array($this->algorithm, hash_algos(), true)) { + throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm)); + } + + $salted = $this->mergePasswordAndSalt($raw, $salt); + $digest = hash($this->algorithm, $salted, true); + + // "stretch" hash + for ($i = 1; $i < $this->iterations; $i++) { + $digest = hash($this->algorithm, $digest.$salted, true); + } + + return $this->encodeHashAsBase64 ? base64_encode($digest) : bin2hex($digest); + } + + /** + * {@inheritdoc} + * + * We inject the username inside the salted password + */ + protected function mergePasswordAndSalt($password, $salt) + { + if (empty($salt)) { + return $password; + } + + return $password.$this->username.$salt; + } + + /** + * {@inheritdoc} + */ + public function isPasswordValid($encoded, $raw, $salt) + { + return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt)); + } +} diff --git a/src/Wallabag/CoreBundle/Security/Authentication/Provider/WallabagAuthenticationProvider.php b/src/Wallabag/CoreBundle/Security/Authentication/Provider/WallabagAuthenticationProvider.php new file mode 100644 index 00000000..1c7c5fae --- /dev/null +++ b/src/Wallabag/CoreBundle/Security/Authentication/Provider/WallabagAuthenticationProvider.php @@ -0,0 +1,89 @@ +encoderFactory = $encoderFactory; + $this->userProvider = $userProvider; + } + + /** + * {@inheritdoc} + */ + protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token) + { + $currentUser = $token->getUser(); + if ($currentUser instanceof UserInterface) { + if ($currentUser->getPassword() !== $user->getPassword()) { + throw new BadCredentialsException('The credentials were changed from another session.'); + } + } else { + if ("" === ($presentedPassword = $token->getCredentials())) { + throw new BadCredentialsException('The presented password cannot be empty.'); + } + + // give username, it's used to hash the password + $encoder = $this->encoderFactory->getEncoder($user); + $encoder->setUsername($user->getUsername()); + + if (!$encoder->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) { + throw new BadCredentialsException('The presented password is invalid.'); + } + } + } + + /** + * {@inheritdoc} + */ + protected function retrieveUser($username, UsernamePasswordToken $token) + { + $user = $token->getUser(); + if ($user instanceof UserInterface) { + return $user; + } + + try { + $user = $this->userProvider->loadUserByUsername($username); + + if (!$user instanceof UserInterface) { + throw new AuthenticationServiceException('The user provider must return a UserInterface object.'); + } + + return $user; + } catch (UsernameNotFoundException $notFound) { + $notFound->setUsername($username); + throw $notFound; + } catch (\Exception $repositoryProblem) { + $ex = new AuthenticationServiceException($repositoryProblem->getMessage(), 0, $repositoryProblem); + $ex->setToken($token); + throw $ex; + } + } +} -- cgit v1.2.3 From 3b815d2de5a852fe2ebad5827bd4c9070aa175ea Mon Sep 17 00:00:00 2001 From: Jeremy Date: Sun, 8 Feb 2015 23:05:51 +0100 Subject: Add some fixtures Improve test, so user can login Fix some leftJoin Cleanup EntryController --- .../CoreBundle/Controller/EntryController.php | 22 ++++---- .../CoreBundle/DataFixtures/ORM/LoadEntryData.php | 35 ++++++++++++ .../CoreBundle/DataFixtures/ORM/LoadUserData.php | 34 ++++++++++++ .../CoreBundle/Repository/EntryRepository.php | 63 ++++++++++++++-------- .../Tests/Controller/EntryControllerTest.php | 38 +++++++++---- .../Tests/Controller/SecurityControllerTest.php | 40 ++++++++++++++ src/Wallabag/CoreBundle/Tests/WallabagTestCase.php | 34 ++++++++++++ 7 files changed, 222 insertions(+), 44 deletions(-) create mode 100644 src/Wallabag/CoreBundle/DataFixtures/ORM/LoadEntryData.php create mode 100644 src/Wallabag/CoreBundle/DataFixtures/ORM/LoadUserData.php create mode 100644 src/Wallabag/CoreBundle/Tests/Controller/SecurityControllerTest.php create mode 100644 src/Wallabag/CoreBundle/Tests/WallabagTestCase.php (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index 2dfe2f51..e0697ca3 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -19,9 +19,7 @@ class EntryController extends Controller */ public function addEntryAction(Request $request) { - $repository = $this->getDoctrine()->getRepository('WallabagCoreBundle:User'); - $user = $repository->find(1); - $entry = new Entry($user); + $entry = new Entry($this->getUser()); $form = $this->createFormBuilder($entry) ->add('url', 'url') @@ -61,10 +59,10 @@ class EntryController extends Controller */ public function showUnreadAction() { - $repository = $this->getDoctrine()->getRepository('WallabagCoreBundle:Entry'); - // TODO don't give the user ID like this // TODO change pagination - $entries = $repository->findUnreadByUser(1, 0); + $entries = $this->getDoctrine() + ->getRepository('WallabagCoreBundle:Entry') + ->findUnreadByUser($this->getUser()->getId(), 0); return $this->render( 'WallabagCoreBundle:Entry:entries.html.twig', @@ -80,10 +78,10 @@ class EntryController extends Controller */ public function showArchiveAction() { - $repository = $this->getDoctrine()->getRepository('WallabagCoreBundle:Entry'); - // TODO don't give the user ID like this // TODO change pagination - $entries = $repository->findArchiveByUser(1, 0); + $entries = $this->getDoctrine() + ->getRepository('WallabagCoreBundle:Entry') + ->findArchiveByUser($this->getUser()->getId(), 0); return $this->render( 'WallabagCoreBundle:Entry:entries.html.twig', @@ -99,10 +97,10 @@ class EntryController extends Controller */ public function showStarredAction() { - $repository = $this->getDoctrine()->getRepository('WallabagCoreBundle:Entry'); - // TODO don't give the user ID like this // TODO change pagination - $entries = $repository->findStarredByUser(1, 0); + $entries = $this->getDoctrine() + ->getRepository('WallabagCoreBundle:Entry') + ->findStarredByUser($this->getUser()->getId(), 0); return $this->render( 'WallabagCoreBundle:Entry:entries.html.twig', diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadEntryData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadEntryData.php new file mode 100644 index 00000000..fccd06be --- /dev/null +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadEntryData.php @@ -0,0 +1,35 @@ +getReference('admin-user')); + $entry1->setUrl('http://0.0.0.0'); + $entry1->setTitle('test title'); + $entry1->setContent('This is my content /o/'); + + $manager->persist($entry1); + $manager->flush(); + + $this->addReference('entry1', $entry1); + } + + /** + * {@inheritDoc} + */ + public function getOrder() + { + return 20; + } +} diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadUserData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadUserData.php new file mode 100644 index 00000000..da788218 --- /dev/null +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadUserData.php @@ -0,0 +1,34 @@ +setUsername('admin'); + $userAdmin->setPassword('test'); + + $manager->persist($userAdmin); + $manager->flush(); + + $this->addReference('admin-user', $userAdmin); + } + + /** + * {@inheritDoc} + */ + public function getOrder() + { + return 10; + } +} diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index f4c803f9..5ae1337a 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -11,19 +11,20 @@ class EntryRepository extends EntityRepository /** * Retrieves unread entries for a user * - * @param $userId - * @param $firstResult - * @param int $maxResults + * @param int $userId + * @param int $firstResult + * @param int $maxResults + * * @return Paginator */ public function findUnreadByUser($userId, $firstResult, $maxResults = 12) { $qb = $this->createQueryBuilder('e') - ->select('e') ->setFirstResult($firstResult) ->setMaxResults($maxResults) + ->leftJoin('e.user', 'u') ->where('e.isArchived = false') - ->andWhere('e.userId =:userId')->setParameter('userId', $userId) + ->andWhere('u.id =:userId')->setParameter('userId', $userId) ->andWhere('e.isDeleted=false') ->orderBy('e.createdAt', 'desc') ->getQuery(); @@ -36,9 +37,10 @@ class EntryRepository extends EntityRepository /** * Retrieves read entries for a user * - * @param $userId - * @param $firstResult - * @param int $maxResults + * @param int $userId + * @param int $firstResult + * @param int $maxResults + * * @return Paginator */ public function findArchiveByUser($userId, $firstResult, $maxResults = 12) @@ -47,8 +49,9 @@ class EntryRepository extends EntityRepository ->select('e') ->setFirstResult($firstResult) ->setMaxResults($maxResults) + ->leftJoin('e.user', 'u') ->where('e.isArchived = true') - ->andWhere('e.userId =:userId')->setParameter('userId', $userId) + ->andWhere('u.id =:userId')->setParameter('userId', $userId) ->andWhere('e.isDeleted=false') ->orderBy('e.createdAt', 'desc') ->getQuery(); @@ -61,9 +64,10 @@ class EntryRepository extends EntityRepository /** * Retrieves starred entries for a user * - * @param $userId - * @param $firstResult - * @param int $maxResults + * @param int $userId + * @param int $firstResult + * @param int $maxResults + * * @return Paginator */ public function findStarredByUser($userId, $firstResult, $maxResults = 12) @@ -72,9 +76,10 @@ class EntryRepository extends EntityRepository ->select('e') ->setFirstResult($firstResult) ->setMaxResults($maxResults) + ->leftJoin('e.user', 'u') ->where('e.isStarred = true') - ->andWhere('e.userId =:userId')->setParameter('userId', $userId) - ->andWhere('e.isDeleted=false') + ->andWhere('u.id =:userId')->setParameter('userId', $userId) + ->andWhere('e.isDeleted = false') ->orderBy('e.createdAt', 'desc') ->getQuery(); @@ -83,22 +88,34 @@ class EntryRepository extends EntityRepository return $paginator; } - public function findEntries($userId, $isArchived, $isStarred, $isDeleted, $sort, $order) + /** + * Find Entries + * + * @param int $userId + * @param bool $isArchived + * @param bool $isStarred + * @param bool $isDeleted + * @param string $sort + * @param string $order + * + * @return ArrayCollection + */ + public function findEntries($userId, $isArchived = null, $isStarred = null, $isDeleted = null, $sort = 'created', $order = 'ASC') { $qb = $this->createQueryBuilder('e') - ->select('e') - ->where('e.userId =:userId')->setParameter('userId', $userId); + ->leftJoin('e.user', 'u') + ->where('u.id =:userId')->setParameter('userId', $userId); - if (!is_null($isArchived)) { - $qb->andWhere('e.isArchived =:isArchived')->setParameter('isArchived', $isArchived); + if (null !== $isArchived) { + $qb->andWhere('e.isArchived =:isArchived')->setParameter('isArchived', (bool) $isArchived); } - if (!is_null($isStarred)) { - $qb->andWhere('e.isStarred =:isStarred')->setParameter('isStarred', $isStarred); + if (null !== $isStarred) { + $qb->andWhere('e.isStarred =:isStarred')->setParameter('isStarred', (bool) $isStarred); } - if (!is_null($isDeleted)) { - $qb->andWhere('e.isDeleted =:isDeleted')->setParameter('isDeleted', $isDeleted); + if (null !== $isDeleted) { + $qb->andWhere('e.isDeleted =:isDeleted')->setParameter('isDeleted', (bool) $isDeleted); } if ('created' === $sort) { diff --git a/src/Wallabag/CoreBundle/Tests/Controller/EntryControllerTest.php b/src/Wallabag/CoreBundle/Tests/Controller/EntryControllerTest.php index fde210c9..5d8daea3 100644 --- a/src/Wallabag/CoreBundle/Tests/Controller/EntryControllerTest.php +++ b/src/Wallabag/CoreBundle/Tests/Controller/EntryControllerTest.php @@ -2,13 +2,24 @@ namespace Wallabag\CoreBundle\Tests\Controller; -use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; +use Wallabag\CoreBundle\Tests\WallabagTestCase; -class EntryControllerTest extends WebTestCase +class EntryControllerTest extends WallabagTestCase { + public function testLogin() + { + $client = $this->getClient(); + + $crawler = $client->request('GET', '/new'); + + $this->assertEquals(302, $client->getResponse()->getStatusCode()); + $this->assertContains('login', $client->getResponse()->headers->get('location')); + } + public function testGetNew() { - $client = static::createClient(); + $this->logIn(); + $client = $this->getClient(); $crawler = $client->request('GET', '/new'); @@ -20,7 +31,8 @@ class EntryControllerTest extends WebTestCase public function testPostNewEmpty() { - $client = static::createClient(); + $this->logIn(); + $client = $this->getClient(); $crawler = $client->request('GET', '/new'); @@ -37,7 +49,8 @@ class EntryControllerTest extends WebTestCase public function testPostNewOk() { - $client = static::createClient(); + $this->logIn(); + $client = $this->getClient(); $crawler = $client->request('GET', '/new'); @@ -55,13 +68,14 @@ class EntryControllerTest extends WebTestCase $crawler = $client->followRedirect(); - $this->assertCount(1, $alert = $crawler->filter('h2 a')->extract(array('_text'))); + $this->assertGreaterThan(1, $alert = $crawler->filter('h2 a')->extract(array('_text'))); $this->assertContains('Mailjet', $alert[0]); } public function testArchive() { - $client = static::createClient(); + $this->logIn(); + $client = $this->getClient(); $crawler = $client->request('GET', '/archive'); @@ -70,7 +84,8 @@ class EntryControllerTest extends WebTestCase public function testStarred() { - $client = static::createClient(); + $this->logIn(); + $client = $this->getClient(); $crawler = $client->request('GET', '/starred'); @@ -79,13 +94,18 @@ class EntryControllerTest extends WebTestCase public function testView() { - $client = static::createClient(); + $this->logIn(); + $client = $this->getClient(); $content = $client->getContainer() ->get('doctrine.orm.entity_manager') ->getRepository('WallabagCoreBundle:Entry') ->findOneByIsArchived(false); + if (!$content) { + $this->markTestSkipped('No content found in db.'); + } + $crawler = $client->request('GET', '/view/'.$content->getId()); $this->assertEquals(200, $client->getResponse()->getStatusCode()); diff --git a/src/Wallabag/CoreBundle/Tests/Controller/SecurityControllerTest.php b/src/Wallabag/CoreBundle/Tests/Controller/SecurityControllerTest.php new file mode 100644 index 00000000..54cf5073 --- /dev/null +++ b/src/Wallabag/CoreBundle/Tests/Controller/SecurityControllerTest.php @@ -0,0 +1,40 @@ +getClient(); + + $crawler = $client->request('GET', '/new'); + + $this->assertEquals(302, $client->getResponse()->getStatusCode()); + $this->assertContains('login', $client->getResponse()->headers->get('location')); + } + + public function testLoginFail() + { + $client = $this->getClient(); + + $crawler = $client->request('GET', '/login'); + + $form = $crawler->filter('button[type=submit]')->form(); + $data = array( + '_username' => 'admin', + '_password' => 'admin', + ); + + $client->submit($form, $data); + + $this->assertEquals(302, $client->getResponse()->getStatusCode()); + $this->assertContains('login', $client->getResponse()->headers->get('location')); + + $crawler = $client->followRedirect(); + + $this->assertContains('Bad credentials', $client->getResponse()->getContent()); + } +} diff --git a/src/Wallabag/CoreBundle/Tests/WallabagTestCase.php b/src/Wallabag/CoreBundle/Tests/WallabagTestCase.php new file mode 100644 index 00000000..5f092318 --- /dev/null +++ b/src/Wallabag/CoreBundle/Tests/WallabagTestCase.php @@ -0,0 +1,34 @@ +client; + } + + public function setUp() + { + $this->client = static::createClient(); + } + + public function logIn() + { + $crawler = $this->client->request('GET', '/login'); + $form = $crawler->filter('button[type=submit]')->form(); + $data = array( + '_username' => 'admin', + '_password' => 'test', + ); + + $this->client->submit($form, $data); + } +} -- cgit v1.2.3