aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Wallabag/ApiBundle
diff options
context:
space:
mode:
authorNicolas LÅ“uillet <nicolas@loeuillet.org>2015-09-29 14:31:52 +0200
committerJeremy Benoist <jeremy.benoist@gmail.com>2015-10-03 13:30:43 +0200
commitfcb1fba5c2fdb12c9f4041bd334aaced6f302d91 (patch)
tree0f388190a3648127c06dd3b4b9b198d2505bb7a8 /src/Wallabag/ApiBundle
parent8a60bc4cc2b6b1cfb5d8beb7ddcafc51d89a64c9 (diff)
downloadwallabag-fcb1fba5c2fdb12c9f4041bd334aaced6f302d91.tar.gz
wallabag-fcb1fba5c2fdb12c9f4041bd334aaced6f302d91.tar.zst
wallabag-fcb1fba5c2fdb12c9f4041bd334aaced6f302d91.zip
* public registration
* remove WSSE implementation * add oAuth2 implementation
Diffstat (limited to 'src/Wallabag/ApiBundle')
-rw-r--r--src/Wallabag/ApiBundle/Controller/WallabagRestController.php51
-rw-r--r--src/Wallabag/ApiBundle/DependencyInjection/Security/Factory/WsseFactory.php40
-rw-r--r--src/Wallabag/ApiBundle/DependencyInjection/WallabagApiExtension.php3
-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, 235 insertions, 447 deletions
diff --git a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php
index 349229f3..284dbb25 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
@@ -39,31 +39,6 @@ class WallabagRestController extends Controller
39 } 39 }
40 40
41 /** 41 /**
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 {
54 $user = $this
55 ->getDoctrine()
56 ->getRepository('WallabagCoreBundle:User')
57 ->findOneByUsername($username);
58
59 if (is_null($user)) {
60 throw $this->createNotFoundException();
61 }
62
63 return array($user->getSalt() ?: null);
64 }
65
66 /**
67 * Retrieve all entries. It could be filtered by many options. 42 * Retrieve all entries. It could be filtered by many options.
68 * 43 *
69 * @ApiDoc( 44 * @ApiDoc(
@@ -122,7 +97,7 @@ class WallabagRestController extends Controller
122 */ 97 */
123 public function getEntryAction(Entry $entry) 98 public function getEntryAction(Entry $entry)
124 { 99 {
125 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 100 $this->validateUserAccess($entry->getUser()->getId());
126 101
127 $json = $this->get('serializer')->serialize($entry, 'json'); 102 $json = $this->get('serializer')->serialize($entry, 'json');
128 103
@@ -184,7 +159,7 @@ class WallabagRestController extends Controller
184 */ 159 */
185 public function patchEntriesAction(Entry $entry, Request $request) 160 public function patchEntriesAction(Entry $entry, Request $request)
186 { 161 {
187 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 162 $this->validateUserAccess($entry->getUser()->getId());
188 163
189 $title = $request->request->get('title'); 164 $title = $request->request->get('title');
190 $isArchived = $request->request->get('is_archived'); 165 $isArchived = $request->request->get('is_archived');
@@ -228,7 +203,7 @@ class WallabagRestController extends Controller
228 */ 203 */
229 public function deleteEntriesAction(Entry $entry) 204 public function deleteEntriesAction(Entry $entry)
230 { 205 {
231 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 206 $this->validateUserAccess($entry->getUser()->getId());
232 207
233 $em = $this->getDoctrine()->getManager(); 208 $em = $this->getDoctrine()->getManager();
234 $em->remove($entry); 209 $em->remove($entry);
@@ -250,7 +225,7 @@ class WallabagRestController extends Controller
250 */ 225 */
251 public function getEntriesTagsAction(Entry $entry) 226 public function getEntriesTagsAction(Entry $entry)
252 { 227 {
253 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 228 $this->validateUserAccess($entry->getUser()->getId());
254 229
255 $json = $this->get('serializer')->serialize($entry->getTags(), 'json'); 230 $json = $this->get('serializer')->serialize($entry->getTags(), 'json');
256 231
@@ -271,7 +246,7 @@ class WallabagRestController extends Controller
271 */ 246 */
272 public function postEntriesTagsAction(Request $request, Entry $entry) 247 public function postEntriesTagsAction(Request $request, Entry $entry)
273 { 248 {
274 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 249 $this->validateUserAccess($entry->getUser()->getId());
275 250
276 $tags = $request->request->get('tags', ''); 251 $tags = $request->request->get('tags', '');
277 if (!empty($tags)) { 252 if (!empty($tags)) {
@@ -299,7 +274,7 @@ class WallabagRestController extends Controller
299 */ 274 */
300 public function deleteEntriesTagsAction(Entry $entry, Tag $tag) 275 public function deleteEntriesTagsAction(Entry $entry, Tag $tag)
301 { 276 {
302 $this->validateUserAccess($entry->getUser()->getId(), $this->getUser()->getId()); 277 $this->validateUserAccess($entry->getUser()->getId());
303 278
304 $entry->removeTag($tag); 279 $entry->removeTag($tag);
305 $em = $this->getDoctrine()->getManager(); 280 $em = $this->getDoctrine()->getManager();
@@ -334,7 +309,7 @@ class WallabagRestController extends Controller
334 */ 309 */
335 public function deleteTagAction(Tag $tag) 310 public function deleteTagAction(Tag $tag)
336 { 311 {
337 $this->validateUserAccess($tag->getUser()->getId(), $this->getUser()->getId()); 312 $this->validateUserAccess($tag->getUser()->getId());
338 313
339 $em = $this->getDoctrine()->getManager(); 314 $em = $this->getDoctrine()->getManager();
340 $em->remove($tag); 315 $em->remove($tag);
@@ -350,12 +325,12 @@ class WallabagRestController extends Controller
350 * If not, throw exception. It means a user try to access information from an other user. 325 * If not, throw exception. It means a user try to access information from an other user.
351 * 326 *
352 * @param int $requestUserId User id from the requested source 327 * @param int $requestUserId User id from the requested source
353 * @param int $currentUserId User id from the retrieved source
354 */ 328 */
355 private function validateUserAccess($requestUserId, $currentUserId) 329 private function validateUserAccess($requestUserId)
356 { 330 {
357 if ($requestUserId != $currentUserId) { 331 $user = $this->get('security.context')->getToken()->getUser();
358 throw $this->createAccessDeniedException('Access forbidden. Entry user id: '.$requestUserId.', logged user id: '.$currentUserId); 332 if ($requestUserId != $user->getId()) {
333 throw $this->createAccessDeniedException('Access forbidden. Entry user id: '.$requestUserId.', logged user id: '.$user->getId());
359 } 334 }
360 } 335 }
361 336
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..a147e7ef 100644
--- a/src/Wallabag/ApiBundle/DependencyInjection/WallabagApiExtension.php
+++ b/src/Wallabag/ApiBundle/DependencyInjection/WallabagApiExtension.php
@@ -13,9 +13,6 @@ class WallabagApiExtension extends Extension
13 { 13 {
14 $configuration = new Configuration(); 14 $configuration = new Configuration();
15 $config = $this->processConfiguration($configuration, $configs); 15 $config = $this->processConfiguration($configuration, $configs);
16
17 $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
18 $loader->load('services.yml');
19 } 16 }
20 17
21 public function getAlias() 18 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..d6cf0af5
--- /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\CoreBundle\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..7873d97d
--- /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\CoreBundle\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..74c564b7
--- /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\CoreBundle\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}