From a725684d17959c4750f3b441ff2e94ecde7793a1 Mon Sep 17 00:00:00 2001 From: Tim MacDonald Date: Thu, 9 May 2024 04:07:38 +1000 Subject: [PATCH] [1.x] Ensure logout route is authenticated (#536) * Ensure logout route is authenticated * Formatting * Remove unused user --- routes/routes.php | 1 + tests/AuthenticatedSessionControllerTest.php | 28 ++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/routes/routes.php b/routes/routes.php index 141be97b..6bc8e187 100644 --- a/routes/routes.php +++ b/routes/routes.php @@ -42,6 +42,7 @@ ])); Route::post(RoutePath::for('logout', '/logout'), [AuthenticatedSessionController::class, 'destroy']) + ->middleware([config('fortify.auth_middleware', 'auth').':'.config('fortify.guard')]) ->name('logout'); // Password Reset... diff --git a/tests/AuthenticatedSessionControllerTest.php b/tests/AuthenticatedSessionControllerTest.php index 9df58110..512bd8ba 100644 --- a/tests/AuthenticatedSessionControllerTest.php +++ b/tests/AuthenticatedSessionControllerTest.php @@ -2,6 +2,7 @@ namespace Laravel\Fortify\Tests; +use Illuminate\Auth\Events\Logout; use Illuminate\Cache\RateLimiter; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Foundation\Auth\User; @@ -404,6 +405,33 @@ public function test_case_insensitive_usernames_can_be_used() $response->assertRedirect('/home'); } + public function test_users_can_logout(): void + { + $user = TestAuthenticationSessionUser::forceCreate([ + 'name' => 'Taylor Otwell', + 'email' => 'taylor@laravel.com', + 'password' => bcrypt('secret'), + ]); + Event::fake([Logout::class]); + + $response = $this->actingAs($user)->post('/logout'); + + $response->assertRedirect(); + $this->assertGuest(); + Event::assertDispatched(fn (Logout $logout) => $logout->user->is($user)); + } + + public function test_must_be_authenticated_to_logout(): void + { + Event::fake([Logout::class]); + + $response = $this->post('/logout'); + + $response->assertRedirect(); + $this->assertGuest(); + Event::assertNotDispatched(Logout::class); + } + protected function defineEnvironment($app) { parent::defineEnvironment($app);