diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImpl.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImpl.java index 7e6803d4b5..56fd401dc6 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImpl.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImpl.java @@ -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; @@ -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); } @@ -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 roleInfoPage = rolePersistService.getRolesByUserNameAndRoleName(username, + role, DEFAULT_PAGE_NO, Integer.MAX_VALUE); + if (roleInfoPage == null) { + return false; + } + List roleInfos = roleInfoPage.getPageItems(); + return CollectionUtils.isNotEmpty(roleInfos) && roleInfos.stream() + .anyMatch(roleInfo -> role.equals(roleInfo.getRole())); + } }