添加主机身份页面.

This commit is contained in:
lijiahang
2023-09-21 13:50:42 +08:00
parent fbc40116f0
commit b13cbd8cca
39 changed files with 444 additions and 649 deletions

View File

@@ -21,6 +21,8 @@ public interface ErrorMessage {
String DATA_ABSENT = "数据不存在"; String DATA_ABSENT = "数据不存在";
String KEY_ABSENT = "秘钥不存在";
String CONFIG_ABSENT = "配置不存在"; String CONFIG_ABSENT = "配置不存在";
String DATA_PRESENT = "数据已存在"; String DATA_PRESENT = "数据已存在";

View File

@@ -0,0 +1,40 @@
package com.orion.ops.framework.common.security;
import com.orion.lang.utils.Booleans;
import com.orion.lang.utils.Strings;
import com.orion.ops.framework.common.constant.Const;
import com.orion.ops.framework.common.utils.CryptoUtils;
/**
* 密码修改器
*
* @author Jiahang Li
* @version 1.0.0
* @since 2023/9/21 11:35
*/
public class PasswordModifier {
private PasswordModifier() {
}
/**
* 获取新密码
*
* @param action action
* @return password
*/
public static String getEncryptNewPassword(UpdatePasswordAction action) {
if (Booleans.isTrue(action.getUseNewPassword())) {
// 使用新密码
String password = action.getPassword();
if (Strings.isBlank(password)) {
return Const.EMPTY;
} else {
return CryptoUtils.encryptAsString(password);
}
} else {
return null;
}
}
}

View File

@@ -0,0 +1,28 @@
package com.orion.ops.framework.common.security;
import java.io.Serializable;
/**
* 更新密码操作
*
* @author Jiahang Li
* @version 1.0.0
* @since 2023/9/21 11:32
*/
public interface UpdatePasswordAction extends Serializable {
/**
* 是否使用新密码
*
* @return use
*/
Boolean getUseNewPassword();
/**
* 获取密码
*
* @return password
*/
String getPassword();
}

View File

@@ -31,24 +31,10 @@ Authorization: {{token}}
### 通过 id 批量查询主机身份 ### 通过 id 批量查询主机身份
GET {{baseUrl}}/asset/host-identity/list?idList=1,2,3 GET {{baseUrl}}/asset/host-identity/list
Authorization: {{token}} Authorization: {{token}}
### 查询主机身份
POST {{baseUrl}}/asset/host-identity/list-all
Content-Type: application/json
Authorization: {{token}}
{
"id": "",
"name": "",
"username": "",
"password": "",
"keyId": ""
}
### 分页查询主机身份 ### 分页查询主机身份
POST {{baseUrl}}/asset/host-identity/query POST {{baseUrl}}/asset/host-identity/query
Content-Type: application/json Content-Type: application/json
@@ -69,24 +55,3 @@ Authorization: {{token}}
DELETE {{baseUrl}}/asset/host-identity/delete?id=1 DELETE {{baseUrl}}/asset/host-identity/delete?id=1
Authorization: {{token}} Authorization: {{token}}
### 通过 id 批量删除主机身份
DELETE {{baseUrl}}/asset/host-identity/delete-batch?idList=1,2,3
Authorization: {{token}}
### 导出主机身份
POST {{baseUrl}}/asset/host-identity/export
Content-Type: application/json
Authorization: {{token}}
{
"id": "",
"name": "",
"username": "",
"password": "",
"keyId": ""
}
###

View File

@@ -5,11 +5,11 @@ import com.orion.ops.framework.common.annotation.IgnoreLog;
import com.orion.ops.framework.common.annotation.RestWrapper; import com.orion.ops.framework.common.annotation.RestWrapper;
import com.orion.ops.framework.common.constant.IgnoreLogMode; import com.orion.ops.framework.common.constant.IgnoreLogMode;
import com.orion.ops.framework.common.valid.group.Page; import com.orion.ops.framework.common.valid.group.Page;
import com.orion.ops.module.asset.service.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityCreateRequest;
import com.orion.ops.module.asset.entity.vo.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityQueryRequest;
import com.orion.ops.module.asset.entity.request.host.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityUpdateRequest;
import com.orion.ops.module.asset.entity.export.*; import com.orion.ops.module.asset.entity.vo.HostIdentityVO;
import com.orion.ops.module.asset.convert.*; import com.orion.ops.module.asset.service.HostIdentityService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@@ -19,8 +19,6 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List; import java.util.List;
/** /**
@@ -67,19 +65,11 @@ public class HostIdentityController {
@IgnoreLog(IgnoreLogMode.RET) @IgnoreLog(IgnoreLogMode.RET)
@GetMapping("/list") @GetMapping("/list")
@Operation(summary = "通过 id 批量查询主机身份") @Operation(summary = "查询主机身份")
@Parameter(name = "idList", description = "idList", required = true) @Parameter(name = "idList", description = "idList", required = true)
@PreAuthorize("@ss.hasPermission('asset:host-identity:query')") @PreAuthorize("@ss.hasPermission('asset:host-identity:query')")
public List<HostIdentityVO> getHostIdentityList(@RequestParam("idList") List<Long> idList) { public List<HostIdentityVO> getHostIdentityList() {
return hostIdentityService.getHostIdentityByIdList(idList); return hostIdentityService.getHostIdentityList();
}
@IgnoreLog(IgnoreLogMode.RET)
@PostMapping("/list-all")
@Operation(summary = "查询主机身份")
@PreAuthorize("@ss.hasPermission('asset:host-identity:query')")
public List<HostIdentityVO> getHostIdentityListAll(@Validated @RequestBody HostIdentityQueryRequest request) {
return hostIdentityService.getHostIdentityList(request);
} }
@IgnoreLog(IgnoreLogMode.RET) @IgnoreLog(IgnoreLogMode.RET)
@@ -98,21 +88,5 @@ public class HostIdentityController {
return hostIdentityService.deleteHostIdentityById(id); return hostIdentityService.deleteHostIdentityById(id);
} }
@DeleteMapping("/delete-batch")
@Operation(summary = "通过 id 批量删除主机身份")
@Parameter(name = "idList", description = "idList", required = true)
@PreAuthorize("@ss.hasPermission('asset:host-identity:delete')")
public Integer batchDeleteHostIdentity(@RequestParam("idList") List<Long> idList) {
return hostIdentityService.batchDeleteHostIdentityByIdList(idList);
}
@PostMapping("/export")
@Operation(summary = "导出主机身份")
@PreAuthorize("@ss.hasPermission('asset:host-identity:export')")
public void exportHostIdentity(@Validated @RequestBody HostIdentityQueryRequest request,
HttpServletResponse response) throws IOException {
hostIdentityService.exportHostIdentity(request, response);
}
} }

View File

@@ -30,7 +30,7 @@ GET {{baseUrl}}/asset/host-key/get?id=1
Authorization: {{token}} Authorization: {{token}}
### 查询主机秘钥 ### 查询主机秘钥
POST {{baseUrl}}/asset/host-key/list-all POST {{baseUrl}}/asset/host-key/list
Content-Type: application/json Content-Type: application/json
Authorization: {{token}} Authorization: {{token}}

View File

@@ -64,10 +64,10 @@ public class HostKeyController {
} }
@IgnoreLog(IgnoreLogMode.RET) @IgnoreLog(IgnoreLogMode.RET)
@PostMapping("/list-all") @PostMapping("/list")
@Operation(summary = "查询主机秘钥") @Operation(summary = "查询主机秘钥")
@PreAuthorize("@ss.hasPermission('asset:host-key:query')") @PreAuthorize("@ss.hasPermission('asset:host-key:query')")
public List<HostKeyVO> getHostKeyListAll() { public List<HostKeyVO> getHostKeyList() {
return hostKeyService.getHostKeyList(); return hostKeyService.getHostKeyList();
} }

View File

@@ -1,10 +1,11 @@
package com.orion.ops.module.asset.convert; package com.orion.ops.module.asset.convert;
import com.orion.ops.module.asset.entity.domain.*; import com.orion.ops.module.asset.entity.domain.HostIdentityDO;
import com.orion.ops.module.asset.entity.vo.*; import com.orion.ops.module.asset.entity.dto.HostIdentityCacheDTO;
import com.orion.ops.module.asset.entity.request.host.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityCreateRequest;
import com.orion.ops.module.asset.entity.export.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityQueryRequest;
import com.orion.ops.module.asset.convert.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityUpdateRequest;
import com.orion.ops.module.asset.entity.vo.HostIdentityVO;
import org.mapstruct.Mapper; import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers; import org.mapstruct.factory.Mappers;
@@ -30,7 +31,9 @@ public interface HostIdentityConvert {
HostIdentityVO to(HostIdentityDO domain); HostIdentityVO to(HostIdentityDO domain);
HostIdentityExport toExport(HostIdentityDO domain); HostIdentityVO to(HostIdentityCacheDTO cache);
HostIdentityCacheDTO toCache(HostIdentityDO domain);
List<HostIdentityVO> to(List<HostIdentityDO> list); List<HostIdentityVO> to(List<HostIdentityDO> list);

View File

@@ -1,6 +1,5 @@
package com.orion.ops.module.asset.dao; package com.orion.ops.module.asset.dao;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.ops.framework.mybatis.core.mapper.IMapper; import com.orion.ops.framework.mybatis.core.mapper.IMapper;
import com.orion.ops.module.asset.entity.domain.HostDO; import com.orion.ops.module.asset.entity.domain.HostDO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
@@ -15,18 +14,4 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper @Mapper
public interface HostDAO extends IMapper<HostDO> { public interface HostDAO extends IMapper<HostDO> {
/**
* 获取查询条件
*
* @param entity entity
* @return 查询条件
*/
default LambdaQueryWrapper<HostDO> queryCondition(HostDO entity) {
return this.wrapper()
.eq(HostDO::getId, entity.getId())
.eq(HostDO::getName, entity.getName())
.eq(HostDO::getCode, entity.getCode())
.eq(HostDO::getAddress, entity.getAddress());
}
} }

