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

[type: security]fix shenyu-admin: add dashboard user permission #2357

Merged
merged 9 commits into from
Nov 16, 2021
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.apache.shenyu.admin.service.DashboardUserService;
import org.apache.shenyu.admin.utils.AesUtils;
import org.apache.shenyu.admin.utils.ShenyuResultMessage;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
Expand Down Expand Up @@ -70,14 +71,15 @@ public DashboardUserController(final SecretProperties secretProperties, final Da
* @param pageSize page size
* @return {@linkplain ShenyuAdminResult}
*/
@RequiresPermissions("system:manager:list")
@GetMapping("")
public ShenyuAdminResult queryDashboardUsers(final String userName, final Integer currentPage, final Integer pageSize) {
String key = secretProperties.getKey();
String iv = secretProperties.getIv();
CommonPager<DashboardUserVO> commonPager = dashboardUserService.listByPage(new DashboardUserQuery(userName, new PageParameter(currentPage, pageSize)));
public ShenyuAdminResult queryDashboardUsers(final String userName,
final Integer currentPage,
final Integer pageSize) {
CommonPager<DashboardUserVO> commonPager = dashboardUserService.listByPage(new DashboardUserQuery(userName,
new PageParameter(currentPage, pageSize)));

if (CollectionUtils.isNotEmpty(commonPager.getDataList())) {
commonPager.getDataList()
.forEach(item -> item.setPassword(AesUtils.aesDecryption(item.getPassword(), key, iv)));
return ShenyuAdminResult.success(ShenyuResultMessage.QUERY_SUCCESS, commonPager);
} else {
return ShenyuAdminResult.error(ShenyuResultMessage.DASHBOARD_QUERY_ERROR);
Expand All @@ -90,13 +92,13 @@ public ShenyuAdminResult queryDashboardUsers(final String userName, final Intege
* @param id dashboard user id.
* @return {@linkplain ShenyuAdminResult}
*/
@RequiresPermissions("system:manager:list")
@GetMapping("/{id}")
public ShenyuAdminResult detailDashboardUser(@PathVariable("id") final String id) {
DashboardUserEditVO dashboardUserEditVO = dashboardUserService.findById(id);
return Optional.ofNullable(dashboardUserEditVO).map(item -> {
item.setPassword("");
return ShenyuAdminResult.success(ShenyuResultMessage.DETAIL_SUCCESS, item);
}).orElseGet(() -> ShenyuAdminResult.error(ShenyuResultMessage.DASHBOARD_QUERY_ERROR));
return Optional.ofNullable(dashboardUserEditVO)
.map(item -> ShenyuAdminResult.success(ShenyuResultMessage.DETAIL_SUCCESS, item))
.orElseGet(() -> ShenyuAdminResult.error(ShenyuResultMessage.DASHBOARD_QUERY_ERROR));
}

/**
Expand All @@ -105,6 +107,7 @@ public ShenyuAdminResult detailDashboardUser(@PathVariable("id") final String id
* @param dashboardUserDTO dashboard user.
* @return {@linkplain ShenyuAdminResult}
*/
@RequiresPermissions("system:manager:add")
@PostMapping("")
public ShenyuAdminResult createDashboardUser(@Valid @RequestBody final DashboardUserDTO dashboardUserDTO) {
String key = secretProperties.getKey();
Expand All @@ -123,6 +126,7 @@ public ShenyuAdminResult createDashboardUser(@Valid @RequestBody final Dashboard
* @param dashboardUserDTO dashboard user.
* @return {@linkplain ShenyuAdminResult}
*/
@RequiresPermissions("system:manager:edit")
@PutMapping("/{id}")
public ShenyuAdminResult updateDashboardUser(@PathVariable("id") final String id, @Valid @RequestBody final DashboardUserDTO dashboardUserDTO) {
String key = secretProperties.getKey();
Expand All @@ -139,6 +143,7 @@ public ShenyuAdminResult updateDashboardUser(@PathVariable("id") final String id
* @param ids primary key.
* @return {@linkplain ShenyuAdminResult}
*/
@RequiresPermissions("system:manager:delete")
@DeleteMapping("/batch")
public ShenyuAdminResult deleteDashboardUser(@RequestBody @NotEmpty final List<@NotBlank String> ids) {
Integer deleteCount = dashboardUserService.delete(ids);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.apache.shenyu.admin.model.vo;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.shenyu.admin.model.entity.DashboardUserDO;
import org.apache.shenyu.common.utils.DateUtils;

Expand Down Expand Up @@ -44,6 +45,7 @@ public class DashboardUserVO implements Serializable {
/**
* user password.
*/
@JsonIgnore
private String password;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ public ShenyuAdminResult updateDetail(final AppAuthDTO appAuthDTO) {
List<AuthParamDTO> authParamDTOList = appAuthDTO.getAuthParamDTOList();
if (CollectionUtils.isNotEmpty(authParamDTOList)) {
authParamMapper.deleteByAuthId(appAuthDTO.getId());

List<AuthParamDO> authParamDOList = authParamDTOList.stream()
.map(dto -> AuthParamDO.create(appAuthDTO.getId(), dto.getAppName(), dto.getAppParam()))
.collect(Collectors.toList());
Expand All @@ -179,13 +180,16 @@ public ShenyuAdminResult updateDetail(final AppAuthDTO appAuthDTO) {
List<AuthPathDO> oldAuthPathDOList = authPathMapper.findByAuthId(appAuthDTO.getId());
String appName = oldAuthPathDOList.stream().findFirst()
.map(AuthPathDO::getAppName).orElse(StringUtils.EMPTY);

authPathMapper.deleteByAuthId(appAuthDTO.getId());

List<AuthPathDO> authPathDOList = authPathDTOList.stream()
.filter(Objects::nonNull)
.map(dto -> AuthPathDO.create(dto.getPath(), appAuthDTO.getId(), appName))
.collect(Collectors.toList());
authPathMapper.batchSave(authPathDOList);
}

AppAuthData appAuthData = buildByEntity(appAuthDO);
eventPublisher.publishEvent(new DataChangedEvent(ConfigGroupEnum.APP_AUTH,
DataEventTypeEnum.UPDATE,
Expand All @@ -202,6 +206,7 @@ public ShenyuAdminResult updateDetailPath(final AuthPathWarpDTO authPathWarpDTO)
List<AuthPathDTO> authPathDTOList = authPathWarpDTO.getAuthPathDTOList();
if (CollectionUtils.isNotEmpty(authPathDTOList)) {
authPathMapper.deleteByAuthId(authPathWarpDTO.getId());

List<AuthPathDO> collect = authPathDTOList.stream()
.filter(Objects::nonNull)
.map(authPathDTO -> AuthPathDO.create(authPathDTO.getPath(), appAuthDO.getId(), authPathDTO.getAppName()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,15 @@ public int createOrUpdate(final DashboardUserDTO dashboardUserDTO) {
bindUserRole(dashboardUserDO.getId(), dashboardUserDTO.getRoles());
return dashboardUserMapper.insertSelective(dashboardUserDO);
}

if (!AdminConstants.ADMIN_NAME.equals(dashboardUserDTO.getUserName())) {
userRoleMapper.deleteByUserId(dashboardUserDTO.getId());
}

if (CollectionUtils.isNotEmpty(dashboardUserDTO.getRoles())) {
bindUserRole(dashboardUserDTO.getId(), dashboardUserDTO.getRoles());
}

return dashboardUserMapper.updateSelective(dashboardUserDO);
}

Expand Down Expand Up @@ -213,9 +216,11 @@ public LoginDashboardUserVO login(final String userName, final String password)
if (Objects.nonNull(ldapTemplate)) {
dashboardUserVO = loginByLdap(userName, password);
}

if (Objects.isNull(dashboardUserVO)) {
dashboardUserVO = loginByDatabase(userName, password);
}

return LoginDashboardUserVO.buildLoginDashboardUserVO(dashboardUserVO)
.setToken(JwtUtils.generateToken(dashboardUserVO.getUserName(), dashboardUserVO.getPassword(),
jwtProperties.getExpiredSeconds()));
Expand Down Expand Up @@ -256,8 +261,7 @@ private DashboardUserVO loginByLdap(final String userName, final String password
private DashboardUserVO loginByDatabase(final String userName, final String password) {
String key = secretProperties.getKey();
String iv = secretProperties.getIv();
DashboardUserVO dashboardUserVO = findByQuery(userName, AesUtils.aesEncryption(password, key, iv));
return dashboardUserVO;
return findByQuery(userName, AesUtils.aesEncryption(password, key, iv));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,11 @@ public Map<String, List<EnumVO>> list() {
List<EnumVO> redisModeEnums = Arrays.stream(RedisModeEnum.values())
.map(redisModeEnum -> new EnumVO(null, redisModeEnum.getName(), true))
.collect(Collectors.toList());

List<EnumVO> hystrixIsolationModeEnums = Arrays.stream(HystrixIsolationModeEnum.values())
.map(hystrixIsolationModeEnum -> new EnumVO(hystrixIsolationModeEnum.getCode(), hystrixIsolationModeEnum.getName(), true))
.collect(Collectors.toList());

Map<String, List<EnumVO>> enums = Maps.newHashMap();
enums.put("httpMethodEnums", httpMethodEnums);
enums.put("loadBalanceEnums", loadBalanceEnums);
Expand All @@ -117,6 +119,7 @@ public Map<String, List<EnumVO>> list() {
enums.put("wafEnums", wafEnums);
enums.put("redisModeEnums", redisModeEnums);
enums.put("hystrixIsolationModeEnums", hystrixIsolationModeEnums);

return enums;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public String createOrUpdate(final MetaDataDTO metaDataDTO) {
}
MetaDataDO metaDataDO = MetaDataTransfer.INSTANCE.mapToEntity(metaDataDTO);
DataEventTypeEnum eventType;
String pathDesc = metaDataDO.getPathDesc() == null ? "" : metaDataDO.getPathDesc();
String pathDesc = Objects.isNull(metaDataDO.getPathDesc()) ? "" : metaDataDO.getPathDesc();
if (StringUtils.isEmpty(metaDataDTO.getId())) {
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
metaDataDO.setId(UUIDUtils.getInstance().generateShortUuid());
Expand Down Expand Up @@ -168,11 +168,10 @@ public MetaDataVO findById(final String id) {
@Override
@Pageable
public CommonPager<MetaDataVO> listByPage(final MetaDataQuery metaDataQuery) {
return PageResultUtils.result(metaDataQuery.getPageParameter(),
() -> metaDataMapper.selectByQuery(metaDataQuery)
.stream()
.map(MetaDataTransfer.INSTANCE::mapToVO)
.collect(Collectors.toList()));
return PageResultUtils.result(metaDataQuery.getPageParameter(), () -> metaDataMapper.selectByQuery(metaDataQuery)
.stream()
.map(MetaDataTransfer.INSTANCE::mapToVO)
.collect(Collectors.toList()));
}

@Override
Expand Down Expand Up @@ -216,10 +215,12 @@ private String checkData(final MetaDataDTO metaDataDTO) {
LOG.error("metaData create param is error, {}", metaDataDTO);
return AdminConstants.PARAMS_ERROR;
}

final MetaDataDO exist = metaDataMapper.findByPath(metaDataDTO.getPath());
if (exist != null && !exist.getId().equals(metaDataDTO.getId())) {
if (Objects.nonNull(exist) && !exist.getId().equals(metaDataDTO.getId())) {
return AdminConstants.DATA_PATH_IS_EXIST;
}

return StringUtils.EMPTY;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,21 +80,24 @@ public PermissionServiceImpl(final DashboardUserMapper dashboardUserMapper,
@Override
public PermissionMenuVO getPermissionMenu(final String token) {
UserInfo userInfo = JwtUtils.getUserInfo();
if (Objects.nonNull(userInfo)) {
List<ResourceVO> resourceVOList = getResourceListByUserName(userInfo.getUserName());
if (CollectionUtils.isNotEmpty(resourceVOList)) {
List<MenuInfo> menuInfoList = new ArrayList<>();
resourceService.getMenuInfo(menuInfoList, resourceVOList, null);
return new PermissionMenuVO(menuInfoList, getAuthPerm(resourceVOList), getAllAuthPerms());
}
if (Objects.isNull(userInfo)) {
return null;
}
return null;

List<ResourceVO> resourceVOList = getResourceListByUserName(userInfo.getUserName());
if (CollectionUtils.isEmpty(resourceVOList)) {
return null;
}

List<MenuInfo> menuInfoList = new ArrayList<>();
resourceService.getMenuInfo(menuInfoList, resourceVOList, null);
return new PermissionMenuVO(menuInfoList, getAuthPerm(resourceVOList), getAllAuthPerms());
}

/**
* get Auth perm by user name for shiro.
* get Auth perm by username for shiro.
*
* @param userName user name.
* @param userName username.
* @return {@linkplain Set}
*/
@Override
Expand All @@ -109,25 +112,28 @@ public Set<String> getAuthPermByUserName(final String userName) {
/**
* get resource by username.
*
* @param userName user name
* @param userName username
* @return {@linkplain List}
*/
private List<ResourceVO> getResourceListByUserName(final String userName) {
List<UserRoleDO> userRoleDOList = userRoleMapper.findByUserId(dashboardUserMapper.selectByUserName(userName).getId());
List<String> roleIds = userRoleDOList.stream().filter(Objects::nonNull)
.map(UserRoleDO::getRoleId)
.collect(Collectors.toList());

Set<String> resourceIds = permissionMapper.findByObjectIds(roleIds).stream()
.map(PermissionDO::getResourceId)
.filter(StringUtils::isNoneBlank)
.collect(Collectors.toSet());
if (CollectionUtils.isNotEmpty(resourceIds)) {
return new ArrayList<>(resourceIds).stream()
.map(resource -> ResourceVO.buildResourceVO(resourceMapper.selectById(resource)))
.filter(Objects::nonNull)
.collect(Collectors.toList());

if (CollectionUtils.isEmpty(resourceIds)) {
return Collections.emptyList();
}
return Collections.emptyList();

return new ArrayList<>(resourceIds).stream()
.map(resource -> ResourceVO.buildResourceVO(resourceMapper.selectById(resource)))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}

/**
Expand All @@ -150,7 +156,8 @@ private List<AuthPerm> getAuthPerm(final List<ResourceVO> resourceVOList) {
*/
private List<AuthPerm> getAllAuthPerms() {
return resourceMapper.selectAll().stream()
.filter(item -> item.getResourceType().equals(ResourceTypeConstants.MENU_TYPE_2))
.map(item -> AuthPerm.buildAuthPerm(ResourceVO.buildResourceVO(item))).collect(Collectors.toList());
.filter(item -> item.getResourceType().equals(ResourceTypeConstants.MENU_TYPE_2))
.map(item -> AuthPerm.buildAuthPerm(ResourceVO.buildResourceVO(item)))
.collect(Collectors.toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ public String createOrUpdate(final PluginDTO pluginDTO) {
if (StringUtils.isNoneBlank(msg)) {
return msg;
}

PluginDO pluginDO = PluginDO.buildPluginDO(pluginDTO);
DataEventTypeEnum eventType = DataEventTypeEnum.CREATE;
if (StringUtils.isBlank(pluginDTO.getId())) {
Expand All @@ -137,18 +138,21 @@ public String createOrUpdate(final PluginDTO pluginDTO) {
@Override
@Transactional(rollbackFor = Exception.class)
public String delete(final List<String> ids) {
// 1. select plugin id.
List<PluginDO> plugins = Optional.ofNullable(this.pluginMapper.selectByIds(ids))
.orElse(Collections.emptyList());
final List<String> pluginIds = plugins.stream()
.map(PluginDO::getId).collect(Collectors.toList());
if (CollectionUtils.isEmpty(pluginIds)) {
return AdminConstants.SYS_PLUGIN_ID_NOT_EXIST;
}
// delete plugins

// 2. delete plugins.
this.pluginMapper.deleteByIds(pluginIds);
// delete plugin handle
// 3. delete plugin handle.
this.pluginHandleMapper.deleteByPluginIds(pluginIds);
// all selectors

// 4. all selectors.
final List<String> selectorIds = Optional.ofNullable(this.selectorMapper.findByPluginIds(pluginIds))
.orElse(Collections.emptyList())
.stream().map(SelectorDO::getId).collect(Collectors.toList());
Expand All @@ -159,20 +163,25 @@ public String delete(final List<String> ids) {
this.selectorConditionMapper.deleteBySelectorIds(selectorIds);
// delete all rules
final List<String> ruleIds = Optional.ofNullable(this.ruleMapper.findBySelectorIds(selectorIds))
.orElse(Collections.emptyList()).stream().map(RuleDO::getId).collect(Collectors.toList());
.orElse(Collections.emptyList())
.stream()
.map(RuleDO::getId)
.collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(ruleIds)) {
this.ruleMapper.deleteByIds(ruleIds);
// delete all rule conditions
this.ruleConditionMapper.deleteByRuleIds(ruleIds);
}
}
// delete resource & permission

// 5. delete resource & permission.
final List<ResourceVO> resources = this.resourceService.listByTitles(plugins.stream()
.map(PluginDO::getName).collect(Collectors.toList()));
if (CollectionUtils.isNotEmpty(resources)) {
this.resourceService.delete(resources.stream().map(ResourceVO::getId).collect(Collectors.toList()));
}
// publish change event.

// 6. publish change event.
eventPublisher.publishEvent(new DataChangedEvent(ConfigGroupEnum.PLUGIN, DataEventTypeEnum.DELETE,
plugins.stream().map(PluginTransfer.INSTANCE::mapToData).collect(Collectors.toList())));
return StringUtils.EMPTY;
Expand All @@ -198,6 +207,7 @@ public String enabled(final List<String> ids, final Boolean enabled) {
pluginMapper.updateEnable(pluginDO);
plugins.add(pluginDO);
}

// publish change event.
if (CollectionUtils.isNotEmpty(plugins)) {
eventPublisher.publishEvent(new DataChangedEvent(ConfigGroupEnum.PLUGIN, DataEventTypeEnum.UPDATE,
Expand Down Expand Up @@ -248,7 +258,7 @@ public String selectIdByName(final String name) {
Objects.requireNonNull(pluginDO);
return pluginDO.getId();
}

/**
* Find by name plugin do.
*
Expand All @@ -259,7 +269,7 @@ public String selectIdByName(final String name) {
public PluginDO findByName(final String name) {
return pluginMapper.selectByName(name);
}

/**
* check plugin Data integrity.
*
Expand Down
Loading