AuthenticateMiddlewareTest.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Tests\Feature\Http\Middlewares;
  3. use App\Http\Middleware\Authenticate;
  4. use App\Models\User;
  5. use App\Providers\AuthServiceProvider;
  6. use Illuminate\Support\Facades\App;
  7. use Illuminate\Support\Facades\Config;
  8. use PHPUnit\Framework\Attributes\CoversClass;
  9. use PHPUnit\Framework\Attributes\CoversMethod;
  10. use PHPUnit\Framework\Attributes\Test;
  11. use Tests\FeatureTestCase;
  12. #[CoversClass(Authenticate::class)]
  13. #[CoversMethod(AuthServiceProvider::class, 'boot')]
  14. class AuthenticateMiddlewareTest extends FeatureTestCase
  15. {
  16. private const USER_NAME = 'John';
  17. private const USER_EMAIL = 'john@example.com';
  18. #[Test]
  19. public function test_it_always_authenticates_with_reverse_proxy_guard()
  20. {
  21. Config::set('auth.auth_proxy_headers.user', 'HTTP_REMOTE_USER');
  22. $this->app['auth']->shouldUse('reverse-proxy-guard');
  23. $this->json('GET', '/api/v1/groups', [], ['HTTP_REMOTE_USER' => self::USER_NAME]);
  24. $this->assertAuthenticated('reverse-proxy-guard');
  25. }
  26. #[Test]
  27. public function test_it_does_not_authenticate_with_empty_header()
  28. {
  29. Config::set('auth.auth_proxy_headers.user', 'HTTP_REMOTE_USER');
  30. Config::set('auth.auth_proxy_headers.email', 'HTTP_REMOTE_EMAIL');
  31. $this->app['auth']->shouldUse('reverse-proxy-guard');
  32. $this->json('GET', '/api/v1/groups', [], [
  33. 'HTTP_REMOTE_USER' => '',
  34. 'HTTP_REMOTE_EMAIL' => '',
  35. ])->assertStatus(407);
  36. }
  37. #[Test]
  38. public function test_it_does_not_authenticate_with_missing_header()
  39. {
  40. $this->app['auth']->shouldUse('reverse-proxy-guard');
  41. $this->json('GET', '/api/v1/groups', [], [])
  42. ->assertStatus(407);
  43. }
  44. #[Test]
  45. public function test_it_overrides_locale_when_auth_is_successful()
  46. {
  47. Config::set('auth.auth_proxy_headers.user', 'HTTP_REMOTE_USER');
  48. Config::set('auth.auth_proxy_headers.email', 'HTTP_REMOTE_EMAIL');
  49. $this->app['auth']->shouldUse('reverse-proxy-guard');
  50. $lang = 'fr';
  51. $user = User::factory()->create([
  52. 'name' => self::USER_NAME,
  53. 'email' => self::USER_EMAIL,
  54. ]);
  55. $user['preferences->lang'] = $lang;
  56. $user->save();
  57. $this->json('GET', '/api/v1/groups', [], [
  58. 'HTTP_REMOTE_USER' => self::USER_NAME,
  59. ]);
  60. $this->assertEquals($lang, App::getLocale());
  61. }
  62. }