From f110f26c0b278bb3141aeacecd604bbb8c41d8d8 Mon Sep 17 00:00:00 2001 From: songtianlun Date: Thu, 2 Jan 2025 17:17:09 +0800 Subject: [PATCH] fix: ensure user logout only if logged in - Update `destroy` action in `SessionsController` to log out only if the user is currently logged in. - Add a check in the `authenticated?` method of the `User` model to return false if `remember_digest` is nil. - Enhance integration tests to simulate logout in another browser session and verify that the logout link is not present after logging out. These changes improve the robustness of the session management by preventing unnecessary logout attempts and ensuring that authentication checks are more reliable. --- app/controllers/sessions_controller.rb | 2 +- app/models/user.rb | 1 + test/integration/users_login_test.rb | 2 ++ test/models/user_test.rb | 4 ++++ 4 files changed, 8 insertions(+), 1 deletion(-) diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 78d1c52..1fff20c 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -18,7 +18,7 @@ class SessionsController < ApplicationController end def destroy - log_out + log_out if logged_in? redirect_to root_url end end diff --git a/app/models/user.rb b/app/models/user.rb index cecb0dd..2e83727 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -38,6 +38,7 @@ class User < ApplicationRecord end def authenticated?(remember_token) + return false if remember_digest.nil? BCrypt::Password.new(remember_digest).is_password?(remember_token) end diff --git a/test/integration/users_login_test.rb b/test/integration/users_login_test.rb index 6d8176d..818f3e5 100644 --- a/test/integration/users_login_test.rb +++ b/test/integration/users_login_test.rb @@ -43,6 +43,8 @@ class UsersLoginTest < ActionDispatch::IntegrationTest delete logout_path assert_not is_logged_in? assert_redirected_to root_url + # 模拟在另一个浏览器中登出 + delete logout_path follow_redirect! # assert_select "a[href=?]", login_path assert_select "a[href=?]", logout_path, count: 0 diff --git a/test/models/user_test.rb b/test/models/user_test.rb index e1aee96..54014d5 100644 --- a/test/models/user_test.rb +++ b/test/models/user_test.rb @@ -73,4 +73,8 @@ class UserTest < ActiveSupport::TestCase @user.password = @user.password_confirmation = " " * 5 assert_not @user.valid? end + + test "authenticated? should return false for a user with nil digest" do + assert_not @user.authenticated?('') + end end