View File

@@ -1,9 +1,9 @@
package com.orion.ops.module.asset.dao; package com.orion.ops.module.asset.dao;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.ops.framework.mybatis.core.mapper.IMapper; import com.orion.ops.framework.mybatis.core.mapper.IMapper;
import com.orion.ops.module.asset.entity.domain.HostIdentityDO; import com.orion.ops.module.asset.entity.domain.HostIdentityDO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/** /**
* 主机身份 Mapper 接口 * 主机身份 Mapper 接口
@@ -16,18 +16,11 @@ import org.apache.ibatis.annotations.Mapper;
public interface HostIdentityDAO extends IMapper<HostIdentityDO> { public interface HostIdentityDAO extends IMapper<HostIdentityDO> {
/** /**
* 获取查询条件 * 设置 keyId 为 null
* *
* @param entity entity * @param keyId keyId
* @return 查询条件 * @return effect
*/ */
default LambdaQueryWrapper<HostIdentityDO> queryCondition(HostIdentityDO entity) { int setKeyWithNull(@Param("keyId") Long keyId);
return this.wrapper()
.eq(HostIdentityDO::getId, entity.getId())
.eq(HostIdentityDO::getName, entity.getName())
.eq(HostIdentityDO::getUsername, entity.getUsername())
.eq(HostIdentityDO::getPassword, entity.getPassword())
.eq(HostIdentityDO::getKeyId, entity.getKeyId());
}
} }

View File

@@ -1,6 +1,5 @@
package com.orion.ops.module.asset.dao; package com.orion.ops.module.asset.dao;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.ops.framework.mybatis.core.mapper.IMapper; import com.orion.ops.framework.mybatis.core.mapper.IMapper;
import com.orion.ops.module.asset.entity.domain.HostKeyDO; import com.orion.ops.module.asset.entity.domain.HostKeyDO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
@@ -15,19 +14,4 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper @Mapper
public interface HostKeyDAO extends IMapper<HostKeyDO> { public interface HostKeyDAO extends IMapper<HostKeyDO> {
/**
* 获取查询条件
*
* @param entity entity
* @return 查询条件
*/
default LambdaQueryWrapper<HostKeyDO> queryCondition(HostKeyDO entity) {
return this.wrapper()
.eq(HostKeyDO::getId, entity.getId())
.eq(HostKeyDO::getName, entity.getName())
.eq(HostKeyDO::getPublicKey, entity.getPublicKey())
.eq(HostKeyDO::getPrivateKey, entity.getPrivateKey())
.eq(HostKeyDO::getPassword, entity.getPassword());
}
} }

View File

@@ -2,6 +2,7 @@ package com.orion.ops.module.asset.define;
import com.orion.lang.define.cache.CacheKeyBuilder; import com.orion.lang.define.cache.CacheKeyBuilder;
import com.orion.lang.define.cache.CacheKeyDefine; import com.orion.lang.define.cache.CacheKeyDefine;
import com.orion.ops.module.asset.entity.dto.HostIdentityCacheDTO;
import com.orion.ops.module.asset.entity.dto.HostKeyCacheDTO; import com.orion.ops.module.asset.entity.dto.HostKeyCacheDTO;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -22,4 +23,11 @@ public interface HostCacheKeyDefine {
.timeout(3, TimeUnit.DAYS) .timeout(3, TimeUnit.DAYS)
.build(); .build();
CacheKeyDefine HOST_IDENTITY = new CacheKeyBuilder()
.key("host:identity:list")
.desc("主机身份列表")
.type(HostIdentityCacheDTO.class)
.timeout(3, TimeUnit.DAYS)
.build();
} }

View File

@@ -0,0 +1,31 @@
package com.orion.ops.module.asset.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 主机身份缓存
*
* @author Jiahang Li
* @version 1.0.0
* @since 2023/9/21 12:00
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(name = "HostIdentityCacheDTO", description = "主机身份缓存")
public class HostIdentityCacheDTO implements Serializable {
@Schema(description = "id")
private Long id;
@Schema(description = "名称")
private String name;
}

View File

