AuthentificationTest.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. // tests/AuthenticationTest.php
  3. namespace App\Tests;
  4. use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
  5. use App\Entity\Access\Access;
  6. use App\Entity\Organization\Organization;
  7. use App\Entity\Person\Person;
  8. use Hautelook\AliceBundle\PhpUnit\ReloadDatabaseTrait;
  9. class AuthentificationTest extends ApiTestCase
  10. {
  11. use ReloadDatabaseTrait;
  12. public function testLogin(): void
  13. {
  14. $client = self::createClient();
  15. $container = self::getContainer();
  16. $organization = new Organization();
  17. $access = new Access();
  18. $user = new Person();
  19. $user->setUsername('foo');
  20. $user->setPassword(
  21. $container->get('security.user_password_hasher')->hashPassword($user, '$3CR3T')
  22. );
  23. $access->setPerson($user);
  24. $organization->addAccess($access);
  25. $manager = $container->get('doctrine')->getManager();
  26. $manager->persist($organization);
  27. $manager->flush();
  28. // retrieve a token
  29. $response = $client->request('POST', '/login_check', [
  30. 'headers' => ['Content-Type' => 'application/json'],
  31. 'json' => [
  32. 'username' => 'foo',
  33. 'password' => '$3CR3T',
  34. ],
  35. ]);
  36. $json = $response->toArray();
  37. self::assertResponseIsSuccessful();
  38. $this->assertArrayHasKey('token', $json);
  39. // test not authorized
  40. $client->request('GET', '/my_profile/1');
  41. self::assertResponseStatusCodeSame(401);
  42. // test authorized
  43. $client->request('GET', '/my_profile/1',
  44. [
  45. 'Content-Type' => 'application/ld+json',
  46. 'authorization' => sprintf('BEARER %s', $json['token']),
  47. 'x-accessid' => 1
  48. ]);
  49. self::assertResponseIsSuccessful();
  50. }
  51. }