Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve JdbcUserDetailsManager.userExists method #14649

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa

public static final String DEF_DELETE_USER_AUTHORITIES_SQL = "delete from authorities where username = ?";

public static final String DEF_USER_EXISTS_SQL = "select username from users where username = ?";
public static final String DEF_USER_EXISTS_SQL = "select count(*) from users where username = ?";

public static final String DEF_CHANGE_PASSWORD_SQL = "update users set password = ? where username = ?";

Expand Down Expand Up @@ -300,13 +300,18 @@ protected Authentication createNewAuthentication(Authentication currentAuth, Str

@Override
public boolean userExists(String username) {
List<String> users = getJdbcTemplate().queryForList(this.userExistsSql, new String[] { username },
String.class);
if (users.size() > 1) {
throw new IncorrectResultSizeDataAccessException("More than one user found with name '" + username + "'",
1);
@SuppressWarnings("ConstantConditions")
int usersCount = getJdbcTemplate().queryForObject(
this.userExistsSql,
Integer.class,
username
);
if (usersCount > 1) {
throw new IncorrectResultSizeDataAccessException(
"["+ usersCount + "] users found with name '" + username + "', expected 1", 1
);
}
return users.size() == 1;
return usersCount == 1;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,11 @@ public void userExistsReturnsFalseForNonExistentUsername() {
assertThat(this.manager.userExists("joe")).isFalse();
}

@Test
public void userExistsReturnsFalseForNullUsername() {
assertThat(this.manager.userExists(null)).isFalse();
}

@Test
public void userExistsReturnsTrueForExistingUsername() {
insertJoe();
Expand Down