TestApiAuthorization.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. * @dataProvider ApiRoutesThatRequireAuthorization
  13. * @return void
  14. * @test
  15. */
  16. public function test_api_route_without_auth_headers(string $method, string $route)
  17. {
  18. $response = $this->withHeaders([
  19. 'Accept' => 'application/json',
  20. ])->{$method}($route);
  21. $response->assertStatus(403);
  22. $response->assertJson(['message' => 'Missing Authorization header']);
  23. }
  24. /**
  25. * A basic feature test example.
  26. * @dataProvider ApiRoutesThatRequireAuthorization
  27. * @return void
  28. */
  29. public function test_api_route_with_auth_headers_but_invalid_token(string $method, string $route)
  30. {
  31. $response = $this->withHeaders([
  32. 'Accept' => 'application/json',
  33. 'Authorization' => 'Bearer ' . Str::random(48)
  34. ])->{$method}($route);
  35. $response->assertStatus(401);
  36. $response->assertJson(['message' => 'Invalid Authorization token']);
  37. }
  38. /**
  39. * A basic feature test example.
  40. * @dataProvider ApiRoutesThatRequireAuthorization
  41. * @return void
  42. */
  43. public function test_api_route_with_valid_auth_headers(string $method, string $route)
  44. {
  45. $applicationApi = ApplicationApi::factory()->create();
  46. $response = $this->withHeaders([
  47. 'Accept' => 'application/json',
  48. 'Authorization' => 'Bearer ' . $applicationApi->token
  49. ])->{$method}($route);
  50. $response->assertStatus(200);
  51. }
  52. public function ApiRoutesThatRequireAuthorization(): array
  53. {
  54. return [
  55. 'List Users' => [
  56. 'method' => 'get',
  57. 'route' => '/api/users',
  58. ],
  59. 'List Servers' => [
  60. 'method' => 'get',
  61. 'route' => '/api/servers',
  62. ]
  63. ];
  64. }
  65. }