@@ -1,67 +0,0 @@
package com.orion.ops.module.asset.entity.export;
import com.orion.lang.utils.time.Dates;
import com.orion.office.excel.annotation.ExportField;
import com.orion.office.excel.annotation.ExportSheet;
import com.orion.office.excel.annotation.ExportTitle;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import java.io.Serializable;
import java.util.*;
/**
* 主机身份 导出对象
*
* @author Jiahang Li
* @version 1.0.0
* @since 2023-9-20 11:55
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ExportTitle(title = HostIdentityExport.TITLE)
@ExportSheet(name = "主机身份", filterHeader = true, freezeHeader = true, indexToSort = true)
@Schema(name = "HostIdentityExport", description = "主机身份导出对象")
public class HostIdentityExport implements Serializable {
public static final String TITLE = "主机身份导出";
@Schema(description = "id")
@ExportField(index = 0, header = "id", width = 16)
private Long id;
@Schema(description = "名称")
@ExportField(index = 1, header = "名称", width = 16)
private String name;
@Schema(description = "用户名")
@ExportField(index = 2, header = "用户名", width = 16)
private String username;
@Schema(description = "用户密码")
@ExportField(index = 3, header = "用户密码", width = 16)
private String password;
@Schema(description = "秘钥id")
@ExportField(index = 4, header = "秘钥id", width = 16)
private Long keyId;
@ExportField(index = 5, header = "创建时间", width = 16, format = Dates.YMD_HMS)
@Schema(description = "创建时间")
private Date createTime;
@Schema(description = "修改时间")
@ExportField(index = 6, header = "修改时间", width = 16, format = Dates.YMD_HMS)
private Date updateTime;
@Schema(description = "创建人")
@ExportField(index = 7, header = "创建人", width = 16)
private String creator;
@Schema(description = "修改人")
@ExportField(index = 8, header = "修改人", width = 16)
private String updater;
}

View File

@@ -1,5 +1,6 @@
package com.orion.ops.module.asset.entity.request.host; package com.orion.ops.module.asset.entity.request.host;
import com.orion.ops.framework.common.security.UpdatePasswordAction;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
@@ -9,7 +10,6 @@ import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.io.Serializable;
/** /**
* 主机身份 更新请求对象 * 主机身份 更新请求对象
@@ -23,7 +23,7 @@ import java.io.Serializable;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Schema(name = "HostIdentityUpdateRequest", description = "主机身份 更新请求对象") @Schema(name = "HostIdentityUpdateRequest", description = "主机身份 更新请求对象")
public class HostIdentityUpdateRequest implements Serializable { public class HostIdentityUpdateRequest implements UpdatePasswordAction {
@NotNull @NotNull
@Schema(description = "id") @Schema(description = "id")
@@ -48,4 +48,7 @@ public class HostIdentityUpdateRequest implements Serializable {
@Schema(description = "秘钥id") @Schema(description = "秘钥id")
private Long keyId; private Long keyId;
@Schema(description = "是否使用新密码")
private Boolean useNewPassword;
} }

View File

@@ -1,5 +1,6 @@
package com.orion.ops.module.asset.entity.request.host; package com.orion.ops.module.asset.entity.request.host;
import com.orion.ops.framework.common.security.UpdatePasswordAction;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
@@ -9,7 +10,6 @@ import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.io.Serializable;
/** /**
* 主机秘钥 更新请求对象 * 主机秘钥 更新请求对象
@@ -23,7 +23,7 @@ import java.io.Serializable;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Schema(name = "HostKeyUpdateRequest", description = "主机秘钥 更新请求对象") @Schema(name = "HostKeyUpdateRequest", description = "主机秘钥 更新请求对象")
public class HostKeyUpdateRequest implements Serializable { public class HostKeyUpdateRequest implements UpdatePasswordAction {
@NotNull @NotNull
@Schema(description = "id") @Schema(description = "id")

View File

@@ -1,10 +1,13 @@
package com.orion.ops.module.asset.entity.vo; package com.orion.ops.module.asset.entity.vo;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*; import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable; import java.io.Serializable;
import java.util.*; import java.util.Date;
/** /**
* 主机身份 视图响应对象 * 主机身份 视图响应对象
@@ -31,22 +34,16 @@ public class HostIdentityVO implements Serializable {
@Schema(description = "用户名") @Schema(description = "用户名")
private String username; private String username;
@Schema(description = "用户密码")
private String password;
@Schema(description = "秘钥id") @Schema(description = "秘钥id")
private Long keyId; private Long keyId;
@Schema(description = "秘钥名称")
private String keyName;
@Schema(description = "创建时间") @Schema(description = "创建时间")
private Date createTime; private Date createTime;
@Schema(description = "修改时间") @Schema(description = "修改时间")
private Date updateTime; private Date updateTime;
@Schema(description = "创建人")
private String creator;
@Schema(description = "修改人")
private String updater;
} }

View File

@@ -1,13 +1,11 @@
package com.orion.ops.module.asset.service; package com.orion.ops.module.asset.service;
import com.orion.lang.define.wrapper.DataGrid; import com.orion.lang.define.wrapper.DataGrid;
import com.orion.ops.module.asset.entity.vo.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityCreateRequest;
import com.orion.ops.module.asset.entity.request.host.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityQueryRequest;
import com.orion.ops.module.asset.entity.export.*; import com.orion.ops.module.asset.entity.request.host.HostIdentityUpdateRequest;
import com.orion.ops.module.asset.convert.*; import com.orion.ops.module.asset.entity.vo.HostIdentityVO;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List; import java.util.List;
/** /**
@@ -35,15 +33,6 @@ public interface HostIdentityService {
*/ */
Integer updateHostIdentityById(HostIdentityUpdateRequest request); Integer updateHostIdentityById(HostIdentityUpdateRequest request);
/**
* 更新主机身份
*
* @param query query
* @param update update
* @return effect
*/
Integer updateHostIdentity(HostIdentityQueryRequest query, HostIdentityUpdateRequest update);
/** /**
* 通过 id 查询主机身份 * 通过 id 查询主机身份
* *
@@ -52,29 +41,12 @@ public interface HostIdentityService {
*/ */
HostIdentityVO getHostIdentityById(Long id); HostIdentityVO getHostIdentityById(Long id);
/**
* 通过 id 批量查询主机身份
*
* @param idList idList
* @return rows
*/
List<HostIdentityVO> getHostIdentityByIdList(List<Long> idList);
/** /**
* 查询主机身份 * 查询主机身份
* *
* @param request request
* @return rows * @return rows
*/ */
List<HostIdentityVO> getHostIdentityList(HostIdentityQueryRequest request); List<HostIdentityVO> getHostIdentityList();
/**
* 查询主机身份数量
*
* @param request request
* @return count
*/
Long getHostIdentityCount(HostIdentityQueryRequest request);
/** /**
* 分页查询主机身份 * 分页查询主机身份
@@ -92,29 +64,4 @@ public interface HostIdentityService {
*/ */
Integer deleteHostIdentityById(Long id); Integer deleteHostIdentityById(Long id);
/**
* 通过 id 批量删除主机身份
*
* @param idList idList
* @return effect
*/
Integer batchDeleteHostIdentityByIdList(List<Long> idList);
/**
* 删除主机身份
*
* @param request request
* @return effect
*/
Integer deleteHostIdentity(HostIdentityQueryRequest request);
/**
* 导出主机身份
*
* @param request request
* @param response response
* @throws IOException IOException
*/
void exportHostIdentity(HostIdentityQueryRequest request, HttpServletResponse response) throws IOException;
} }

View File

