Skip to content

Commit

Permalink
The error message is not user-friendly when adding duplicate role.
Browse files Browse the repository at this point in the history
  • Loading branch information
DirtyBit committed Nov 24, 2024
1 parent 2a0dafa commit 7809764
Showing 1 changed file with 23 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import com.alibaba.nacos.plugin.auth.impl.persistence.RolePersistService;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl;
import com.sun.istack.internal.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -235,6 +236,12 @@ public void addRole(String role, String username) {
throw new IllegalArgumentException(
"role '" + AuthConstants.GLOBAL_ADMIN_ROLE + "' is not permitted to create!");
}

if (hasRoleWithUsername(role, username)) {
throw new IllegalArgumentException(
"user '" + username + "' already bound to the role '" + role + "' !");
}

rolePersistService.addRole(role, username);
roleSet.add(role);
}
Expand Down Expand Up @@ -370,5 +377,21 @@ public boolean hasGlobalAdminRole() {
authConfigs.setHasGlobalAdminRole(hasGlobalAdminRole);
return hasGlobalAdminRole;
}

/**
* check if the user is already bound to the role.
*
* @return true if the user is already bound to the role.
*/
public boolean hasRoleWithUsername(@NotNull String role, @NotNull String username) {
Page<RoleInfo> roleInfoPage = rolePersistService.getRolesByUserNameAndRoleName(username,
role, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
if (roleInfoPage == null) {
return false;
}
List<RoleInfo> roleInfos = roleInfoPage.getPageItems();
return CollectionUtils.isNotEmpty(roleInfos) && roleInfos.stream()
.anyMatch(roleInfo -> role.equals(roleInfo.getRole()));
}

}

0 comments on commit 7809764

Please sign in to comment.