aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Wallabag/ApiBundle
diff options
context:
space:
mode:
Diffstat (limited to 'src/Wallabag/ApiBundle')
-rw-r--r--src/Wallabag/ApiBundle/Controller/WallabagRestController.php62
-rw-r--r--src/Wallabag/ApiBundle/DependencyInjection/Security/Factory/WsseFactory.php40
-rw-r--r--src/Wallabag/ApiBundle/DependencyInjection/WallabagApiExtension.php5
-rw-r--r--src/Wallabag/ApiBundle/Entity/AccessToken.php31
-rw-r--r--src/Wallabag/ApiBundle/Entity/AuthCode.php31
-rw-r--r--src/Wallabag/ApiBundle/Entity/Client.php25
-rw-r--r--src/Wallabag/ApiBundle/Entity/RefreshToken.php31
-rw-r--r--src/Wallabag/ApiBundle/Resources/config/services.yml12
-rw-r--r--src/Wallabag/ApiBundle/Security/Authentication/Provider/WsseProvider.php79
-rw-r--r--src/Wallabag/ApiBundle/Security/Authentication/Token/WsseUserToken.php24
-rw-r--r--src/Wallabag/ApiBundle/Security/Firewall/WsseListener.php62
-rw-r--r--src/Wallabag/ApiBundle/Tests/AbstractControllerTest.php46
-rw-r--r--src/Wallabag/ApiBundle/Tests/Controller/WallabagRestControllerTest.php238
-rw-r--r--src/Wallabag/ApiBundle/WallabagApiBundle.php9
14 files changed, 250 insertions, 445 deletions
diff --git a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php
index 349229f3..1fee56ad 100644
--- a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php
+++ b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php
@@ -2,8 +2,8 @@
2 2
3namespace Wallabag\ApiBundle\Controller; 3namespace Wallabag\ApiBundle\Controller;
4 4
5use FOS\RestBundle\Controller\FOSRestController;
5use Nelmio\ApiDocBundle\Annotation\ApiDoc; 6use Nelmio\ApiDocBundle\Annotation\ApiDoc;
6use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7use Symfony\Component\HttpFoundation\Request; 7use Symfony\Component\HttpFoundation\Request;
8use Symfony\Component\HttpFoundation\Response; 8use Symfony\Component\HttpFoundation\Response;
9use Wallabag\CoreBundle\Entity\Entry; 9use Wallabag\CoreBundle\Entity\Entry;
@@ -11,7 +11,7 @@ use Wallabag\CoreBundle\Entity\Tag;
11use Hateoas\Configuration\Route; 11use Hateoas\Configuration\Route;
12use Hateoas\Representation\Factory\PagerfantaFactory; 12use Hateoas\Representation\Factory\PagerfantaFactory;
13 13
14class WallabagRestController extends Controller 14class WallabagRestController extends FOSRestController
15{ 15{
16 /** 16 /**
17 * @param Entry $entry 17 * @param Entry $entry
@@ -38,29 +38,11 @@ class WallabagRestController extends Controller
38 } 38 }
39 } 39 }
40 40
41 /** 41 private function validateAuthentication()
42 * Retrieve salt for a giver user.
43 *
44 * @ApiDoc(
45 * parameters={
46 * {"name"="username", "dataType"="string", "required"=true, "description"="username"}
47 * }
48 * )
49 *
50 * @return array
51 */
52 public function getSaltAction($username)
53 { 42 {
54 $user = $this 43 if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
55 ->getDoctrine() 44 throw new AccessDeniedException();
56 ->getRepository('WallabagCoreBundle:User')
57 ->findOneByUsername($username);
58
59 if (is_null($user)) {
60 throw $this->createNotFoundException();
61 } 45 }
62
63 return array($user->getSalt() ?: null);
64 } 46 }
65 47
66 /** 48 /**
@@ -82,6 +64,8 @@ class WallabagRestController extends Controller
82 */ 64 */
83 public function getEntriesAction(Request $request) 65 public function getEntriesAction(Request $request)
84 { 66 {
67 $this->validateAuthentication();
68
85 $isArchived = $request->query->get('archive'); 69 $isArchived = $request->query->get('archive');
86 $isStarred = $request->query->get('star'); 70 $isStarred = $request->query->get('star');
87 $sort = $request->query->get('sort', 'created'); 71 $sort = $request->query->get('sort', 'created');
@@ -122,7 +106,8 @@ class WallabagRestController extends Controller
122 */ 106 */
123 public function getEntryAction(Entry $entry) 107 public function getEntryAction(Entry $entry)
124 { 108 {
125 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 109 $this->validateAuthentication();
110 $this->validateUserAccess($entry->getUser()->getId());
126 111
127 $json = $this->get('serializer')->serialize($entry, 'json'); 112 $json = $this->get('serializer')->serialize($entry, 'json');
128 113
@@ -144,6 +129,8 @@ class WallabagRestController extends Controller
144 */ 129 */
145 public function postEntriesAction(Request $request) 130 public function postEntriesAction(Request $request)
146 { 131 {
132 $this->validateAuthentication();
133
147 $url = $request->request->get('url'); 134 $url = $request->request->get('url');
148 135
149 $entry = $this->get('wallabag_core.content_proxy')->updateEntry( 136 $entry = $this->get('wallabag_core.content_proxy')->updateEntry(
@@ -184,7 +171,8 @@ class WallabagRestController extends Controller
184 */ 171 */
185 public function patchEntriesAction(Entry $entry, Request $request) 172 public function patchEntriesAction(Entry $entry, Request $request)
186 { 173 {
187 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 174 $this->validateAuthentication();
175 $this->validateUserAccess($entry->getUser()->getId());
188 176
189 $title = $request->request->get('title'); 177 $title = $request->request->get('title');
190 $isArchived = $request->request->get('is_archived'); 178 $isArchived = $request->request->get('is_archived');
@@ -228,7 +216,8 @@ class WallabagRestController extends Controller
228 */ 216 */
229 public function deleteEntriesAction(Entry $entry) 217 public function deleteEntriesAction(Entry $entry)
230 { 218 {
231 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 219 $this->validateAuthentication();
220 $this->validateUserAccess($entry->getUser()->getId());
232 221
233 $em = $this->getDoctrine()->getManager(); 222 $em = $this->getDoctrine()->getManager();
234 $em->remove($entry); 223 $em->remove($entry);
@@ -250,7 +239,8 @@ class WallabagRestController extends Controller
250 */ 239 */
251 public function getEntriesTagsAction(Entry $entry) 240 public function getEntriesTagsAction(Entry $entry)
252 { 241 {
253 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 242 $this->validateAuthentication();
243 $this->validateUserAccess($entry->getUser()->getId());
254 244
255 $json = $this->get('serializer')->serialize($entry->getTags(), 'json'); 245 $json = $this->get('serializer')->serialize($entry->getTags(), 'json');
256 246
@@ -271,7 +261,8 @@ class WallabagRestController extends Controller
271 */ 261 */
272 public function postEntriesTagsAction(Request $request, Entry $entry) 262 public function postEntriesTagsAction(Request $request, Entry $entry)
273 { 263 {
274 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 264 $this->validateAuthentication();
265 $this->validateUserAccess($entry->getUser()->getId());
275 266
276 $tags = $request->request->get('tags', ''); 267 $tags = $request->request->get('tags', '');
277 if (!empty($tags)) { 268 if (!empty($tags)) {
@@ -299,7 +290,8 @@ class WallabagRestController extends Controller
299 */ 290 */
300 public function deleteEntriesTagsAction(Entry $entry, Tag $tag) 291 public function deleteEntriesTagsAction(Entry $entry, Tag $tag)
301 { 292 {
302 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 293 $this->validateAuthentication();
294 $this->validateUserAccess($entry->getUser()->getId());
303 295
304 $entry->removeTag($tag); 296 $entry->removeTag($tag);
305 $em = $this->getDoctrine()->getManager(); 297 $em = $this->getDoctrine()->getManager();
@@ -318,6 +310,7 @@ class WallabagRestController extends Controller
318 */ 310 */
319 public function getTagsAction() 311 public function getTagsAction()
320 { 312 {
313 $this->validateAuthentication();
321 $json = $this->get('serializer')->serialize($this->getUser()->getTags(), 'json'); 314 $json = $this->get('serializer')->serialize($this->getUser()->getTags(), 'json');
322 315
323 return $this->renderJsonResponse($json); 316 return $this->renderJsonResponse($json);
@@ -334,7 +327,8 @@ class WallabagRestController extends Controller
334 */ 327 */
335 public function deleteTagAction(Tag $tag) 328 public function deleteTagAction(Tag $tag)
336 { 329 {
337 $this->validateUserAccess($tag->getUser()->getId(), $this->getUser()->getId()); 330 $this->validateAuthentication();
331 $this->validateUserAccess($tag->getUser()->getId());
338 332
339 $em = $this->getDoctrine()->getManager(); 333 $em = $this->getDoctrine()->getManager();
340 $em->remove($tag); 334 $em->remove($tag);
@@ -350,12 +344,12 @@ class WallabagRestController extends Controller
350 * If not, throw exception. It means a user try to access information from an other user. 344 * If not, throw exception. It means a user try to access information from an other user.
351 * 345 *
352 * @param int $requestUserId User id from the requested source 346 * @param int $requestUserId User id from the requested source
353 * @param int $currentUserId User id from the retrieved source
354 */ 347 */
355 private function validateUserAccess($requestUserId, $currentUserId) 348 private function validateUserAccess($requestUserId)
356 { 349 {
357 if ($requestUserId != $currentUserId) { 350 $user = $this->get('security.context')->getToken()->getUser();
358 throw $this->createAccessDeniedException('Access forbidden. Entry user id: '.$requestUserId.', logged user id: '.$currentUserId); 351 if ($requestUserId != $user->getId()) {
352 throw $this->createAccessDeniedException('Access forbidden. Entry user id: '.$requestUserId.', logged user id: '.$user->getId());
359 } 353 }
360 } 354 }
361 355
diff --git a/src/Wallabag/ApiBundle/DependencyInjection/Security/Factory/WsseFactory.php b/src/Wallabag/ApiBundle/DependencyInjection/Security/Factory/WsseFactory.php
deleted file mode 100644
index 402eb869..00000000
--- a/src/Wallabag/ApiBundle/DependencyInjection/Security/Factory/WsseFactory.php
+++ /dev/null
@@ -1,40 +0,0 @@
1<?php
2
3namespace Wallabag\ApiBundle\DependencyInjection\Security\Factory;
4
5use Symfony\Component\DependencyInjection\ContainerBuilder;
6use Symfony\Component\DependencyInjection\Reference;
7use Symfony\Component\DependencyInjection\DefinitionDecorator;
8use Symfony\Component\Config\Definition\Builder\NodeDefinition;
9use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
10
11class WsseFactory implements SecurityFactoryInterface
12{
13 public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
14 {
15 $providerId = 'security.authentication.provider.wsse.'.$id;
16 $container
17 ->setDefinition($providerId, new DefinitionDecorator('wsse.security.authentication.provider'))
18 ->replaceArgument(0, new Reference($userProvider))
19 ;
20
21 $listenerId = 'security.authentication.listener.wsse.'.$id;
22 $listener = $container->setDefinition($listenerId, new DefinitionDecorator('wsse.security.authentication.listener'));
23
24 return array($providerId, $listenerId, $defaultEntryPoint);
25 }
26
27 public function getPosition()
28 {
29 return 'pre_auth';
30 }
31
32 public function getKey()
33 {
34 return 'wsse';
35 }
36
37 public function addConfiguration(NodeDefinition $node)
38 {
39 }
40}
diff --git a/src/Wallabag/ApiBundle/DependencyInjection/WallabagApiExtension.php b/src/Wallabag/ApiBundle/DependencyInjection/WallabagApiExtension.php
index c5cc204e..cde43aed 100644
--- a/src/Wallabag/ApiBundle/DependencyInjection/WallabagApiExtension.php
+++ b/src/Wallabag/ApiBundle/DependencyInjection/WallabagApiExtension.php
@@ -3,9 +3,7 @@
3namespace Wallabag\ApiBundle\DependencyInjection; 3namespace Wallabag\ApiBundle\DependencyInjection;
4 4
5use Symfony\Component\DependencyInjection\ContainerBuilder; 5use Symfony\Component\DependencyInjection\ContainerBuilder;
6use Symfony\Component\Config\FileLocator;
7use Symfony\Component\HttpKernel\DependencyInjection\Extension; 6use Symfony\Component\HttpKernel\DependencyInjection\Extension;
8use Symfony\Component\DependencyInjection\Loader;
9 7
10class WallabagApiExtension extends Extension 8class WallabagApiExtension extends Extension
11{ 9{
@@ -13,9 +11,6 @@ class WallabagApiExtension extends Extension
13 { 11 {
14 $configuration = new Configuration(); 12 $configuration = new Configuration();
15 $config = $this->processConfiguration($configuration, $configs); 13 $config = $this->processConfiguration($configuration, $configs);
16
17 $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
18 $loader->load('services.yml');
19 } 14 }
20 15
21 public function getAlias() 16 public function getAlias()
diff --git a/src/Wallabag/ApiBundle/Entity/AccessToken.php b/src/Wallabag/ApiBundle/Entity/AccessToken.php
new file mode 100644
index 00000000..b1f4e7de
--- /dev/null
+++ b/src/Wallabag/ApiBundle/Entity/AccessToken.php
@@ -0,0 +1,31 @@
1<?php
2
3namespace Wallabag\ApiBundle\Entity;
4
5use FOS\OAuthServerBundle\Entity\AccessToken as BaseAccessToken;
6use Doctrine\ORM\Mapping as ORM;
7
8/**
9 * @ORM\Table("oauth2_access_tokens")
10 * @ORM\Entity
11 */
12class AccessToken extends BaseAccessToken
13{
14 /**
15 * @ORM\Id
16 * @ORM\Column(type="integer")
17 * @ORM\GeneratedValue(strategy="AUTO")
18 */
19 protected $id;
20
21 /**
22 * @ORM\ManyToOne(targetEntity="Client")
23 * @ORM\JoinColumn(nullable=false)
24 */
25 protected $client;
26
27 /**
28 * @ORM\ManyToOne(targetEntity="Wallabag\UserBundle\Entity\User")
29 */
30 protected $user;
31}
diff --git a/src/Wallabag/ApiBundle/Entity/AuthCode.php b/src/Wallabag/ApiBundle/Entity/AuthCode.php
new file mode 100644
index 00000000..81398158
--- /dev/null
+++ b/src/Wallabag/ApiBundle/Entity/AuthCode.php
@@ -0,0 +1,31 @@
1<?php
2
3namespace Wallabag\ApiBundle\Entity;
4
5use FOS\OAuthServerBundle\Entity\AuthCode as BaseAuthCode;
6use Doctrine\ORM\Mapping as ORM;
7
8/**
9 * @ORM\Table("oauth2_auth_codes")
10 * @ORM\Entity
11 */
12class AuthCode extends BaseAuthCode
13{
14 /**
15 * @ORM\Id
16 * @ORM\Column(type="integer")
17 * @ORM\GeneratedValue(strategy="AUTO")
18 */
19 protected $id;
20
21 /**
22 * @ORM\ManyToOne(targetEntity="Client")
23 * @ORM\JoinColumn(nullable=false)
24 */
25 protected $client;
26
27 /**
28 * @ORM\ManyToOne(targetEntity="Wallabag\UserBundle\Entity\User")
29 */
30 protected $user;
31}
diff --git a/src/Wallabag/ApiBundle/Entity/Client.php b/src/Wallabag/ApiBundle/Entity/Client.php
new file mode 100644
index 00000000..d449870a
--- /dev/null
+++ b/src/Wallabag/ApiBundle/Entity/Client.php
@@ -0,0 +1,25 @@
1<?php
2
3namespace Wallabag\ApiBundle\Entity;
4
5use FOS\OAuthServerBundle\Entity\Client as BaseClient;
6use Doctrine\ORM\Mapping as ORM;
7
8/**
9 * @ORM\Table("oauth2_clients")
10 * @ORM\Entity
11 */
12class Client extends BaseClient
13{
14 /**
15 * @ORM\Id
16 * @ORM\Column(type="integer")
17 * @ORM\GeneratedValue(strategy="AUTO")
18 */
19 protected $id;
20
21 public function __construct()
22 {
23 parent::__construct();
24 }
25}
diff --git a/src/Wallabag/ApiBundle/Entity/RefreshToken.php b/src/Wallabag/ApiBundle/Entity/RefreshToken.php
new file mode 100644
index 00000000..be2c1d2e
--- /dev/null
+++ b/src/Wallabag/ApiBundle/Entity/RefreshToken.php
@@ -0,0 +1,31 @@
1<?php
2
3namespace Wallabag\ApiBundle\Entity;
4
5use FOS\OAuthServerBundle\Entity\RefreshToken as BaseRefreshToken;
6use Doctrine\ORM\Mapping as ORM;
7
8/**
9 * @ORM\Table("oauth2_refresh_tokens")
10 * @ORM\Entity
11 */
12class RefreshToken extends BaseRefreshToken
13{
14 /**
15 * @ORM\Id
16 * @ORM\Column(type="integer")
17 * @ORM\GeneratedValue(strategy="AUTO")
18 */
19 protected $id;
20
21 /**
22 * @ORM\ManyToOne(targetEntity="Client")
23 * @ORM\JoinColumn(nullable=false)
24 */
25 protected $client;
26
27 /**
28 * @ORM\ManyToOne(targetEntity="Wallabag\UserBundle\Entity\User")
29 */
30 protected $user;
31}
diff --git a/src/Wallabag/ApiBundle/Resources/config/services.yml b/src/Wallabag/ApiBundle/Resources/config/services.yml
deleted file mode 100644
index 6854a444..00000000
--- a/src/Wallabag/ApiBundle/Resources/config/services.yml
+++ /dev/null
@@ -1,12 +0,0 @@
1services:
2 wsse.security.authentication.provider:
3 class: Wallabag\ApiBundle\Security\Authentication\Provider\WsseProvider
4 public: false
5 arguments: ['', '%kernel.cache_dir%/security/nonces']
6
7 wsse.security.authentication.listener:
8 class: Wallabag\ApiBundle\Security\Firewall\WsseListener
9 public: false
10 tags:
11 - { name: monolog.logger, channel: wsse }
12 arguments: ['@security.context', '@security.authentication.manager', '@logger']
diff --git a/src/Wallabag/ApiBundle/Security/Authentication/Provider/WsseProvider.php b/src/Wallabag/ApiBundle/Security/Authentication/Provider/WsseProvider.php
deleted file mode 100644
index 9bf8b377..00000000
--- a/src/Wallabag/ApiBundle/Security/Authentication/Provider/WsseProvider.php
+++ /dev/null
@@ -1,79 +0,0 @@
1<?php
2
3namespace Wallabag\ApiBundle\Security\Authentication\Provider;
4
5use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
6use Symfony\Component\Security\Core\User\UserProviderInterface;
7use Symfony\Component\Security\Core\Exception\AuthenticationException;
8use Symfony\Component\Security\Core\Exception\NonceExpiredException;
9use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
10use Wallabag\ApiBundle\Security\Authentication\Token\WsseUserToken;
11
12class WsseProvider implements AuthenticationProviderInterface
13{
14 private $userProvider;
15 private $cacheDir;
16
17 public function __construct(UserProviderInterface $userProvider, $cacheDir)
18 {
19 $this->userProvider = $userProvider;
20 $this->cacheDir = $cacheDir;
21
22 // If cache directory does not exist we create it
23 if (!is_dir($this->cacheDir)) {
24 mkdir($this->cacheDir, 0777, true);
25 }
26 }
27
28 public function authenticate(TokenInterface $token)
29 {
30 $user = $this->userProvider->loadUserByUsername($token->getUsername());
31
32 if (!$user) {
33 throw new AuthenticationException('Bad credentials. Did you forgot your username?');
34 }
35
36 if ($user && $this->validateDigest($token->digest, $token->nonce, $token->created, $user->getPassword())) {
37 $authenticatedToken = new WsseUserToken($user->getRoles());
38 $authenticatedToken->setUser($user);
39
40 return $authenticatedToken;
41 }
42
43 throw new AuthenticationException('The WSSE authentication failed.');
44 }
45
46 protected function validateDigest($digest, $nonce, $created, $secret)
47 {
48 // Check created time is not in the future
49 if (strtotime($created) > time()) {
50 throw new AuthenticationException('Back to the future...');
51 }
52
53 // Expire timestamp after 5 minutes
54 if (time() - strtotime($created) > 300) {
55 throw new AuthenticationException('Too late for this timestamp... Watch your watch.');
56 }
57
58 // Validate nonce is unique within 5 minutes
59 if (file_exists($this->cacheDir.'/'.$nonce) && file_get_contents($this->cacheDir.'/'.$nonce) + 300 > time()) {
60 throw new NonceExpiredException('Previously used nonce detected');
61 }
62
63 file_put_contents($this->cacheDir.'/'.$nonce, time());
64
65 // Validate Secret
66 $expected = base64_encode(sha1(base64_decode($nonce).$created.$secret, true));
67
68 if ($digest !== $expected) {
69 throw new AuthenticationException('Bad credentials ! Digest is not as expected.');
70 }
71
72 return $digest === $expected;
73 }
74
75 public function supports(TokenInterface $token)
76 {
77 return $token instanceof WsseUserToken;
78 }
79}
diff --git a/src/Wallabag/ApiBundle/Security/Authentication/Token/WsseUserToken.php b/src/Wallabag/ApiBundle/Security/Authentication/Token/WsseUserToken.php
deleted file mode 100644
index e6d30224..00000000
--- a/src/Wallabag/ApiBundle/Security/Authentication/Token/WsseUserToken.php
+++ /dev/null
@@ -1,24 +0,0 @@
1<?php
2
3namespace Wallabag\ApiBundle\Security\Authentication\Token;
4
5use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
6
7class WsseUserToken extends AbstractToken
8{
9 public $created;
10 public $digest;
11 public $nonce;
12
13 public function __construct(array $roles = array())
14 {
15 parent::__construct($roles);
16
17 $this->setAuthenticated(count($roles) > 0);
18 }
19
20 public function getCredentials()
21 {
22 return '';
23 }
24}
diff --git a/src/Wallabag/ApiBundle/Security/Firewall/WsseListener.php b/src/Wallabag/ApiBundle/Security/Firewall/WsseListener.php
deleted file mode 100644
index 2fcbe014..00000000
--- a/src/Wallabag/ApiBundle/Security/Firewall/WsseListener.php
+++ /dev/null
@@ -1,62 +0,0 @@
1<?php
2
3namespace Wallabag\ApiBundle\Security\Firewall;
4
5use Symfony\Component\HttpFoundation\Response;
6use Symfony\Component\HttpKernel\Event\GetResponseEvent;
7use Symfony\Component\Security\Http\Firewall\ListenerInterface;
8use Symfony\Component\Security\Core\Exception\AuthenticationException;
9use Symfony\Component\Security\Core\SecurityContextInterface;
10use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
11use Wallabag\ApiBundle\Security\Authentication\Token\WsseUserToken;
12use Psr\Log\LoggerInterface;
13
14class WsseListener implements ListenerInterface
15{
16 protected $securityContext;
17 protected $authenticationManager;
18 protected $logger;
19
20 public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, LoggerInterface $logger)
21 {
22 $this->securityContext = $securityContext;
23 $this->authenticationManager = $authenticationManager;
24 $this->logger = $logger;
25 }
26
27 public function handle(GetResponseEvent $event)
28 {
29 $request = $event->getRequest();
30
31 $wsseRegex = '/UsernameToken Username="([^"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
32 if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
33 return;
34 }
35
36 $token = new WsseUserToken();
37 $token->setUser($matches[1]);
38
39 $token->digest = $matches[2];
40 $token->nonce = $matches[3];
41 $token->created = $matches[4];
42
43 try {
44 $authToken = $this->authenticationManager->authenticate($token);
45
46 $this->securityContext->setToken($authToken);
47
48 return;
49 } catch (AuthenticationException $failed) {
50 $failedMessage = 'WSSE Login failed for '.$token->getUsername().'. Why ? '.$failed->getMessage();
51 $this->logger->err($failedMessage);
52
53 // Deny authentication with a '403 Forbidden' HTTP response
54 $response = new Response();
55 $response->setStatusCode(403);
56 $response->setContent($failedMessage);
57 $event->setResponse($response);
58
59 return;
60 }
61 }
62}
diff --git a/src/Wallabag/ApiBundle/Tests/AbstractControllerTest.php b/src/Wallabag/ApiBundle/Tests/AbstractControllerTest.php
new file mode 100644
index 00000000..119889b3
--- /dev/null
+++ b/src/Wallabag/ApiBundle/Tests/AbstractControllerTest.php
@@ -0,0 +1,46 @@
1<?php
2
3namespace Wallabag\ApiBundle\Tests;
4
5use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
6use Symfony\Component\BrowserKit\Cookie;
7
8abstract class AbstractControllerTest extends WebTestCase
9{
10 /**
11 * @var Client
12 */
13 protected $client = null;
14
15 public function setUp()
16 {
17 $this->client = $this->createAuthorizedClient();
18 }
19
20 /**
21 * @return Client
22 */
23 protected function createAuthorizedClient()
24 {
25 $client = static::createClient();
26 $container = $client->getContainer();
27
28 $session = $container->get('session');
29 /** @var $userManager \FOS\UserBundle\Doctrine\UserManager */
30 $userManager = $container->get('fos_user.user_manager');
31 /** @var $loginManager \FOS\UserBundle\Security\LoginManager */
32 $loginManager = $container->get('fos_user.security.login_manager');
33 $firewallName = $container->getParameter('fos_user.firewall_name');
34
35 $user = $userManager->findUserBy(array('username' => 'admin'));
36 $loginManager->loginUser($firewallName, $user);
37
38 // save the login token into the session and put it in a cookie
39 $container->get('session')->set('_security_'.$firewallName,
40 serialize($container->get('security.context')->getToken()));
41 $container->get('session')->save();
42 $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
43
44 return $client;
45 }
46}
diff --git a/src/Wallabag/ApiBundle/Tests/Controller/WallabagRestControllerTest.php b/src/Wallabag/ApiBundle/Tests/Controller/WallabagRestControllerTest.php
index 7ae54b57..bc7ef489 100644
--- a/src/Wallabag/ApiBundle/Tests/Controller/WallabagRestControllerTest.php
+++ b/src/Wallabag/ApiBundle/Tests/Controller/WallabagRestControllerTest.php
@@ -2,99 +2,15 @@
2 2
3namespace Wallabag\ApiBundle\Tests\Controller; 3namespace Wallabag\ApiBundle\Tests\Controller;
4 4
5use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; 5use Wallabag\ApiBundle\Tests\AbstractControllerTest;
6 6
7class WallabagRestControllerTest extends WebTestCase 7class WallabagRestControllerTest extends AbstractControllerTest
8{ 8{
9 protected static $salt; 9 protected static $salt;
10 10
11 /**
12 * Grab the salt once and store it to be available for all tests.
13 */
14 public static function setUpBeforeClass()
15 {
16 $client = self::createClient();
17
18 $user = $client->getContainer()
19 ->get('doctrine.orm.entity_manager')
20 ->getRepository('WallabagCoreBundle:User')
21 ->findOneByUsername('admin');
22
23 self::$salt = $user->getSalt();
24 }
25
26 /**
27 * Generate HTTP headers for authenticate user on API.
28 *
29 * @param string $username
30 * @param string $password
31 *
32 * @return array
33 */
34 private function generateHeaders($username, $password)
35 {
36 $encryptedPassword = sha1($password.$username.self::$salt);
37 $nonce = substr(md5(uniqid('nonce_', true)), 0, 16);
38
39 $now = new \DateTime('now', new \DateTimeZone('UTC'));
40 $created = (string) $now->format('Y-m-d\TH:i:s\Z');
41 $digest = base64_encode(sha1(base64_decode($nonce).$created.$encryptedPassword, true));
42
43 return array(
44 'HTTP_AUTHORIZATION' => 'Authorization profile="UsernameToken"',
45 'HTTP_x-wsse' => 'X-WSSE: UsernameToken Username="'.$username.'", PasswordDigest="'.$digest.'", Nonce="'.$nonce.'", Created="'.$created.'"',
46 );
47 }
48
49 public function testGetSalt()
50 {
51 $client = $this->createClient();
52 $client->request('GET', '/api/salts/admin.json');
53
54 $user = $client->getContainer()
55 ->get('doctrine.orm.entity_manager')
56 ->getRepository('WallabagCoreBundle:User')
57 ->findOneByUsername('admin');
58
59 $this->assertEquals(200, $client->getResponse()->getStatusCode());
60
61 $content = json_decode($client->getResponse()->getContent(), true);
62
63 $this->assertArrayHasKey(0, $content);
64 $this->assertEquals($user->getSalt(), $content[0]);
65
66 $client->request('GET', '/api/salts/notfound.json');
67 $this->assertEquals(404, $client->getResponse()->getStatusCode());
68 }
69
70 public function testWithBadHeaders()
71 {
72 $client = $this->createClient();
73
74 $entry = $client->getContainer()
75 ->get('doctrine.orm.entity_manager')
76 ->getRepository('WallabagCoreBundle:Entry')
77 ->findOneByIsArchived(false);
78
79 if (!$entry) {
80 $this->markTestSkipped('No content found in db.');
81 }
82
83 $badHeaders = array(
84 'HTTP_AUTHORIZATION' => 'Authorization profile="UsernameToken"',
85 'HTTP_x-wsse' => 'X-WSSE: UsernameToken Username="admin", PasswordDigest="Wr0ngDig3st", Nonce="n0Nc3", Created="2015-01-01T13:37:00Z"',
86 );
87
88 $client->request('GET', '/api/entries/'.$entry->getId().'.json', array(), array(), $badHeaders);
89 $this->assertEquals(403, $client->getResponse()->getStatusCode());
90 }
91
92 public function testGetOneEntry() 11 public function testGetOneEntry()
93 { 12 {
94 $client = $this->createClient(); 13 $entry = $this->client->getContainer()
95 $headers = $this->generateHeaders('admin', 'mypassword');
96
97 $entry = $client->getContainer()
98 ->get('doctrine.orm.entity_manager') 14 ->get('doctrine.orm.entity_manager')
99 ->getRepository('WallabagCoreBundle:Entry') 15 ->getRepository('WallabagCoreBundle:Entry')
100 ->findOneBy(array('user' => 1, 'isArchived' => false)); 16 ->findOneBy(array('user' => 1, 'isArchived' => false));
@@ -103,18 +19,17 @@ class WallabagRestControllerTest extends WebTestCase
103 $this->markTestSkipped('No content found in db.'); 19 $this->markTestSkipped('No content found in db.');
104 } 20 }
105 21
106 $client->request('GET', '/api/entries/'.$entry->getId().'.json', array(), array(), $headers); 22 $this->client->request('GET', '/api/entries/'.$entry->getId().'.json');
23 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
107 24
108 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 25 $content = json_decode($this->client->getResponse()->getContent(), true);
109
110 $content = json_decode($client->getResponse()->getContent(), true);
111 26
112 $this->assertEquals($entry->getTitle(), $content['title']); 27 $this->assertEquals($entry->getTitle(), $content['title']);
113 $this->assertEquals($entry->getUrl(), $content['url']); 28 $this->assertEquals($entry->getUrl(), $content['url']);
114 $this->assertCount(count($entry->getTags()), $content['tags']); 29 $this->assertCount(count($entry->getTags()), $content['tags']);
115 30
116 $this->assertTrue( 31 $this->assertTrue(
117 $client->getResponse()->headers->contains( 32 $this->client->getResponse()->headers->contains(
118 'Content-Type', 33 'Content-Type',
119 'application/json' 34 'application/json'
120 ) 35 )
@@ -123,10 +38,7 @@ class WallabagRestControllerTest extends WebTestCase
123 38
124 public function testGetOneEntryWrongUser() 39 public function testGetOneEntryWrongUser()
125 { 40 {
126 $client = $this->createClient(); 41 $entry = $this->client->getContainer()
127 $headers = $this->generateHeaders('admin', 'mypassword');
128
129 $entry = $client->getContainer()
130 ->get('doctrine.orm.entity_manager') 42 ->get('doctrine.orm.entity_manager')
131 ->getRepository('WallabagCoreBundle:Entry') 43 ->getRepository('WallabagCoreBundle:Entry')
132 ->findOneBy(array('user' => 2, 'isArchived' => false)); 44 ->findOneBy(array('user' => 2, 'isArchived' => false));
@@ -135,21 +47,18 @@ class WallabagRestControllerTest extends WebTestCase
135 $this->markTestSkipped('No content found in db.'); 47 $this->markTestSkipped('No content found in db.');
136 } 48 }
137 49
138 $client->request('GET', '/api/entries/'.$entry->getId().'.json', array(), array(), $headers); 50 $this->client->request('GET', '/api/entries/'.$entry->getId().'.json');
139 51
140 $this->assertEquals(403, $client->getResponse()->getStatusCode()); 52 $this->assertEquals(403, $this->client->getResponse()->getStatusCode());
141 } 53 }
142 54
143 public function testGetEntries() 55 public function testGetEntries()
144 { 56 {
145 $client = $this->createClient(); 57 $this->client->request('GET', '/api/entries');
146 $headers = $this->generateHeaders('admin', 'mypassword');
147
148 $client->request('GET', '/api/entries', array(), array(), $headers);
149 58
150 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 59 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
151 60
152 $content = json_decode($client->getResponse()->getContent(), true); 61 $content = json_decode($this->client->getResponse()->getContent(), true);
153 62
154 $this->assertGreaterThanOrEqual(1, count($content)); 63 $this->assertGreaterThanOrEqual(1, count($content));
155 $this->assertNotEmpty($content['_embedded']['items']); 64 $this->assertNotEmpty($content['_embedded']['items']);
@@ -158,7 +67,7 @@ class WallabagRestControllerTest extends WebTestCase
158 $this->assertGreaterThanOrEqual(1, $content['pages']); 67 $this->assertGreaterThanOrEqual(1, $content['pages']);
159 68
160 $this->assertTrue( 69 $this->assertTrue(
161 $client->getResponse()->headers->contains( 70 $this->client->getResponse()->headers->contains(
162 'Content-Type', 71 'Content-Type',
163 'application/json' 72 'application/json'
164 ) 73 )
@@ -167,14 +76,11 @@ class WallabagRestControllerTest extends WebTestCase
167 76
168 public function testGetStarredEntries() 77 public function testGetStarredEntries()
169 { 78 {
170 $client = $this->createClient(); 79 $this->client->request('GET', '/api/entries', array('star' => 1, 'sort' => 'updated'));
171 $headers = $this->generateHeaders('admin', 'mypassword');
172 80
173 $client->request('GET', '/api/entries', array('star' => 1, 'sort' => 'updated'), array(), $headers); 81 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
174 82
175 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 83 $content = json_decode($this->client->getResponse()->getContent(), true);
176
177 $content = json_decode($client->getResponse()->getContent(), true);
178 84
179 $this->assertGreaterThanOrEqual(1, count($content)); 85 $this->assertGreaterThanOrEqual(1, count($content));
180 $this->assertNotEmpty($content['_embedded']['items']); 86 $this->assertNotEmpty($content['_embedded']['items']);
@@ -183,7 +89,7 @@ class WallabagRestControllerTest extends WebTestCase
183 $this->assertGreaterThanOrEqual(1, $content['pages']); 89 $this->assertGreaterThanOrEqual(1, $content['pages']);
184 90
185 $this->assertTrue( 91 $this->assertTrue(
186 $client->getResponse()->headers->contains( 92 $this->client->getResponse()->headers->contains(
187 'Content-Type', 93 'Content-Type',
188 'application/json' 94 'application/json'
189 ) 95 )
@@ -192,14 +98,11 @@ class WallabagRestControllerTest extends WebTestCase
192 98
193 public function testGetArchiveEntries() 99 public function testGetArchiveEntries()
194 { 100 {
195 $client = $this->createClient(); 101 $this->client->request('GET', '/api/entries', array('archive' => 1));
196 $headers = $this->generateHeaders('admin', 'mypassword');
197
198 $client->request('GET', '/api/entries', array('archive' => 1), array(), $headers);
199 102
200 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 103 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
201 104
202 $content = json_decode($client->getResponse()->getContent(), true); 105 $content = json_decode($this->client->getResponse()->getContent(), true);
203 106
204 $this->assertGreaterThanOrEqual(1, count($content)); 107 $this->assertGreaterThanOrEqual(1, count($content));
205 $this->assertNotEmpty($content['_embedded']['items']); 108 $this->assertNotEmpty($content['_embedded']['items']);
@@ -208,7 +111,7 @@ class WallabagRestControllerTest extends WebTestCase
208 $this->assertGreaterThanOrEqual(1, $content['pages']); 111 $this->assertGreaterThanOrEqual(1, $content['pages']);
209 112
210 $this->assertTrue( 113 $this->assertTrue(
211 $client->getResponse()->headers->contains( 114 $this->client->getResponse()->headers->contains(
212 'Content-Type', 115 'Content-Type',
213 'application/json' 116 'application/json'
214 ) 117 )
@@ -217,10 +120,7 @@ class WallabagRestControllerTest extends WebTestCase
217 120
218 public function testDeleteEntry() 121 public function testDeleteEntry()
219 { 122 {
220 $client = $this->createClient(); 123 $entry = $this->client->getContainer()
221 $headers = $this->generateHeaders('admin', 'mypassword');
222
223 $entry = $client->getContainer()
224 ->get('doctrine.orm.entity_manager') 124 ->get('doctrine.orm.entity_manager')
225 ->getRepository('WallabagCoreBundle:Entry') 125 ->getRepository('WallabagCoreBundle:Entry')
226 ->findOneByUser(1); 126 ->findOneByUser(1);
@@ -229,36 +129,31 @@ class WallabagRestControllerTest extends WebTestCase
229 $this->markTestSkipped('No content found in db.'); 129 $this->markTestSkipped('No content found in db.');
230 } 130 }
231 131
232 $client->request('DELETE', '/api/entries/'.$entry->getId().'.json', array(), array(), $headers); 132 $this->client->request('DELETE', '/api/entries/'.$entry->getId().'.json');
233 133
234 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 134 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
235 135
236 $content = json_decode($client->getResponse()->getContent(), true); 136 $content = json_decode($this->client->getResponse()->getContent(), true);
237 137
238 $this->assertEquals($entry->getTitle(), $content['title']); 138 $this->assertEquals($entry->getTitle(), $content['title']);
239 $this->assertEquals($entry->getUrl(), $content['url']); 139 $this->assertEquals($entry->getUrl(), $content['url']);
240 140
241 // We'll try to delete this entry again 141 // We'll try to delete this entry again
242 $headers = $this->generateHeaders('admin', 'mypassword'); 142 $this->client->request('DELETE', '/api/entries/'.$entry->getId().'.json');
243
244 $client->request('DELETE', '/api/entries/'.$entry->getId().'.json', array(), array(), $headers);
245 143
246 $this->assertEquals(404, $client->getResponse()->getStatusCode()); 144 $this->assertEquals(404, $this->client->getResponse()->getStatusCode());
247 } 145 }
248 146
249 public function testPostEntry() 147 public function testPostEntry()
250 { 148 {
251 $client = $this->createClient(); 149 $this->client->request('POST', '/api/entries.json', array(
252 $headers = $this->generateHeaders('admin', 'mypassword');
253
254 $client->request('POST', '/api/entries.json', array(
255 'url' => 'http://www.lemonde.fr/pixels/article/2015/03/28/plongee-dans-l-univers-d-ingress-le-jeu-de-google-aux-frontieres-du-reel_4601155_4408996.html', 150 'url' => 'http://www.lemonde.fr/pixels/article/2015/03/28/plongee-dans-l-univers-d-ingress-le-jeu-de-google-aux-frontieres-du-reel_4601155_4408996.html',
256 'tags' => 'google', 151 'tags' => 'google',
257 ), array(), $headers); 152 ));
258 153
259 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 154 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
260 155
261 $content = json_decode($client->getResponse()->getContent(), true); 156 $content = json_decode($this->client->getResponse()->getContent(), true);
262 157
263 $this->assertGreaterThan(0, $content['id']); 158 $this->assertGreaterThan(0, $content['id']);
264 $this->assertEquals('http://www.lemonde.fr/pixels/article/2015/03/28/plongee-dans-l-univers-d-ingress-le-jeu-de-google-aux-frontieres-du-reel_4601155_4408996.html', $content['url']); 159 $this->assertEquals('http://www.lemonde.fr/pixels/article/2015/03/28/plongee-dans-l-univers-d-ingress-le-jeu-de-google-aux-frontieres-du-reel_4601155_4408996.html', $content['url']);
@@ -269,10 +164,7 @@ class WallabagRestControllerTest extends WebTestCase
269 164
270 public function testPatchEntry() 165 public function testPatchEntry()
271 { 166 {
272 $client = $this->createClient(); 167 $entry = $this->client->getContainer()
273 $headers = $this->generateHeaders('admin', 'mypassword');
274
275 $entry = $client->getContainer()
276 ->get('doctrine.orm.entity_manager') 168 ->get('doctrine.orm.entity_manager')
277 ->getRepository('WallabagCoreBundle:Entry') 169 ->getRepository('WallabagCoreBundle:Entry')
278 ->findOneByUser(1); 170 ->findOneByUser(1);
@@ -284,16 +176,16 @@ class WallabagRestControllerTest extends WebTestCase
284 // hydrate the tags relations 176 // hydrate the tags relations
285 $nbTags = count($entry->getTags()); 177 $nbTags = count($entry->getTags());
286 178
287 $client->request('PATCH', '/api/entries/'.$entry->getId().'.json', array( 179 $this->client->request('PATCH', '/api/entries/'.$entry->getId().'.json', array(
288 'title' => 'New awesome title', 180 'title' => 'New awesome title',
289 'tags' => 'new tag '.uniqid(), 181 'tags' => 'new tag '.uniqid(),
290 'star' => true, 182 'star' => true,
291 'archive' => false, 183 'archive' => false,
292 ), array(), $headers); 184 ));
293 185
294 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 186 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
295 187
296 $content = json_decode($client->getResponse()->getContent(), true); 188 $content = json_decode($this->client->getResponse()->getContent(), true);
297 189
298 $this->assertEquals($entry->getId(), $content['id']); 190 $this->assertEquals($entry->getId(), $content['id']);
299 $this->assertEquals($entry->getUrl(), $content['url']); 191 $this->assertEquals($entry->getUrl(), $content['url']);
@@ -303,10 +195,7 @@ class WallabagRestControllerTest extends WebTestCase
303 195
304 public function testGetTagsEntry() 196 public function testGetTagsEntry()
305 { 197 {
306 $client = $this->createClient(); 198 $entry = $this->client->getContainer()
307 $headers = $this->generateHeaders('admin', 'mypassword');
308
309 $entry = $client->getContainer()
310 ->get('doctrine.orm.entity_manager') 199 ->get('doctrine.orm.entity_manager')
311 ->getRepository('WallabagCoreBundle:Entry') 200 ->getRepository('WallabagCoreBundle:Entry')
312 ->findOneWithTags(1); 201 ->findOneWithTags(1);
@@ -322,17 +211,14 @@ class WallabagRestControllerTest extends WebTestCase
322 $tags[] = array('id' => $tag->getId(), 'label' => $tag->getLabel()); 211 $tags[] = array('id' => $tag->getId(), 'label' => $tag->getLabel());
323 } 212 }
324 213
325 $client->request('GET', '/api/entries/'.$entry->getId().'/tags', array(), array(), $headers); 214 $this->client->request('GET', '/api/entries/'.$entry->getId().'/tags');
326 215
327 $this->assertEquals(json_encode($tags, JSON_HEX_QUOT), $client->getResponse()->getContent()); 216 $this->assertEquals(json_encode($tags, JSON_HEX_QUOT), $this->client->getResponse()->getContent());
328 } 217 }
329 218
330 public function testPostTagsOnEntry() 219 public function testPostTagsOnEntry()
331 { 220 {
332 $client = $this->createClient(); 221 $entry = $this->client->getContainer()
333 $headers = $this->generateHeaders('admin', 'mypassword');
334
335 $entry = $client->getContainer()
336 ->get('doctrine.orm.entity_manager') 222 ->get('doctrine.orm.entity_manager')
337 ->getRepository('WallabagCoreBundle:Entry') 223 ->getRepository('WallabagCoreBundle:Entry')
338 ->findOneByUser(1); 224 ->findOneByUser(1);
@@ -345,16 +231,16 @@ class WallabagRestControllerTest extends WebTestCase
345 231
346 $newTags = 'tag1,tag2,tag3'; 232 $newTags = 'tag1,tag2,tag3';
347 233
348 $client->request('POST', '/api/entries/'.$entry->getId().'/tags', array('tags' => $newTags), array(), $headers); 234 $this->client->request('POST', '/api/entries/'.$entry->getId().'/tags', array('tags' => $newTags));
349 235
350 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 236 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
351 237
352 $content = json_decode($client->getResponse()->getContent(), true); 238 $content = json_decode($this->client->getResponse()->getContent(), true);
353 239
354 $this->assertArrayHasKey('tags', $content); 240 $this->assertArrayHasKey('tags', $content);
355 $this->assertEquals($nbTags + 3, count($content['tags'])); 241 $this->assertEquals($nbTags + 3, count($content['tags']));
356 242
357 $entryDB = $client->getContainer() 243 $entryDB = $this->client->getContainer()
358 ->get('doctrine.orm.entity_manager') 244 ->get('doctrine.orm.entity_manager')
359 ->getRepository('WallabagCoreBundle:Entry') 245 ->getRepository('WallabagCoreBundle:Entry')
360 ->find($entry->getId()); 246 ->find($entry->getId());
@@ -369,15 +255,13 @@ class WallabagRestControllerTest extends WebTestCase
369 } 255 }
370 } 256 }
371 257
372 public function testDeleteOneTagEntrie() 258 public function testDeleteOneTagEntry()
373 { 259 {
374 $client = $this->createClient(); 260 $entry = $this->client->getContainer()
375 $headers = $this->generateHeaders('admin', 'mypassword');
376
377 $entry = $client->getContainer()
378 ->get('doctrine.orm.entity_manager') 261 ->get('doctrine.orm.entity_manager')
379 ->getRepository('WallabagCoreBundle:Entry') 262 ->getRepository('WallabagCoreBundle:Entry')
380 ->findOneByUser(1); 263 ->findOneWithTags(1);
264 $entry = $entry[0];
381 265
382 if (!$entry) { 266 if (!$entry) {
383 $this->markTestSkipped('No content found in db.'); 267 $this->markTestSkipped('No content found in db.');
@@ -387,11 +271,11 @@ class WallabagRestControllerTest extends WebTestCase
387 $nbTags = count($entry->getTags()); 271 $nbTags = count($entry->getTags());
388 $tag = $entry->getTags()[0]; 272 $tag = $entry->getTags()[0];
389 273
390 $client->request('DELETE', '/api/entries/'.$entry->getId().'/tags/'.$tag->getId().'.json', array(), array(), $headers); 274 $this->client->request('DELETE', '/api/entries/'.$entry->getId().'/tags/'.$tag->getId().'.json');
391 275
392 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 276 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
393 277
394 $content = json_decode($client->getResponse()->getContent(), true); 278 $content = json_decode($this->client->getResponse()->getContent(), true);
395 279
396 $this->assertArrayHasKey('tags', $content); 280 $this->assertArrayHasKey('tags', $content);
397 $this->assertEquals($nbTags - 1, count($content['tags'])); 281 $this->assertEquals($nbTags - 1, count($content['tags']));
@@ -399,14 +283,11 @@ class WallabagRestControllerTest extends WebTestCase
399 283
400 public function testGetUserTags() 284 public function testGetUserTags()
401 { 285 {
402 $client = $this->createClient(); 286 $this->client->request('GET', '/api/tags.json');
403 $headers = $this->generateHeaders('admin', 'mypassword');
404
405 $client->request('GET', '/api/tags.json', array(), array(), $headers);
406 287
407 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 288 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
408 289
409 $content = json_decode($client->getResponse()->getContent(), true); 290 $content = json_decode($this->client->getResponse()->getContent(), true);
410 291
411 $this->assertGreaterThan(0, $content); 292 $this->assertGreaterThan(0, $content);
412 $this->assertArrayHasKey('id', $content[0]); 293 $this->assertArrayHasKey('id', $content[0]);
@@ -420,14 +301,11 @@ class WallabagRestControllerTest extends WebTestCase
420 */ 301 */
421 public function testDeleteUserTag($tag) 302 public function testDeleteUserTag($tag)
422 { 303 {
423 $client = $this->createClient(); 304 $this->client->request('DELETE', '/api/tags/'.$tag['id'].'.json');
424 $headers = $this->generateHeaders('admin', 'mypassword');
425
426 $client->request('DELETE', '/api/tags/'.$tag['id'].'.json', array(), array(), $headers);
427 305
428 $this->assertEquals(200, $client->getResponse()->getStatusCode()); 306 $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
429 307
430 $content = json_decode($client->getResponse()->getContent(), true); 308 $content = json_decode($this->client->getResponse()->getContent(), true);
431 309
432 $this->assertArrayHasKey('label', $content); 310 $this->assertArrayHasKey('label', $content);
433 $this->assertEquals($tag['label'], $content['label']); 311 $this->assertEquals($tag['label'], $content['label']);
diff --git a/src/Wallabag/ApiBundle/WallabagApiBundle.php b/src/Wallabag/ApiBundle/WallabagApiBundle.php
index 2484f277..19d887ab 100644
--- a/src/Wallabag/ApiBundle/WallabagApiBundle.php
+++ b/src/Wallabag/ApiBundle/WallabagApiBundle.php
@@ -3,16 +3,7 @@
3namespace Wallabag\ApiBundle; 3namespace Wallabag\ApiBundle;
4 4
5use Symfony\Component\HttpKernel\Bundle\Bundle; 5use Symfony\Component\HttpKernel\Bundle\Bundle;
6use Wallabag\ApiBundle\DependencyInjection\Security\Factory\WsseFactory;
7use Symfony\Component\DependencyInjection\ContainerBuilder;
8 6
9class WallabagApiBundle extends Bundle 7class WallabagApiBundle extends Bundle
10{ 8{
11 public function build(ContainerBuilder $container)
12 {
13 parent::build($container);
14
15 $extension = $container->getExtension('security');
16 $extension->addSecurityListenerFactory(new WsseFactory());
17 }
18} 9}