@@ -3,28 +3,31 @@ package com.orion.ops.module.asset.service.impl;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.lang.define.wrapper.DataGrid; import com.orion.lang.define.wrapper.DataGrid;
import com.orion.lang.utils.collect.Lists; import com.orion.ops.framework.common.constant.Const;
import com.orion.office.excel.writer.exporting.ExcelExport;
import com.orion.ops.framework.common.constant.ErrorMessage;
import com.orion.ops.framework.common.utils.FileNames;
import com.orion.ops.framework.common.constant.ErrorMessage; import com.orion.ops.framework.common.constant.ErrorMessage;
import com.orion.ops.framework.common.security.PasswordModifier;
import com.orion.ops.framework.common.utils.Valid; import com.orion.ops.framework.common.utils.Valid;
import com.orion.ops.module.asset.entity.vo.*; import com.orion.ops.framework.redis.core.utils.RedisLists;
import com.orion.ops.module.asset.entity.request.host.*; import com.orion.ops.module.asset.convert.HostIdentityConvert;
import com.orion.ops.module.asset.entity.export.*;
import com.orion.ops.module.asset.convert.*;
import com.orion.ops.module.asset.entity.domain.HostIdentityDO;
import com.orion.ops.module.asset.dao.HostIdentityDAO; import com.orion.ops.module.asset.dao.HostIdentityDAO;
import com.orion.ops.module.asset.dao.HostKeyDAO;
import com.orion.ops.module.asset.define.HostCacheKeyDefine;
import com.orion.ops.module.asset.entity.domain.HostIdentityDO;
import com.orion.ops.module.asset.entity.domain.HostKeyDO;
import com.orion.ops.module.asset.entity.dto.HostIdentityCacheDTO;
import com.orion.ops.module.asset.entity.request.host.HostIdentityCreateRequest;
import com.orion.ops.module.asset.entity.request.host.HostIdentityQueryRequest;
import com.orion.ops.module.asset.entity.request.host.HostIdentityUpdateRequest;
import com.orion.ops.module.asset.entity.vo.HostIdentityVO;
import com.orion.ops.module.asset.service.HostIdentityService; import com.orion.ops.module.asset.service.HostIdentityService;
import com.orion.web.servlet.web.Servlets;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/** /**
* 主机身份 服务实现类 * 主机身份 服务实现类
@@ -40,9 +43,14 @@ public class HostIdentityServiceImpl implements HostIdentityService {
@Resource @Resource
private HostIdentityDAO hostIdentityDAO; private HostIdentityDAO hostIdentityDAO;
@Resource
private HostKeyDAO hostKeyDAO;
@Override @Override
public Long createHostIdentity(HostIdentityCreateRequest request) { public Long createHostIdentity(HostIdentityCreateRequest request) {
log.info("HostIdentityService-createHostIdentity request: {}", JSON.toJSONString(request)); log.info("HostIdentityService-createHostIdentity request: {}", JSON.toJSONString(request));
// 检查秘钥是否存在
this.checkKeyIdPresent(request.getKeyId());
// 转换 // 转换
HostIdentityDO record = HostIdentityConvert.MAPPER.to(request); HostIdentityDO record = HostIdentityConvert.MAPPER.to(request);
// 查询数据是否冲突 // 查询数据是否冲突
@@ -50,7 +58,11 @@ public class HostIdentityServiceImpl implements HostIdentityService {
// 插入 // 插入
int effect = hostIdentityDAO.insert(record); int effect = hostIdentityDAO.insert(record);
log.info("HostIdentityService-createHostIdentity effect: {}", effect); log.info("HostIdentityService-createHostIdentity effect: {}", effect);
return record.getId(); Long id = record.getId();
// 设置缓存
RedisLists.pushJson(HostCacheKeyDefine.HOST_IDENTITY.getKey(), HostIdentityConvert.MAPPER.toCache(record));
RedisLists.setExpire(HostCacheKeyDefine.HOST_IDENTITY);
return id;
} }
@Override @Override
@@ -60,29 +72,26 @@ public class HostIdentityServiceImpl implements HostIdentityService {
Long id = Valid.notNull(request.getId(), ErrorMessage.ID_MISSING); Long id = Valid.notNull(request.getId(), ErrorMessage.ID_MISSING);
HostIdentityDO record = hostIdentityDAO.selectById(id); HostIdentityDO record = hostIdentityDAO.selectById(id);
Valid.notNull(record, ErrorMessage.DATA_ABSENT); Valid.notNull(record, ErrorMessage.DATA_ABSENT);
// 检查秘钥是否存在
this.checkKeyIdPresent(request.getKeyId());
// 转换 // 转换
HostIdentityDO updateRecord = HostIdentityConvert.MAPPER.to(request); HostIdentityDO updateRecord = HostIdentityConvert.MAPPER.to(request);
// 查询数据是否冲突 // 查询数据是否冲突
this.checkHostIdentityPresent(updateRecord); this.checkHostIdentityPresent(updateRecord);
// 设置密码
String newPassword = PasswordModifier.getEncryptNewPassword(request);
updateRecord.setPassword(newPassword);
// 更新 // 更新
int effect = hostIdentityDAO.updateById(updateRecord); int effect = hostIdentityDAO.updateById(updateRecord);
// 设置缓存
if (!record.getName().equals(updateRecord.getName())) {
RedisLists.removeJson(HostCacheKeyDefine.HOST_IDENTITY.getKey(), HostIdentityConvert.MAPPER.toCache(record));
RedisLists.pushJson(HostCacheKeyDefine.HOST_IDENTITY.getKey(), HostIdentityConvert.MAPPER.toCache(updateRecord));
}
log.info("HostIdentityService-updateHostIdentityById effect: {}", effect); log.info("HostIdentityService-updateHostIdentityById effect: {}", effect);
return effect; return effect;
} }
@Override
public Integer updateHostIdentity(HostIdentityQueryRequest query, HostIdentityUpdateRequest update) {
log.info("HostIdentityService.updateHostIdentity query: {}, update: {}", JSON.toJSONString(query), JSON.toJSONString(update));
// 条件
LambdaQueryWrapper<HostIdentityDO> wrapper = this.buildQueryWrapper(query);
// 转换
HostIdentityDO updateRecord = HostIdentityConvert.MAPPER.to(update);
// 更新
int effect = hostIdentityDAO.update(updateRecord, wrapper);
log.info("HostIdentityService.updateHostIdentity effect: {}", effect);
return effect;
}
@Override @Override
public HostIdentityVO getHostIdentityById(Long id) { public HostIdentityVO getHostIdentityById(Long id) {
// 查询 // 查询
@@ -93,30 +102,27 @@ public class HostIdentityServiceImpl implements HostIdentityService {
} }
@Override @Override
public List<HostIdentityVO> getHostIdentityByIdList(List<Long> idList) { public List<HostIdentityVO> getHostIdentityList() {
// 查询 // 查询缓存
List<HostIdentityDO> records = hostIdentityDAO.selectBatchIds(idList); List<HostIdentityCacheDTO> list = RedisLists.rangeJson(HostCacheKeyDefine.HOST_IDENTITY);
if (records.isEmpty()) { if (list.isEmpty()) {
return Lists.empty(); // 查询数据库
list = hostIdentityDAO.of().list(HostIdentityConvert.MAPPER::toCache);
// 添加默认值 防止穿透
if (list.isEmpty()) {
list.add(HostIdentityCacheDTO.builder()
.id(Const.NONE_ID)
.build());
}
// 设置缓存
RedisLists.pushAllJson(HostCacheKeyDefine.HOST_IDENTITY.getKey(), list);
RedisLists.setExpire(HostCacheKeyDefine.HOST_IDENTITY);
} }
// 转换 // 删除默认值
return HostIdentityConvert.MAPPER.to(records); return list.stream()
} .filter(s -> !s.getId().equals(Const.NONE_ID))
.map(HostIdentityConvert.MAPPER::to)
@Override .collect(Collectors.toList());
public List<HostIdentityVO> getHostIdentityList(HostIdentityQueryRequest request) {
// 条件
LambdaQueryWrapper<HostIdentityDO> wrapper = this.buildQueryWrapper(request);
// 查询
return hostIdentityDAO.of(wrapper).list(HostIdentityConvert.MAPPER::to);
}
@Override
public Long getHostIdentityCount(HostIdentityQueryRequest request) {
// 条件
LambdaQueryWrapper<HostIdentityDO> wrapper = this.buildQueryWrapper(request);
// 查询
return hostIdentityDAO.selectCount(wrapper);
} }
@Override @Override
@@ -124,58 +130,51 @@ public class HostIdentityServiceImpl implements HostIdentityService {
// 条件 // 条件
LambdaQueryWrapper<HostIdentityDO> wrapper = this.buildQueryWrapper(request); LambdaQueryWrapper<HostIdentityDO> wrapper = this.buildQueryWrapper(request);
// 查询 // 查询
return hostIdentityDAO.of(wrapper) DataGrid<HostIdentityVO> dataGrid = hostIdentityDAO.of(wrapper)
.page(request) .page(request)
.dataGrid(HostIdentityConvert.MAPPER::to); .dataGrid(HostIdentityConvert.MAPPER::to);
if (dataGrid.isEmpty()) {
return dataGrid;
}
// 设置秘钥名称
List<Long> keyIdList = dataGrid.stream()
.map(HostIdentityVO::getKeyId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (!keyIdList.isEmpty()) {
// 查询秘钥名称
Map<Long, String> keyNameMap = hostKeyDAO.selectBatchIds(keyIdList)
.stream()
.collect(Collectors.toMap(HostKeyDO::getId, HostKeyDO::getName));
dataGrid.forEach(s -> {
if (s.getKeyId() == null) {
return;
}
s.setKeyName(keyNameMap.get(s.getKeyId()));
});
}
return dataGrid;
} }
@Override @Override
public Integer deleteHostIdentityById(Long id) { public Integer deleteHostIdentityById(Long id) {
log.info("HostIdentityService-deleteHostIdentityById id: {}", id); log.info("HostIdentityService-deleteHostIdentityById id: {}", id);
// 检查数据是否存在
HostIdentityDO record = hostIdentityDAO.selectById(id);
Valid.notNull(record, ErrorMessage.DATA_ABSENT);
// 删除数据库
int effect = hostIdentityDAO.deleteById(id); int effect = hostIdentityDAO.deleteById(id);
// TODO config
// 删除缓存
RedisLists.removeJson(HostCacheKeyDefine.HOST_IDENTITY.getKey(), HostIdentityConvert.MAPPER.toCache(record));
log.info("HostIdentityService-deleteHostIdentityById effect: {}", effect); log.info("HostIdentityService-deleteHostIdentityById effect: {}", effect);
return effect; return effect;
} }
@Override
public Integer batchDeleteHostIdentityByIdList(List<Long> idList) {
log.info("HostIdentityService-batchDeleteHostIdentityByIdList idList: {}", idList);
int effect = hostIdentityDAO.deleteBatchIds(idList);
log.info("HostIdentityService-batchDeleteHostIdentityByIdList effect: {}", effect);
return effect;
}
@Override
public Integer deleteHostIdentity(HostIdentityQueryRequest request) {
log.info("HostIdentityService.deleteHostIdentity request: {}", JSON.toJSONString(request));
// 条件
LambdaQueryWrapper<HostIdentityDO> wrapper = this.buildQueryWrapper(request);
// 删除
int effect = hostIdentityDAO.delete(wrapper);
log.info("HostIdentityService.deleteHostIdentity effect: {}", effect);
return effect;
}
@Override
public void exportHostIdentity(HostIdentityQueryRequest request, HttpServletResponse response) throws IOException {
log.info("HostIdentityService.exportHostIdentity request: {}", JSON.toJSONString(request));
// 条件
LambdaQueryWrapper<HostIdentityDO> wrapper = this.buildQueryWrapper(request);
// 查询
List<HostIdentityExport> rows = hostIdentityDAO.of(wrapper).list(HostIdentityConvert.MAPPER::toExport);
log.info("HostIdentityService.exportHostIdentity size: {}", rows.size());
// 导出
ByteArrayOutputStream out = new ByteArrayOutputStream();
ExcelExport.create(HostIdentityExport.class)
.addRows(rows)
.write(out)
.close();
// 传输
Servlets.transfer(response, out.toByteArray(), FileNames.exportName(HostIdentityExport.TITLE));
}
/** /**
* 检对象是否存在 * 检对象是否存在
* *
* @param domain domain * @param domain domain
*/ */
@@ -185,15 +184,24 @@ public class HostIdentityServiceImpl implements HostIdentityService {
// 更新时忽略当前记录 // 更新时忽略当前记录
.ne(HostIdentityDO::getId, domain.getId()) .ne(HostIdentityDO::getId, domain.getId())
// 用其他字段做重复校验 // 用其他字段做重复校验
.eq(HostIdentityDO::getName, domain.getName()) .eq(HostIdentityDO::getName, domain.getName());
.eq(HostIdentityDO::getUsername, domain.getUsername())
.eq(HostIdentityDO::getPassword, domain.getPassword())
.eq(HostIdentityDO::getKeyId, domain.getKeyId());
// 检查是否存在 // 检查是否存在
boolean present = hostIdentityDAO.of(wrapper).present(); boolean present = hostIdentityDAO.of(wrapper).present();
Valid.isFalse(present, ErrorMessage.DATA_PRESENT); Valid.isFalse(present, ErrorMessage.DATA_PRESENT);
} }
/**
* 检查秘钥是否存在
*
* @param keyId keyId
*/
private void checkKeyIdPresent(Long keyId) {
if (keyId == null) {
return;
}
Valid.notNull(hostKeyDAO.selectById(keyId), ErrorMessage.KEY_ABSENT);
}
/** /**
* 构建查询 wrapper * 构建查询 wrapper
* *
@@ -203,9 +211,8 @@ public class HostIdentityServiceImpl implements HostIdentityService {
private LambdaQueryWrapper<HostIdentityDO> buildQueryWrapper(HostIdentityQueryRequest request) { private LambdaQueryWrapper<HostIdentityDO> buildQueryWrapper(HostIdentityQueryRequest request) {
return hostIdentityDAO.wrapper() return hostIdentityDAO.wrapper()
.eq(HostIdentityDO::getId, request.getId()) .eq(HostIdentityDO::getId, request.getId())
.eq(HostIdentityDO::getName, request.getName()) .like(HostIdentityDO::getName, request.getName())
.eq(HostIdentityDO::getUsername, request.getUsername()) .like(HostIdentityDO::getUsername, request.getUsername())
.eq(HostIdentityDO::getPassword, request.getPassword())
.eq(HostIdentityDO::getKeyId, request.getKeyId()); .eq(HostIdentityDO::getKeyId, request.getKeyId());
} }

View File

@@ -3,14 +3,15 @@ package com.orion.ops.module.asset.service.impl;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.lang.define.wrapper.DataGrid; import com.orion.lang.define.wrapper.DataGrid;
import com.orion.lang.utils.Booleans;
import com.orion.lang.utils.Strings; import com.orion.lang.utils.Strings;
import com.orion.ops.framework.common.constant.Const; import com.orion.ops.framework.common.constant.Const;
import com.orion.ops.framework.common.constant.ErrorMessage; import com.orion.ops.framework.common.constant.ErrorMessage;
import com.orion.ops.framework.common.security.PasswordModifier;
import com.orion.ops.framework.common.utils.CryptoUtils; import com.orion.ops.framework.common.utils.CryptoUtils;
import com.orion.ops.framework.common.utils.Valid; import com.orion.ops.framework.common.utils.Valid;
import com.orion.ops.framework.redis.core.utils.RedisLists; import com.orion.ops.framework.redis.core.utils.RedisLists;
import com.orion.ops.module.asset.convert.HostKeyConvert; import com.orion.ops.module.asset.convert.HostKeyConvert;
import com.orion.ops.module.asset.dao.HostIdentityDAO;
import com.orion.ops.module.asset.dao.HostKeyDAO; import com.orion.ops.module.asset.dao.HostKeyDAO;
import com.orion.ops.module.asset.define.HostCacheKeyDefine; import com.orion.ops.module.asset.define.HostCacheKeyDefine;
import com.orion.ops.module.asset.entity.domain.HostKeyDO; import com.orion.ops.module.asset.entity.domain.HostKeyDO;
@@ -22,6 +23,7 @@ import com.orion.ops.module.asset.entity.vo.HostKeyVO;
import com.orion.ops.module.asset.service.HostKeyService; import com.orion.ops.module.asset.service.HostKeyService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.List; import java.util.List;
@@ -41,6 +43,9 @@ public class HostKeyServiceImpl implements HostKeyService {
@Resource @Resource
private HostKeyDAO hostKeyDAO; private HostKeyDAO hostKeyDAO;
@Resource
private HostIdentityDAO hostIdentityDAO;
@Override @Override
public Long createHostKey(HostKeyCreateRequest request) { public Long createHostKey(HostKeyCreateRequest request) {
log.info("HostKeyService-createHostKey request: {}", JSON.toJSONString(request)); log.info("HostKeyService-createHostKey request: {}", JSON.toJSONString(request));
@@ -73,25 +78,17 @@ public class HostKeyServiceImpl implements HostKeyService {
HostKeyDO updateRecord = HostKeyConvert.MAPPER.to(request); HostKeyDO updateRecord = HostKeyConvert.MAPPER.to(request);
// 查询数据是否冲突 // 查询数据是否冲突
this.checkHostKeyPresent(updateRecord); this.checkHostKeyPresent(updateRecord);
if (Booleans.isTrue(request.getUseNewPassword())) { // 设置密码
// 使用新密码 String newPassword = PasswordModifier.getEncryptNewPassword(request);
String password = updateRecord.getPassword(); updateRecord.setPassword(newPassword);
if (Strings.isBlank(password)) {
updateRecord.setPassword(Const.EMPTY);
} else {
updateRecord.setPassword(CryptoUtils.encryptAsString(password));
}
} else {
updateRecord.setPassword(null);
}
// 更新 // 更新
int effect = hostKeyDAO.updateById(updateRecord); int effect = hostKeyDAO.updateById(updateRecord);
log.info("HostKeyService-updateHostKeyById effect: {}", effect);
// 设置缓存 // 设置缓存
if (!record.getName().equals(updateRecord.getName())) { if (!record.getName().equals(updateRecord.getName())) {
RedisLists.removeJson(HostCacheKeyDefine.HOST_KEY.getKey(), HostKeyConvert.MAPPER.toCache(record)); RedisLists.removeJson(HostCacheKeyDefine.HOST_KEY.getKey(), HostKeyConvert.MAPPER.toCache(record));
RedisLists.pushJson(HostCacheKeyDefine.HOST_KEY.getKey(), HostKeyConvert.MAPPER.toCache(updateRecord)); RedisLists.pushJson(HostCacheKeyDefine.HOST_KEY.getKey(), HostKeyConvert.MAPPER.toCache(updateRecord));
} }
log.info("HostKeyService-updateHostKeyById effect: {}", effect);
return effect; return effect;
} }
@@ -130,6 +127,7 @@ public class HostKeyServiceImpl implements HostKeyService {
} }
// 设置缓存 // 设置缓存
RedisLists.pushAllJson(HostCacheKeyDefine.HOST_KEY.getKey(), list); RedisLists.pushAllJson(HostCacheKeyDefine.HOST_KEY.getKey(), list);
RedisLists.setExpire(HostCacheKeyDefine.HOST_KEY);
} }
// 删除默认值 // 删除默认值
return list.stream() return list.stream()
@@ -151,15 +149,26 @@ public class HostKeyServiceImpl implements HostKeyService {
} }
@Override @Override
@Transactional(rollbackFor = Exception.class)
public Integer deleteHostKeyById(Long id) { public Integer deleteHostKeyById(Long id) {
log.info("HostKeyService-deleteHostKeyById id: {}", id); log.info("HostKeyService-deleteHostKeyById id: {}", id);
// 检查数据是否存在
HostKeyDO record = hostKeyDAO.selectById(id);
Valid.notNull(record, ErrorMessage.DATA_ABSENT);
// 删除数据库
int effect = hostKeyDAO.deleteById(id); int effect = hostKeyDAO.deleteById(id);
// 删除关联
hostIdentityDAO.setKeyWithNull(id);
// TODO config
// 删除缓存
RedisLists.removeJson(HostCacheKeyDefine.HOST_KEY.getKey(), HostKeyConvert.MAPPER.toCache(record));
log.info("HostKeyService-deleteHostKeyById effect: {}", effect); log.info("HostKeyService-deleteHostKeyById effect: {}", effect);
return effect; return effect;
} }
/** /**
* 检对象是否存在 * 检对象是否存在
* *
* @param domain domain * @param domain domain
*/ */

