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.
This commit is contained in:
songtianlun 2025-01-02 17:17:09 +08:00
parent ccd6b02a98
commit f110f26c0b
4 changed files with 8 additions and 1 deletions

View File

@ -18,7 +18,7 @@ class SessionsController < ApplicationController
end
def destroy
log_out
log_out if logged_in?
redirect_to root_url
end
end

View File

@ -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

View File

@ -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

View File

@ -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