TestApiAuthorization.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Tests\Feature;
  3. use App\Models\ApplicationApi;
  4. use Illuminate\Foundation\Testing\DatabaseTransactions;
  5. use Illuminate\Support\Str;
  6. use Tests\TestCase;
  7. class TestApiAuthorization extends TestCase
  8. {
  9. use DatabaseTransactions;
  10. /**
  11. * A basic feature test example.
  12. *
  13. * @dataProvider ApiRoutesThatRequireAuthorization
  14. *
  15. * @return void
  16. * @test
  17. */
  18. public function test_api_route_without_auth_headers(string $method, string $route)
  19. {
  20. $response = $this->withHeaders([
  21. 'Accept' => 'application/json',
  22. ])->{$method}($route);
  23. $response->assertStatus(403);
  24. $response->assertJson(['message' => 'Missing Authorization header']);
  25. }
  26. /**
  27. * A basic feature test example.
  28. *
  29. * @dataProvider ApiRoutesThatRequireAuthorization
  30. *
  31. * @return void
  32. */
  33. public function test_api_route_with_auth_headers_but_invalid_token(string $method, string $route)
  34. {
  35. $response = $this->withHeaders([
  36. 'Accept' => 'application/json',
  37. 'Authorization' => 'Bearer '.Str::random(48),
  38. ])->{$method}($route);
  39. $response->assertStatus(401);
  40. $response->assertJson(['message' => 'Invalid Authorization token']);
  41. }
  42. /**
  43. * A basic feature test example.
  44. *
  45. * @dataProvider ApiRoutesThatRequireAuthorization
  46. *
  47. * @return void
  48. */
  49. public function test_api_route_with_valid_auth_headers(string $method, string $route)
  50. {
  51. $applicationApi = ApplicationApi::factory()->create();
  52. $response = $this->withHeaders([
  53. 'Accept' => 'application/json',
  54. 'Authorization' => 'Bearer '.$applicationApi->token,
  55. ])->{$method}($route);
  56. $response->assertStatus(200);
  57. }
  58. public function ApiRoutesThatRequireAuthorization(): array
  59. {
  60. return [
  61. 'List Users' => [
  62. 'method' => 'get',
  63. 'route' => '/api/users',
  64. ],
  65. 'List Servers' => [
  66. 'method' => 'get',
  67. 'route' => '/api/servers',
  68. ],
  69. ];
  70. }
  71. }