View File

@@ -21,4 +21,10 @@
id, name, username, password, key_id, create_time, update_time, creator, updater, deleted id, name, username, password, key_id, create_time, update_time, creator, updater, deleted
</sql> </sql>
<update id="setKeyWithNull">
UPDATE host_identity
SET key_id = NULL
WHERE key_id = #{keyId}
</update>
</mapper> </mapper>

View File

@@ -17,6 +17,7 @@ export interface HostIdentityCreateRequest {
*/ */
export interface HostIdentityUpdateRequest extends HostIdentityCreateRequest { export interface HostIdentityUpdateRequest extends HostIdentityCreateRequest {
id: number; id: number;
useNewPassword?: boolean;
} }
/** /**
@@ -66,23 +67,11 @@ export function getHostIdentity(id: number) {
return axios.get<HostIdentityQueryResponse>('/asset/host-identity/get', { params: { id } }); return axios.get<HostIdentityQueryResponse>('/asset/host-identity/get', { params: { id } });
} }
/**
* 通过 id 批量查询主机身份
*/
export function getHostIdentityList(idList: Array<number>) {
return axios.get<HostIdentityQueryResponse[]>('/asset/host-identity/list', {
params: { idList },
paramsSerializer: params => {
return qs.stringify(params, { arrayFormat: 'comma' });
}
});
}
/** /**
* 查询主机身份 * 查询主机身份
*/ */
export function getHostIdentityListAll(request: HostIdentityQueryRequest) { export function getHostIdentityList() {
return axios.post<Array<HostIdentityQueryResponse>>('/asset/host-identity/list-all', request); return axios.post<Array<HostIdentityQueryResponse>>('/asset/host-identity/list');
} }
/** /**
@@ -99,14 +88,3 @@ export function deleteHostIdentity(id: number) {
return axios.delete('/asset/host-identity/delete', { params: { id } }); return axios.delete('/asset/host-identity/delete', { params: { id } });
} }
/**
* 通过 id 批量删除主机身份
*/
export function batchDeleteHostIdentity(idList: Array<number>) {
return axios.delete('/asset/host-identity/delete-batch', {
params: { idList },
paramsSerializer: params => {
return qs.stringify(params, { arrayFormat: 'comma' });
}
});
}

View File

@@ -9,7 +9,6 @@ export interface HostKeyCreateRequest {
publicKey?: string; publicKey?: string;
privateKey?: string; privateKey?: string;
password?: string; password?: string;
useNewPassword?: boolean;
} }
/** /**
@@ -17,6 +16,7 @@ export interface HostKeyCreateRequest {
*/ */
export interface HostKeyUpdateRequest extends HostKeyCreateRequest { export interface HostKeyUpdateRequest extends HostKeyCreateRequest {
id: number; id: number;
useNewPassword?: boolean;
} }
/** /**
@@ -66,8 +66,8 @@ export function getHostKey(id: number) {
/** /**
* 查询主机秘钥 * 查询主机秘钥
*/ */
export function getHostKeyListAll() { export function getHostKeyList() {
return axios.post<Array<HostKeyQueryResponse>>('/asset/host-key/list-all'); return axios.post<Array<HostKeyQueryResponse>>('/asset/host-key/list');
} }
/** /**

View File

@@ -13,7 +13,7 @@ export interface TagCreateRequest {
/** /**
* tag 响应对象 * tag 响应对象
*/ */
export interface TagResponse { export interface TagQueryResponse {
id: number; id: number;
name: string; name: string;
} }
@@ -29,5 +29,5 @@ export function createTag(request: TagCreateRequest) {
* 查询标签 * 查询标签
*/ */
export function getTagList(type: TagType) { export function getTagList(type: TagType) {
return axios.get<TagResponse>('/infra/tag/list', { params: { type } }); return axios.get<TagQueryResponse>('/infra/tag/list', { params: { type } });
} }

View File

@@ -115,6 +115,10 @@ body {
} }
} }
.span-blue {
color: rgb(var(--arcoblue-6));
}
#app { #app {
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;

View File

@@ -0,0 +1,52 @@
<template>
<a-select v-model:model-value="value"
:options="optionData()"
placeholder="请选择主机秘钥"
allow-clear />
</template>
<script lang="ts">
export default {
name: 'host-key-selector'
};
</script>
<script lang="ts" setup>
import { computed } from 'vue';
import { useCacheStore } from '@/store';
import { SelectOptionData } from '@arco-design/web-vue';
const props = defineProps({
modelValue: Number,
});
const emits = defineEmits(['update:modelValue']);
const value = computed({
get() {
return props.modelValue;
},
set(e) {
if (e) {
emits('update:modelValue', e);
} else {
emits('update:modelValue', null);
}
}
});
// 选项数据
const cacheStore = useCacheStore();
const optionData = (): SelectOptionData[] => {
return cacheStore.hostKeys.map(s => {
return {
label: s.name,
value: s.id,
};
});
};
</script>
<style scoped>
</style>

View File

@@ -1,13 +1,14 @@
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import { CacheState } from './types'; import { CacheState } from './types';
export type CacheType = 'menus' | 'roles' | 'tags' export type CacheType = 'menus' | 'roles' | 'tags' | 'hostKeys'
const useCacheStore = defineStore('cache', { const useCacheStore = defineStore('cache', {
state: (): CacheState => ({ state: (): CacheState => ({
menus: [], menus: [],
roles: [], roles: [],
tags: [] tags: [],
hostKeys: [],
}), }),
getters: {}, getters: {},

View File

@@ -1,9 +1,13 @@
import { MenuQueryResponse } from '@/api/system/menu'; import { MenuQueryResponse } from '@/api/system/menu';
import { RoleQueryResponse } from '@/api/user/role'; import { RoleQueryResponse } from '@/api/user/role';
import { TagResponse } from '@/api/meta/tag'; import { TagQueryResponse } from '@/api/meta/tag';
import { HostKeyQueryResponse } from '@/api/asset/host-key';
export interface CacheState { export interface CacheState {
menus: MenuQueryResponse[]; menus: MenuQueryResponse[];
roles: RoleQueryResponse[]; roles: RoleQueryResponse[];
tags: TagResponse[]; tags: TagQueryResponse[];
hostKeys: HostKeyQueryResponse[];
[key: string]: unknown;
} }

View File

@@ -1,145 +0,0 @@
<template>
<a-drawer :visible="visible"
:title="title"
:width="430"
:mask-closable="false"
:unmount-on-close="true"
:on-before-ok="handlerOk"
@cancel="handleClose">
<a-spin :loading="loading">
<a-form :model="formModel"
ref="formRef"
label-align="right"
:style="{ width: '380px' }"
:label-col-props="{ span: 6 }"
:wrapper-col-props="{ span: 18 }"
:rules="formRules">
<!-- 名称 -->
<a-form-item field="name" label="名称">
<a-input v-model="formModel.name" placeholder="请输入名称" />
</a-form-item>
<!-- 用户名 -->
<a-form-item field="username" label="用户名">
<a-input v-model="formModel.username" placeholder="请输入用户名" />
</a-form-item>
<!-- 用户密码 -->
<a-form-item field="password" label="用户密码">
<a-input v-model="formModel.password" placeholder="请输入用户密码" />
</a-form-item>
<!-- 秘钥id -->
<a-form-item field="keyId" label="秘钥id">
<a-input-number v-model="formModel.keyId" placeholder="请输入秘钥id" />
</a-form-item>
</a-form>
</a-spin>
</a-drawer>
</template>
<script lang="ts">
export default {
name: 'asset-host-identity-form-drawer'
};
</script>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import useLoading from '@/hooks/loading';
import useVisible from '@/hooks/visible';
import formRules from '../types/form.rules';
import { createHostIdentity, updateHostIdentity } from '@/api/asset/host-identity';
import { Message } from '@arco-design/web-vue';
import {} from '../types/enum.types';
import {} from '../types/const';
import { toOptions } from '@/utils/enum';
const { visible, setVisible } = useVisible();
const { loading, setLoading } = useLoading();
const title = ref<string>();
const isAddHandle = ref<boolean>(true);
const defaultForm = () => {
return {
id: undefined,
name: undefined,
username: undefined,
password: undefined,
keyId: undefined,
};
};
const formRef = ref<any>();
const formModel = reactive<Record<string, any>>(defaultForm());
const emits = defineEmits(['added', 'updated']);
// 打开新增
const openAdd = () => {
title.value = '添加主机身份';
isAddHandle.value = true;
renderForm({ ...defaultForm() });
setVisible(true);
};
// 打开修改
const openUpdate = (record: any) => {
title.value = '修改主机身份';
isAddHandle.value = false;
renderForm({ ...defaultForm(), ...record });
setVisible(true);
};
// 渲染表单
const renderForm = (record: any) => {
Object.keys(formModel).forEach(k => {
formModel[k] = record[k];
});
};
defineExpose({ openAdd, openUpdate });
// 确定
const handlerOk = async () => {
setLoading(true);
try {
// 验证参数
const error = await formRef.value.validate();
if (error) {
return false;
}
if (isAddHandle.value) {
// 新增
await createHostIdentity(formModel as any);
Message.success('创建成功');
emits('added');
} else {
// 修改
await updateHostIdentity(formModel as any);
Message.success('修改成功');
emits('updated');
}
// 清空
handlerClear();
} catch (e) {
return false;
} finally {
setLoading(false);
}
};
// 关闭
const handleClose = () => {
handlerClear();
};
// 清空
const handlerClear = () => {
setLoading(false);
setVisible(false);
};
</script>
<style lang="less" scoped>
</style>

View File

@@ -29,12 +29,23 @@
<a-input v-model="formModel.username" placeholder="请输入用户名" /> <a-input v-model="formModel.username" placeholder="请输入用户名" />
</a-form-item> </a-form-item>
<!-- 用户密码 --> <!-- 用户密码 -->
<a-form-item field="password" label="用户密码"> <a-form-item field="password"
<a-input v-model="formModel.password" placeholder="请输入用户密码" /> label="用户密码"
style="justify-content: space-between;">
<a-input-password v-model="formModel.password"
:disabled="!formModel.useNewPassword"
class="password-input"
placeholder="请输入用户密码" />
<a-switch v-model="formModel.useNewPassword"
class="password-switch"
type="round"
size="large"
checked-text="使用新密码"
unchecked-text="使用原密码" />
</a-form-item> </a-form-item>
<!-- 秘钥id --> <!-- 秘钥id -->
<a-form-item field="keyId" label="秘钥id"> <a-form-item field="keyId" label="主机秘钥">
<a-input-number v-model="formModel.keyId" placeholder="请输入秘钥id" /> <host-key-selector v-model="formModel.keyId" />
</a-form-item> </a-form-item>
</a-form> </a-form>
</a-spin> </a-spin>
@@ -54,9 +65,7 @@
import formRules from '../types/form.rules'; import formRules from '../types/form.rules';
import { createHostIdentity, updateHostIdentity } from '@/api/asset/host-identity'; import { createHostIdentity, updateHostIdentity } from '@/api/asset/host-identity';
import { Message } from '@arco-design/web-vue'; import { Message } from '@arco-design/web-vue';
import {} from '../types/enum.types'; import HostKeySelector from '@/components/asset/host-key/host-key-selector.vue';
import {} from '../types/const';
import { toOptions } from '@/utils/enum';
const { visible, setVisible } = useVisible(); const { visible, setVisible } = useVisible();
const { loading, setLoading } = useLoading(); const { loading, setLoading } = useLoading();
@@ -70,6 +79,7 @@
name: undefined, name: undefined,
username: undefined, username: undefined,
password: undefined, password: undefined,
useNewPassword: false,
keyId: undefined, keyId: undefined,
}; };
}; };
@@ -147,5 +157,11 @@
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.password-input {
width: 240px;
}
.password-switch {
margin-left: 16px;
}
</style> </style>

View File

@@ -7,23 +7,19 @@
@reset="fetchTableData"> @reset="fetchTableData">
<!-- id --> <!-- id -->
<a-form-item field="id" label="id" label-col-flex="50px"> <a-form-item field="id" label="id" label-col-flex="50px">
<a-input-number v-model="formModel.id" placeholder="请输入id" allow-clear/> <a-input-number v-model="formModel.id" placeholder="请输入id" allow-clear />
</a-form-item> </a-form-item>
<!-- 名称 --> <!-- 名称 -->
<a-form-item field="name" label="名称" label-col-flex="50px"> <a-form-item field="name" label="名称" label-col-flex="50px">
<a-input v-model="formModel.name" placeholder="请输入名称" allow-clear/> <a-input v-model="formModel.name" placeholder="请输入名称" allow-clear />
</a-form-item> </a-form-item>
<!-- 用户名 --> <!-- 用户名 -->
<a-form-item field="username" label="用户名" label-col-flex="50px"> <a-form-item field="username" label="用户名" label-col-flex="50px">
<a-input v-model="formModel.username" placeholder="请输入用户名" allow-clear/> <a-input v-model="formModel.username" placeholder="请输入用户名" allow-clear />
</a-form-item> </a-form-item>
<!-- 用户密码 --> <!-- 主机秘钥 -->
<a-form-item field="password" label="用户密码" label-col-flex="50px"> <a-form-item field="keyId" label="主机秘钥" label-col-flex="50px">
<a-input v-model="formModel.password" placeholder="请输入用户密码" allow-clear/> <host-key-selector v-model="formModel.keyId" allow-clear />
</a-form-item>
<!-- 秘钥id -->
<a-form-item field="keyId" label="秘钥id" label-col-flex="50px">
<a-input-number v-model="formModel.keyId" placeholder="请输入秘钥id" allow-clear/>
</a-form-item> </a-form-item>
</a-query-header> </a-query-header>
</a-card> </a-card>
@@ -32,7 +28,7 @@
<template #title> <template #title>
<!-- 左侧标题 --> <!-- 左侧标题 -->
<div class="table-title"> <div class="table-title">
主机身份列表 身份列表
</div> </div>
<!-- 右侧按钮 --> <!-- 右侧按钮 -->
<div class="table-bar-handle"> <div class="table-bar-handle">
@@ -46,21 +42,6 @@
<icon-plus /> <icon-plus />
</template> </template>
</a-button> </a-button>
<!-- 删除 -->
<a-popconfirm position="br"
type="warning"
:content="`确认删除选中的${selectedKeys.length}条记录吗?`"
@ok="deleteSelectRows">
<a-button v-permission="['asset:host-identity:delete']"
type="secondary"
status="danger"
:disabled="selectedKeys.length === 0">
删除
<template #icon>
<icon-delete />
</template>
</a-button>
</a-popconfirm>
</a-space> </a-space>
</div> </div>
</template> </template>
@@ -71,14 +52,16 @@
label-align="left" label-align="left"
:loading="loading" :loading="loading"
:columns="columns" :columns="columns"
v-model:selectedKeys="selectedKeys"
:row-selection="rowSelection"
:data="tableRenderData" :data="tableRenderData"
:pagination="pagination" :pagination="pagination"
@page-change="(page) => fetchTableData(page, pagination.pageSize)" @page-change="(page) => fetchTableData(page, pagination.pageSize)"
@page-size-change="(size) => fetchTableData(pagination.current, size)" @page-size-change="(size) => fetchTableData(pagination.current, size)"
:bordered="false"> :bordered="false">
<!-- 操作 --> <!-- 操作 -->
<template #keyId="{ record }">
{{ record.keyName }}
</template>
<!-- 操作 -->
<template #handle="{ record }"> <template #handle="{ record }">
<div class="table-handle-wrapper"> <div class="table-handle-wrapper">
<!-- 修改 --> <!-- 修改 -->
@@ -114,46 +97,29 @@
<script lang="ts" setup> <script lang="ts" setup>
import { reactive, ref } from 'vue'; import { reactive, ref } from 'vue';
import { batchDeleteHostIdentity, deleteHostIdentity, getHostIdentityPage, HostIdentityQueryRequest, HostIdentityQueryResponse } from '@/api/asset/host-identity'; import { deleteHostIdentity, getHostIdentityPage, HostIdentityQueryRequest, HostIdentityQueryResponse } from '@/api/asset/host-identity';
import { Message } from '@arco-design/web-vue'; import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading'; import useLoading from '@/hooks/loading';
import columns from '../types/table.columns'; import columns from '../types/table.columns';
import { defaultPagination, defaultRowSelection } from '@/types/table'; import { defaultPagination } from '@/types/table';
import {} from '../types/enum.types'; import { getHostKeyList } from '@/api/asset/host-key';
import {} from '../types/const'; import { useCacheStore } from '@/store';
import { toOptions } from '@/utils/enum'; import HostKeySelector from '@/components/asset/host-key/host-key-selector.vue';
const tableRenderData = ref<HostIdentityQueryResponse[]>(); const tableRenderData = ref<HostIdentityQueryResponse[]>();
const { loading, setLoading } = useLoading(); const { loading, setLoading } = useLoading();
const emits = defineEmits(['openAdd', 'openUpdate']); const emits = defineEmits(['openAdd', 'openUpdate']);
const cacheStore = useCacheStore();
const pagination = reactive(defaultPagination()); const pagination = reactive(defaultPagination());
const selectedKeys = ref<number[]>([]);
const rowSelection = reactive(defaultRowSelection());
const formModel = reactive<HostIdentityQueryRequest>({ const formModel = reactive<HostIdentityQueryRequest>({
id: undefined, id: undefined,
name: undefined, name: undefined,
username: undefined, username: undefined,
password: undefined,
keyId: undefined, keyId: undefined,
}); });
// 删除选中行
const deleteSelectRows = async () => {
try {
setLoading(true);
// 调用删除接口
await batchDeleteHostIdentity(selectedKeys.value);
Message.success(`成功删除${selectedKeys.value.length}条数据`);
selectedKeys.value = [];
// 重新加载数据
await fetchTableData();
} finally {
setLoading(false);
}
};
// 删除当前行 // 删除当前行
const deleteRow = async ({ id }: { id: number }) => { const deleteRow = async ({ id }: { id: number }) => {
try { try {
@@ -202,6 +168,13 @@
}; };
fetchTableData(); fetchTableData();
// 获取主机秘钥列表
const fetchHostKeyList = async () => {
const { data } = await getHostKeyList();
cacheStore.set('hostKeys', data);
};
fetchHostKeyList();
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>

View File

@@ -2,30 +2,36 @@
<div class="layout-container"> <div class="layout-container">
<!-- 表格 --> <!-- 表格 -->
<host-identity-table ref="table" <host-identity-table ref="table"
@openAdd="() => drawer.openAdd()" @openAdd="() => modal.openAdd()"
@openUpdate="(e) => drawer.openUpdate(e)" /> @openUpdate="(e) => modal.openUpdate(e)" />
<!-- 添加修改模态框 --> <!-- 添加修改模态框 -->
<host-identity-form-drawer ref="drawer" <host-identity-form-modal ref="modal"
@added="() => table.addedCallback()" @added="() => table.addedCallback()"
@updated="() => table.updatedCallback()" /> @updated="() => table.updatedCallback()" />
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts">
export default { export default {
name: 'asset-host-identity' name: 'assetHostIdentity'
}; };
</script> </script>
<script lang="ts" setup> <script lang="ts" setup>
import HostIdentityTable from './components/host-identity-table.vue'; import HostIdentityTable from './components/host-identity-table.vue';
import HostIdentityFormDrawer from './components/host-identity-form-drawer.vue'; import HostIdentityFormModal from './components/host-identity-form-modal.vue';
import { ref } from 'vue'; import { onUnmounted, ref } from 'vue';
import { useCacheStore } from '@/store';
const table = ref(); const table = ref();
const drawer = ref(); const modal = ref();
// 卸载时清除 tags cache
onUnmounted(() => {
const cacheStore = useCacheStore();
cacheStore.set('hostKeys', []);
});
</script> </script>

View File

@@ -13,28 +13,14 @@ const columns = [
title: '名称', title: '名称',
dataIndex: 'name', dataIndex: 'name',
slotName: 'name', slotName: 'name',
align: 'center',
ellipsis: true,
tooltip: true,
}, { }, {
title: '用户名', title: '用户名',
dataIndex: 'username', dataIndex: 'username',
slotName: 'username', slotName: 'username',
align: 'center',
ellipsis: true,
tooltip: true,
}, { }, {
title: '用户密码', title: '主机秘钥',
dataIndex: 'password',
slotName: 'password',
align: 'center',
ellipsis: true,
tooltip: true,
}, {
title: '秘钥id',
dataIndex: 'keyId', dataIndex: 'keyId',
slotName: 'keyId', slotName: 'keyId',
align: 'center',
}, { }, {
title: '创建时间', title: '创建时间',
dataIndex: 'createTime', dataIndex: 'createTime',
@@ -53,14 +39,6 @@ const columns = [
render: ({ record }) => { render: ({ record }) => {
return dateFormat(new Date(record.updateTime)); return dateFormat(new Date(record.updateTime));
}, },
}, {
title: '创建人',
dataIndex: 'creator',
slotName: 'creator',
}, {
title: '修改人',
dataIndex: 'updater',
slotName: 'updater',
}, { }, {
title: '操作', title: '操作',
slotName: 'handle', slotName: 'handle',

View File

@@ -20,7 +20,7 @@
<template #title> <template #title>
<!-- 左侧标题 --> <!-- 左侧标题 -->
<div class="table-title"> <div class="table-title">
主机秘钥列表 秘钥列表
</div> </div>
<!-- 右侧按钮 --> <!-- 右侧按钮 -->
<div class="table-bar-handle"> <div class="table-bar-handle">
@@ -49,6 +49,10 @@
@page-change="(page) => fetchTableData(page, pagination.pageSize)" @page-change="(page) => fetchTableData(page, pagination.pageSize)"
@page-size-change="(size) => fetchTableData(pagination.current, size)" @page-size-change="(size) => fetchTableData(pagination.current, size)"
:bordered="false"> :bordered="false">
<!-- 名称 -->
<template #name="{ record }">
<span class="span-blue">{{ record.name }}</span>
</template>
<!-- 操作 --> <!-- 操作 -->
<template #handle="{ record }"> <template #handle="{ record }">
<div class="table-handle-wrapper"> <div class="table-handle-wrapper">

View File

@@ -14,7 +14,7 @@
<script lang="ts"> <script lang="ts">
export default { export default {
name: 'asset-host-key' name: 'assetHostKey'
}; };
</script> </script>

View File

@@ -78,6 +78,14 @@
@page-change="(page) => fetchTableData(page, pagination.pageSize)" @page-change="(page) => fetchTableData(page, pagination.pageSize)"
@page-size-change="(size) => fetchTableData(pagination.current, size)" @page-size-change="(size) => fetchTableData(pagination.current, size)"
:bordered="false"> :bordered="false">
<!-- 名称 -->
<template #name="{ record }">
<span class="span-blue">{{ record.name }}</span>
</template>
<!-- 编码 -->
<template #code="{ record }">
<a-tag>{{ record.code }}</a-tag>
</template>
<!-- 地址 --> <!-- 地址 -->
<template #address="{ record }"> <template #address="{ record }">
<span class="host-address" title="点击复制" @click="copy(record.address)"> <span class="host-address" title="点击复制" @click="copy(record.address)">

View File

@@ -56,6 +56,10 @@
@page-change="(page) => fetchTableData(page, pagination.pageSize)" @page-change="(page) => fetchTableData(page, pagination.pageSize)"
@page-size-change="(size) => fetchTableData(pagination.current, size)" @page-size-change="(size) => fetchTableData(pagination.current, size)"
:bordered="false"> :bordered="false">
<!-- 名称 -->
<template #name="{ record }">
<span class="span-blue">{{ record.name }}</span>
</template>
<!-- 编码 --> <!-- 编码 -->
<template #code="{ record }"> <template #code="{ record }">
<a-tag>{{ record.code }}</a-tag> <a-tag>{{ record.code }}</a-tag>

View File

@@ -72,7 +72,7 @@
:bordered="false"> :bordered="false">
<!-- 用户名 --> <!-- 用户名 -->
<template #username="{ record }"> <template #username="{ record }">
<span class="username-text">{{ record.username }}</span> <span class="span-blue">{{ record.username }}</span>
</template> </template>
<!-- 状态 --> <!-- 状态 -->
<template #status="{ record }"> <template #status="{ record }">
@@ -248,7 +248,5 @@
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.username-text {
color: rgb(var(--arcoblue-6));
}
</style> </style>

View File

@@ -25,7 +25,6 @@ const columns = [
title: '手机号', title: '手机号',
dataIndex: 'mobile', dataIndex: 'mobile',
slotName: 'mobile', slotName: 'mobile',
align: 'center',
ellipsis: true, ellipsis: true,
tooltip: true, tooltip: true,
}, { }, {