添加主机秘钥列表.

This commit is contained in:
lijiahang
2023-09-20 17:13:38 +08:00
parent 9a009dfd95
commit d29cdac130
24 changed files with 525 additions and 476 deletions

View File

@@ -29,12 +29,6 @@ Authorization: {{token}}
GET {{baseUrl}}/asset/host-key/get?id=1
Authorization: {{token}}
### 通过 id 批量查询主机秘钥
GET {{baseUrl}}/asset/host-key/list?idList=1,2,3
Authorization: {{token}}
### 查询主机秘钥
POST {{baseUrl}}/asset/host-key/list-all
Content-Type: application/json
@@ -69,24 +63,4 @@ Authorization: {{token}}
DELETE {{baseUrl}}/asset/host-key/delete?id=1
Authorization: {{token}}
### 通过 id 批量删除主机秘钥
DELETE {{baseUrl}}/asset/host-key/delete-batch?idList=1,2,3
Authorization: {{token}}
### 导出主机秘钥
POST {{baseUrl}}/asset/host-key/export
Content-Type: application/json
Authorization: {{token}}
{
"id": "",
"name": "",
"publicKey": "",
"privateKey": "",
"password": ""
}
###

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.constant.IgnoreLogMode;
import com.orion.ops.framework.common.valid.group.Page;
import com.orion.ops.module.asset.service.*;
import com.orion.ops.module.asset.entity.vo.*;
import com.orion.ops.module.asset.entity.request.host.*;
import com.orion.ops.module.asset.entity.export.*;
import com.orion.ops.module.asset.convert.*;
import com.orion.ops.module.asset.entity.request.host.HostKeyCreateRequest;
import com.orion.ops.module.asset.entity.request.host.HostKeyQueryRequest;
import com.orion.ops.module.asset.entity.request.host.HostKeyUpdateRequest;
import com.orion.ops.module.asset.entity.vo.HostKeyVO;
import com.orion.ops.module.asset.service.HostKeyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
@@ -58,28 +56,19 @@ public class HostKeyController {
@IgnoreLog(IgnoreLogMode.RET)
@GetMapping("/get")
@Operation(summary = "通过 id 查询主机秘钥")
@Operation(summary = "查询主机秘钥详情")
@Parameter(name = "id", description = "id", required = true)
@PreAuthorize("@ss.hasPermission('asset:host-key:query')")
@PreAuthorize("@ss.hasPermission('asset:host-key:detail')")
public HostKeyVO getHostKey(@RequestParam("id") Long id) {
return hostKeyService.getHostKeyById(id);
}
@IgnoreLog(IgnoreLogMode.RET)
@GetMapping("/list")
@Operation(summary = "通过 id 批量查询主机秘钥")
@Parameter(name = "idList", description = "idList", required = true)
@PreAuthorize("@ss.hasPermission('asset:host-key:query')")
public List<HostKeyVO> getHostKeyList(@RequestParam("idList") List<Long> idList) {
return hostKeyService.getHostKeyByIdList(idList);
}
@IgnoreLog(IgnoreLogMode.RET)
@PostMapping("/list-all")
@Operation(summary = "查询主机秘钥")
@PreAuthorize("@ss.hasPermission('asset:host-key:query')")
public List<HostKeyVO> getHostKeyListAll(@Validated @RequestBody HostKeyQueryRequest request) {
return hostKeyService.getHostKeyList(request);
public List<HostKeyVO> getHostKeyListAll() {
return hostKeyService.getHostKeyList();
}
@IgnoreLog(IgnoreLogMode.RET)
@@ -98,21 +87,5 @@ public class HostKeyController {
return hostKeyService.deleteHostKeyById(id);
}
@DeleteMapping("/delete-batch")
@Operation(summary = "通过 id 批量删除主机秘钥")
@Parameter(name = "idList", description = "idList", required = true)
@PreAuthorize("@ss.hasPermission('asset:host-key:delete')")
public Integer batchDeleteHostKey(@RequestParam("idList") List<Long> idList) {
return hostKeyService.batchDeleteHostKeyByIdList(idList);
}
@PostMapping("/export")
@Operation(summary = "导出主机秘钥")
@PreAuthorize("@ss.hasPermission('asset:host-key:export')")
public void exportHostKey(@Validated @RequestBody HostKeyQueryRequest request,
HttpServletResponse response) throws IOException {
hostKeyService.exportHostKey(request, response);
}
}

View File

@@ -1,10 +1,11 @@
package com.orion.ops.module.asset.convert;
import com.orion.ops.module.asset.entity.domain.*;
import com.orion.ops.module.asset.entity.vo.*;
import com.orion.ops.module.asset.entity.request.host.*;
import com.orion.ops.module.asset.entity.export.*;
import com.orion.ops.module.asset.convert.*;
import com.orion.ops.module.asset.entity.domain.HostKeyDO;
import com.orion.ops.module.asset.entity.dto.HostKeyCacheDTO;
import com.orion.ops.module.asset.entity.request.host.HostKeyCreateRequest;
import com.orion.ops.module.asset.entity.request.host.HostKeyQueryRequest;
import com.orion.ops.module.asset.entity.request.host.HostKeyUpdateRequest;
import com.orion.ops.module.asset.entity.vo.HostKeyVO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@@ -30,7 +31,9 @@ public interface HostKeyConvert {
HostKeyVO to(HostKeyDO domain);
HostKeyExport toExport(HostKeyDO domain);
HostKeyVO to(HostKeyCacheDTO cache);
HostKeyCacheDTO toCache(HostKeyDO domain);
List<HostKeyVO> to(List<HostKeyDO> list);

View File

@@ -0,0 +1,25 @@
package com.orion.ops.module.asset.define;
import com.orion.lang.define.cache.CacheKeyBuilder;
import com.orion.lang.define.cache.CacheKeyDefine;
import com.orion.ops.module.asset.entity.dto.HostKeyCacheDTO;
import java.util.concurrent.TimeUnit;
/**
* 主机服务缓存 key
*
* @author Jiahang Li
* @version 1.0.0
* @since 2023/9/20 13:54
*/
public interface HostCacheKeyDefine {
CacheKeyDefine HOST_KEY = new CacheKeyBuilder()
.key("host:key:list")
.desc("主机秘钥列表")
.type(HostKeyCacheDTO.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/20 13:55
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(name = "HostKeyCacheDTO", description = "主机秘钥缓存")
public class HostKeyCacheDTO 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 = HostKeyExport.TITLE)
@ExportSheet(name = "主机秘钥", filterHeader = true, freezeHeader = true, indexToSort = true)
@Schema(name = "HostKeyExport", description = "主机秘钥导出对象")
public class HostKeyExport 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 publicKey;
@Schema(description = "私钥文本")
@ExportField(index = 3, header = "私钥文本", width = 16)
private String privateKey;
@Schema(description = "密码")
@ExportField(index = 4, header = "密码", width = 16)
private String password;
@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

@@ -29,7 +29,6 @@ public class HostKeyCreateRequest implements Serializable {
@Schema(description = "名称")
private String name;
@NotBlank
@Size(max = 65535)
@Schema(description = "公钥文本")
private String publicKey;
@@ -39,7 +38,6 @@ public class HostKeyCreateRequest implements Serializable {
@Schema(description = "私钥文本")
private String privateKey;
@NotBlank
@Size(max = 512)
@Schema(description = "密码")
private String password;

View File

@@ -28,16 +28,4 @@ public class HostKeyQueryRequest extends PageRequest {
@Schema(description = "名称")
private String name;
@Size(max = 65535)
@Schema(description = "公钥文本")
private String publicKey;
@Size(max = 65535)
@Schema(description = "私钥文本")
private String privateKey;
@Size(max = 512)
@Schema(description = "密码")
private String password;
}

View File

@@ -34,7 +34,6 @@ public class HostKeyUpdateRequest implements Serializable {
@Schema(description = "名称")
private String name;
@NotBlank
@Size(max = 65535)
@Schema(description = "公钥文本")
private String publicKey;
@@ -44,7 +43,6 @@ public class HostKeyUpdateRequest implements Serializable {
@Schema(description = "私钥文本")
private String privateKey;
@NotBlank
@Size(max = 512)
@Schema(description = "密码")
private String password;

View File

@@ -1,10 +1,13 @@
package com.orion.ops.module.asset.entity.vo;
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.util.*;
import java.util.Date;
/**
* 主机秘钥 视图响应对象
@@ -34,19 +37,10 @@ public class HostKeyVO implements Serializable {
@Schema(description = "私钥文本")
private String privateKey;
@Schema(description = "密码")
private String password;
@Schema(description = "创建时间")
private Date createTime;
@Schema(description = "修改时间")
private Date updateTime;
@Schema(description = "创建人")
private String creator;
@Schema(description = "修改人")
private String updater;
}

View File

@@ -1,13 +1,12 @@
package com.orion.ops.module.asset.service;
import com.orion.lang.define.wrapper.DataGrid;
import com.orion.ops.module.asset.entity.vo.*;
import com.orion.ops.module.asset.entity.request.host.*;
import com.orion.ops.module.asset.entity.export.*;
import com.orion.ops.module.asset.convert.*;
import com.orion.ops.module.asset.entity.domain.HostKeyDO;
import com.orion.ops.module.asset.entity.request.host.HostKeyCreateRequest;
import com.orion.ops.module.asset.entity.request.host.HostKeyQueryRequest;
import com.orion.ops.module.asset.entity.request.host.HostKeyUpdateRequest;
import com.orion.ops.module.asset.entity.vo.HostKeyVO;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
@@ -35,15 +34,6 @@ public interface HostKeyService {
*/
Integer updateHostKeyById(HostKeyUpdateRequest request);
/**
* 更新主机秘钥
*
* @param query query
* @param update update
* @return effect
*/
Integer updateHostKey(HostKeyQueryRequest query, HostKeyUpdateRequest update);
/**
* 通过 id 查询主机秘钥
*
@@ -53,28 +43,19 @@ public interface HostKeyService {
HostKeyVO getHostKeyById(Long id);
/**
* 通过 id 批量查询主机秘钥
* 通过 id 查询主机秘钥
*
* @param idList idList
* @return rows
* @param id id
* @return row
*/
List<HostKeyVO> getHostKeyByIdList(List<Long> idList);
HostKeyDO getHostKey(Long id);
/**
* 查询主机秘钥
*
* @param request request
* @return rows
*/
List<HostKeyVO> getHostKeyList(HostKeyQueryRequest request);
/**
* 查询主机秘钥数量
*
* @param request request
* @return count
*/
Long getHostKeyCount(HostKeyQueryRequest request);
List<HostKeyVO> getHostKeyList();
/**
* 分页查询主机秘钥
@@ -92,29 +73,4 @@ public interface HostKeyService {
*/
Integer deleteHostKeyById(Long id);
/**
* 通过 id 批量删除主机秘钥
*
* @param idList idList
* @return effect
*/
Integer batchDeleteHostKeyByIdList(List<Long> idList);
/**
* 删除主机秘钥
*
* @param request request
* @return effect
*/
Integer deleteHostKey(HostKeyQueryRequest request);
/**
* 导出主机秘钥
*
* @param request request
* @param response response
* @throws IOException IOException
*/
void exportHostKey(HostKeyQueryRequest request, HttpServletResponse response) throws IOException;
}

View File

@@ -3,28 +3,28 @@ package com.orion.ops.module.asset.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.lang.define.wrapper.DataGrid;
import com.orion.lang.utils.collect.Lists;
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.lang.utils.Strings;
import com.orion.ops.framework.common.constant.Const;
import com.orion.ops.framework.common.constant.ErrorMessage;
import com.orion.ops.framework.common.utils.CryptoUtils;
import com.orion.ops.framework.common.utils.Valid;
import com.orion.ops.module.asset.entity.vo.*;
import com.orion.ops.module.asset.entity.request.host.*;
import com.orion.ops.module.asset.entity.export.*;
import com.orion.ops.module.asset.convert.*;
import com.orion.ops.module.asset.entity.domain.HostKeyDO;
import com.orion.ops.framework.redis.core.utils.RedisLists;
import com.orion.ops.module.asset.convert.HostKeyConvert;
import com.orion.ops.module.asset.dao.HostKeyDAO;
import com.orion.ops.module.asset.define.HostCacheKeyDefine;
import com.orion.ops.module.asset.entity.domain.HostKeyDO;
import com.orion.ops.module.asset.entity.dto.HostKeyCacheDTO;
import com.orion.ops.module.asset.entity.request.host.HostKeyCreateRequest;
import com.orion.ops.module.asset.entity.request.host.HostKeyQueryRequest;
import com.orion.ops.module.asset.entity.request.host.HostKeyUpdateRequest;
import com.orion.ops.module.asset.entity.vo.HostKeyVO;
import com.orion.ops.module.asset.service.HostKeyService;
import com.orion.web.servlet.web.Servlets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
/**
* 主机秘钥 服务实现类
@@ -47,10 +47,18 @@ public class HostKeyServiceImpl implements HostKeyService {
HostKeyDO record = HostKeyConvert.MAPPER.to(request);
// 查询数据是否冲突
this.checkHostKeyPresent(record);
String password = record.getPassword();
if (!Strings.isBlank(password)) {
record.setPassword(CryptoUtils.encryptAsString(password));
}
// 插入
int effect = hostKeyDAO.insert(record);
log.info("HostKeyService-createHostKey effect: {}", effect);
return record.getId();
Long id = record.getId();
// 设置缓存
RedisLists.pushJson(HostCacheKeyDefine.HOST_KEY.getKey(), HostKeyConvert.MAPPER.toCache(record));
RedisLists.setExpire(HostCacheKeyDefine.HOST_KEY);
return id;
}
@Override
@@ -64,22 +72,18 @@ public class HostKeyServiceImpl implements HostKeyService {
HostKeyDO updateRecord = HostKeyConvert.MAPPER.to(request);
// 查询数据是否冲突
this.checkHostKeyPresent(updateRecord);
String password = updateRecord.getPassword();
if (!Strings.isBlank(password)) {
updateRecord.setPassword(CryptoUtils.encryptAsString(password));
}
// 更新
int effect = hostKeyDAO.updateById(updateRecord);
log.info("HostKeyService-updateHostKeyById effect: {}", effect);
return effect;
}
@Override
public Integer updateHostKey(HostKeyQueryRequest query, HostKeyUpdateRequest update) {
log.info("HostKeyService.updateHostKey query: {}, update: {}", JSON.toJSONString(query), JSON.toJSONString(update));
// 条件
LambdaQueryWrapper<HostKeyDO> wrapper = this.buildQueryWrapper(query);
// 转换
HostKeyDO updateRecord = HostKeyConvert.MAPPER.to(update);
// 更新
int effect = hostKeyDAO.update(updateRecord, wrapper);
log.info("HostKeyService.updateHostKey effect: {}", effect);
// 设置缓存
if (!record.getName().equals(updateRecord.getName())) {
RedisLists.removeJson(HostCacheKeyDefine.HOST_KEY.getKey(), HostKeyConvert.MAPPER.toCache(record));
RedisLists.pushJson(HostCacheKeyDefine.HOST_KEY.getKey(), HostKeyConvert.MAPPER.toCache(updateRecord));
}
return effect;
}
@@ -93,30 +97,37 @@ public class HostKeyServiceImpl implements HostKeyService {
}
@Override
public List<HostKeyVO> getHostKeyByIdList(List<Long> idList) {
// 查询
List<HostKeyDO> records = hostKeyDAO.selectBatchIds(idList);
if (records.isEmpty()) {
return Lists.empty();
public HostKeyDO getHostKey(Long id) {
HostKeyDO record = hostKeyDAO.selectById(id);
Valid.notNull(record, ErrorMessage.DATA_ABSENT);
String password = record.getPassword();
if (password != null) {
record.setPassword(CryptoUtils.decryptAsString(password));
}
// 转换
return HostKeyConvert.MAPPER.to(records);
return record;
}
@Override
public List<HostKeyVO> getHostKeyList(HostKeyQueryRequest request) {
// 条件
LambdaQueryWrapper<HostKeyDO> wrapper = this.buildQueryWrapper(request);
// 查询
return hostKeyDAO.of(wrapper).list(HostKeyConvert.MAPPER::to);
}
@Override
public Long getHostKeyCount(HostKeyQueryRequest request) {
// 条件
LambdaQueryWrapper<HostKeyDO> wrapper = this.buildQueryWrapper(request);
// 查询
return hostKeyDAO.selectCount(wrapper);
public List<HostKeyVO> getHostKeyList() {
// 查询缓存
List<HostKeyCacheDTO> list = RedisLists.rangeJson(HostCacheKeyDefine.HOST_KEY);
if (list.isEmpty()) {
// 查询数据库
list = hostKeyDAO.of().list(HostKeyConvert.MAPPER::toCache);
// 添加默认值 防止穿透
if (list.isEmpty()) {
list.add(HostKeyCacheDTO.builder()
.id(Const.NONE_ID)
.build());
}
// 设置缓存
RedisLists.pushAllJson(HostCacheKeyDefine.HOST_KEY.getKey(), list);
}
// 删除默认值
return list.stream()
.filter(s -> !s.getId().equals(Const.NONE_ID))
.map(HostKeyConvert.MAPPER::to)
.collect(Collectors.toList());
}
@Override
@@ -124,9 +135,11 @@ public class HostKeyServiceImpl implements HostKeyService {
// 条件
LambdaQueryWrapper<HostKeyDO> wrapper = this.buildQueryWrapper(request);
// 查询
return hostKeyDAO.of(wrapper)
DataGrid<HostKeyVO> dataGrid = hostKeyDAO.of(wrapper)
.page(request)
.dataGrid(HostKeyConvert.MAPPER::to);
dataGrid.forEach(this::toSafe);
return dataGrid;
}
@Override
@@ -137,43 +150,6 @@ public class HostKeyServiceImpl implements HostKeyService {
return effect;
}
@Override
public Integer batchDeleteHostKeyByIdList(List<Long> idList) {
log.info("HostKeyService-batchDeleteHostKeyByIdList idList: {}", idList);
int effect = hostKeyDAO.deleteBatchIds(idList);
log.info("HostKeyService-batchDeleteHostKeyByIdList effect: {}", effect);
return effect;
}
@Override
public Integer deleteHostKey(HostKeyQueryRequest request) {
log.info("HostKeyService.deleteHostKey request: {}", JSON.toJSONString(request));
// 条件
LambdaQueryWrapper<HostKeyDO> wrapper = this.buildQueryWrapper(request);
// 删除
int effect = hostKeyDAO.delete(wrapper);
log.info("HostKeyService.deleteHostKey effect: {}", effect);
return effect;
}
@Override
public void exportHostKey(HostKeyQueryRequest request, HttpServletResponse response) throws IOException {
log.info("HostKeyService.exportHostKey request: {}", JSON.toJSONString(request));
// 条件
LambdaQueryWrapper<HostKeyDO> wrapper = this.buildQueryWrapper(request);
// 查询
List<HostKeyExport> rows = hostKeyDAO.of(wrapper).list(HostKeyConvert.MAPPER::toExport);
log.info("HostKeyService.exportHostKey size: {}", rows.size());
// 导出
ByteArrayOutputStream out = new ByteArrayOutputStream();
ExcelExport.create(HostKeyExport.class)
.addRows(rows)
.write(out)
.close();
// 传输
Servlets.transfer(response, out.toByteArray(), FileNames.exportName(HostKeyExport.TITLE));
}
/**
* 检测对象是否存在
*
@@ -185,10 +161,7 @@ public class HostKeyServiceImpl implements HostKeyService {
// 更新时忽略当前记录
.ne(HostKeyDO::getId, domain.getId())
// 用其他字段做重复校验
.eq(HostKeyDO::getName, domain.getName())
.eq(HostKeyDO::getPublicKey, domain.getPublicKey())
.eq(HostKeyDO::getPrivateKey, domain.getPrivateKey())
.eq(HostKeyDO::getPassword, domain.getPassword());
.eq(HostKeyDO::getName, domain.getName());
// 检查是否存在
boolean present = hostKeyDAO.of(wrapper).present();
Valid.isFalse(present, ErrorMessage.DATA_PRESENT);
@@ -203,10 +176,17 @@ public class HostKeyServiceImpl implements HostKeyService {
private LambdaQueryWrapper<HostKeyDO> buildQueryWrapper(HostKeyQueryRequest request) {
return hostKeyDAO.wrapper()
.eq(HostKeyDO::getId, request.getId())
.eq(HostKeyDO::getName, request.getName())
.eq(HostKeyDO::getPublicKey, request.getPublicKey())
.eq(HostKeyDO::getPrivateKey, request.getPrivateKey())
.eq(HostKeyDO::getPassword, request.getPassword());
.like(HostKeyDO::getName, request.getName());
}
/**
* 删除不安全字段
*
* @param vo vo
*/
public void toSafe(HostKeyVO vo) {
vo.setPublicKey(null);
vo.setPrivateKey(null);
}
}

View File

@@ -110,10 +110,3 @@ export function batchDeleteHostIdentity(idList: Array<number>) {
}
});
}
/**
* 导出主机身份
*/
export function exportHostIdentity(request: HostIdentityQueryRequest) {
return axios.post('/asset/host-identity/export', request);
}

View File

@@ -1,5 +1,4 @@
import axios from 'axios';
import qs from 'query-string';
import { DataGrid, Pagination } from '@/types/global';
/**
@@ -27,7 +26,6 @@ export interface HostKeyQueryRequest extends Pagination {
name?: string;
publicKey?: string;
privateKey?: string;
password?: string;
}
/**
@@ -41,8 +39,6 @@ export interface HostKeyQueryResponse {
password?: string;
createTime: number;
updateTime: number;
creator: string;
updater: string;
}
/**
@@ -66,23 +62,11 @@ export function getHostKey(id: number) {
return axios.get<HostKeyQueryResponse>('/asset/host-key/get', { params: { id } });
}
/**
* 通过 id 批量查询主机秘钥
*/
export function getHostKeyList(idList: Array<number>) {
return axios.get<HostKeyQueryResponse[]>('/asset/host-key/list', {
params: { idList },
paramsSerializer: params => {
return qs.stringify(params, { arrayFormat: 'comma' });
}
});
}
/**
* 查询主机秘钥
*/
export function getHostKeyListAll(request: HostKeyQueryRequest) {
return axios.post<Array<HostKeyQueryResponse>>('/asset/host-key/list-all', request);
export function getHostKeyListAll() {
return axios.post<Array<HostKeyQueryResponse>>('/asset/host-key/list-all');
}
/**
@@ -98,22 +82,3 @@ export function getHostKeyPage(request: HostKeyQueryRequest) {
export function deleteHostKey(id: number) {
return axios.delete('/asset/host-key/delete', { params: { id } });
}
/**
* 通过 id 批量删除主机秘钥
*/
export function batchDeleteHostKey(idList: Array<number>) {
return axios.delete('/asset/host-key/delete-batch', {
params: { idList },
paramsSerializer: params => {
return qs.stringify(params, { arrayFormat: 'comma' });
}
});
}
/**
* 导出主机秘钥
*/
export function exportHostKey(request: HostKeyQueryRequest) {
return axios.post('/asset/host-key/export', request);
}

View File

@@ -8,12 +8,12 @@ export function getBase64Data(e: string) {
}
/**
* 读取文件 base64 返回 promise
* 读取文件内容 返回 promise
*/
export function readFileBase64(e: any) {
export function readFileText(e: File, encoding = 'UTF-8') {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(e);
reader.readAsText(e, encoding);
reader.onload = res => {
resolve(res.target?.result);
};

View File

@@ -0,0 +1,145 @@
<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

@@ -54,8 +54,8 @@
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 {} from '../types/enum.types';
import {} from '../types/const';
import { toOptions } from '@/utils/enum';
const { visible, setVisible } = useVisible();

View File

@@ -119,8 +119,8 @@
import useLoading from '@/hooks/loading';
import columns from '../types/table.columns';
import { defaultPagination, defaultRowSelection } from '@/types/table';
import { } from '../types/enum.types';
import { } from '../types/const';
import {} from '../types/enum.types';
import {} from '../types/const';
import { toOptions } from '@/utils/enum';
const tableRenderData = ref<HostIdentityQueryResponse[]>();

View File

@@ -2,12 +2,13 @@
<div class="layout-container">
<!-- 表格 -->
<host-identity-table ref="table"
@openAdd="() => modal.openAdd()"
@openUpdate="(e) => modal.openUpdate(e)" />
@openAdd="() => drawer.openAdd()"
@openUpdate="(e) => drawer.openUpdate(e)" />
<!-- 添加修改模态框 -->
<host-identity-form-modal ref="modal"
@added="() => table.addedCallback()"
@updated="() => table.updatedCallback()" />
<host-identity-form-drawer ref="drawer"
@added="() => table.addedCallback()"
@updated="() => table.updatedCallback()" />
</div>
</template>
@@ -19,11 +20,12 @@
<script lang="ts" setup>
import HostIdentityTable from './components/host-identity-table.vue';
import HostIdentityFormModal from './components/host-identity-form-modal.vue';
import HostIdentityFormDrawer from './components/host-identity-form-drawer.vue';
import { ref } from 'vue';
const table = ref();
const modal = ref();
const drawer = ref();
</script>

View File

@@ -0,0 +1,186 @@
<template>
<a-drawer :visible="visible"
:title="title"
:width="470"
:mask-closable="false"
:unmount-on-close="true"
:on-before-ok="handlerOk"
@cancel="handleClose">
<a-spin :loading="loading">
<a-alert style="margin-bottom: 18px;">请使用 ssh-keygen -m PEM -t rsa 生成秘钥</a-alert>
<a-form :model="formModel"
ref="formRef"
label-align="right"
:style="{ width: '420px' }"
:label-col-props="{ span: 4 }"
:wrapper-col-props="{ span: 20 }"
:rules="formRules">
<!-- 名称 -->
<a-form-item field="name" label="名称">
<a-input v-model="formModel.name" placeholder="请输入名称" />
</a-form-item>
<!-- 公钥文本 -->
<a-form-item field="publicKey" label="公钥">
<a-upload :auto-upload="false"
:show-file-list="false"
draggable
@change="selectPublicFile"
@click.prevent="() => {}">
<template #upload-button>
<a-textarea v-model="formModel.publicKey"
placeholder="请输入公钥文本或将文件拖拽到此处"
:auto-size="{ minRows: 7, maxRows: 7}" />
</template>
</a-upload>
</a-form-item>
<!-- 私钥文本 -->
<a-form-item field="privateKey" label="私钥">
<a-upload :auto-upload="false"
:show-file-list="false"
draggable
@change="selectPrivateFile"
@click.prevent="() => {}">
<template #upload-button>
<a-textarea v-model="formModel.privateKey"
placeholder="请输入私钥文本或将文件拖拽到此处"
:auto-size="{ minRows: 8, maxRows: 8}" />
</template>
</a-upload>
</a-form-item>
<!-- 密码 -->
<a-form-item field="password" label="密码">
<a-input-password v-model="formModel.password" placeholder="请输入私钥密码" />
</a-form-item>
</a-form>
</a-spin>
</a-drawer>
</template>
<script lang="ts">
export default {
name: 'asset-host-key-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 { createHostKey, updateHostKey, getHostKey } from '@/api/asset/host-key';
import { FileItem, Message } from '@arco-design/web-vue';
import {} from '../types/enum.types';
import {} from '../types/const';
import { readFileText } from '@/utils/file';
const { visible, setVisible } = useVisible();
const { loading, setLoading } = useLoading();
const title = ref<string>();
const isAddHandle = ref<boolean>(true);
const defaultForm = () => {
return {
id: undefined,
name: undefined,
publicKey: undefined,
privateKey: undefined,
password: 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 = async (record: any) => {
title.value = '修改主机秘钥';
isAddHandle.value = false;
setVisible(true);
setLoading(true);
try {
const { data } = await getHostKey(record.id);
renderForm({ ...data });
} catch (e) {
setVisible(false);
} finally {
setLoading(false);
}
};
// 渲染表单
const renderForm = (record: any) => {
Object.keys(formModel).forEach(k => {
formModel[k] = record[k];
});
};
defineExpose({ openAdd, openUpdate });
// 选择公钥文件
const selectPublicFile = async (fileList: FileItem[]) => {
formModel.publicKey = await readFileText(fileList[0].file as File);
formRef.value.clearValidate('publicKey');
};
// 选择私钥文件
const selectPrivateFile = async (fileList: FileItem[]) => {
formModel.privateKey = await readFileText(fileList[0].file as File);
formRef.value.clearValidate('privateKey');
};
// 确定
const handlerOk = async () => {
setLoading(true);
try {
// 验证参数
const error = await formRef.value.validate();
if (error) {
return false;
}
if (isAddHandle.value) {
// 新增
await createHostKey(formModel as any);
Message.success('创建成功');
emits('added');
} else {
// 修改
await updateHostKey(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

@@ -6,24 +6,12 @@
@submit="fetchTableData"
@reset="fetchTableData">
<!-- id -->
<a-form-item field="id" label="id" label-col-flex="50px">
<a-input-number v-model="formModel.id" placeholder="请输入id" allow-clear/>
<a-form-item field="id" label="id" label-col-flex="30px">
<a-input-number v-model="formModel.id" placeholder="请输入id" allow-clear />
</a-form-item>
<!-- 名称 -->
<a-form-item field="name" label="名称" label-col-flex="50px">
<a-input v-model="formModel.name" placeholder="请输入名称" allow-clear/>
</a-form-item>
<!-- 公钥文本 -->
<a-form-item field="publicKey" label="公钥文本" label-col-flex="50px">
<a-input v-model="formModel.publicKey" placeholder="请输入公钥文本" allow-clear/>
</a-form-item>
<!-- 私钥文本 -->
<a-form-item field="privateKey" label="私钥文本" label-col-flex="50px">
<a-input v-model="formModel.privateKey" placeholder="请输入私钥文本" allow-clear/>
</a-form-item>
<!-- 密码 -->
<a-form-item field="password" label="密码" label-col-flex="50px">
<a-input v-model="formModel.password" placeholder="请输入密码" allow-clear/>
<a-form-item field="name" label="名称" label-col-flex="30px">
<a-input v-model="formModel.name" placeholder="请输入名称" allow-clear />
</a-form-item>
</a-query-header>
</a-card>
@@ -46,21 +34,6 @@
<icon-plus />
</template>
</a-button>
<!-- 删除 -->
<a-popconfirm position="br"
type="warning"
:content="`确认删除选中的${selectedKeys.length}条记录吗?`"
@ok="deleteSelectRows">
<a-button v-permission="['asset:host-key:delete']"
type="secondary"
status="danger"
:disabled="selectedKeys.length === 0">
删除
<template #icon>
<icon-delete />
</template>
</a-button>
</a-popconfirm>
</a-space>
</div>
</template>
@@ -71,8 +44,6 @@
label-align="left"
:loading="loading"
:columns="columns"
v-model:selectedKeys="selectedKeys"
:row-selection="rowSelection"
:data="tableRenderData"
:pagination="pagination"
@page-change="(page) => fetchTableData(page, pagination.pageSize)"
@@ -114,13 +85,13 @@
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { batchDeleteHostKey, deleteHostKey, getHostKeyPage, HostKeyQueryRequest, HostKeyQueryResponse } from '@/api/asset/host-key';
import { deleteHostKey, getHostKeyPage, HostKeyQueryRequest, HostKeyQueryResponse } from '@/api/asset/host-key';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import columns from '../types/table.columns';
import { defaultPagination, defaultRowSelection } from '@/types/table';
import { } from '../types/enum.types';
import { } from '../types/const';
import { defaultPagination } from '@/types/table';
import {} from '../types/enum.types';
import {} from '../types/const';
import { toOptions } from '@/utils/enum';
const tableRenderData = ref<HostKeyQueryResponse[]>();
@@ -128,8 +99,6 @@
const emits = defineEmits(['openAdd', 'openUpdate']);
const pagination = reactive(defaultPagination());
const selectedKeys = ref<number[]>([]);
const rowSelection = reactive(defaultRowSelection());
const formModel = reactive<HostKeyQueryRequest>({
id: undefined,
@@ -139,21 +108,6 @@
password: undefined,
});
// 删除选中行
const deleteSelectRows = async () => {
try {
setLoading(true);
// 调用删除接口
await batchDeleteHostKey(selectedKeys.value);
Message.success(`成功删除${selectedKeys.value.length}条数据`);
selectedKeys.value = [];
// 重新加载数据
await fetchTableData();
} finally {
setLoading(false);
}
};
// 删除当前行
const deleteRow = async ({ id }: { id: number }) => {
try {

View File

@@ -2,10 +2,10 @@
<div class="layout-container">
<!-- 表格 -->
<host-key-table ref="table"
@openAdd="() => modal.openAdd()"
@openUpdate="(e) => modal.openUpdate(e)" />
@openAdd="() => drawer.openAdd()"
@openUpdate="(e) => drawer.openUpdate(e)" />
<!-- 添加修改模态框 -->
<host-key-form-modal ref="modal"
<host-key-form-drawer ref="drawer"
@added="() => table.addedCallback()"
@updated="() => table.updatedCallback()" />
</div>
@@ -19,11 +19,11 @@
<script lang="ts" setup>
import HostKeyTable from './components/host-key-table.vue';
import HostKeyFormModal from './components/host-key-form-modal.vue';
import HostKeyFormDrawer from './components/host-key-form-drawer.vue';
import { ref } from 'vue';
const table = ref();
const modal = ref();
const drawer = ref();
</script>

View File

@@ -8,33 +8,18 @@ export const name = [{
message: '名称长度不能大于64位'
}] as FieldRule[];
export const publicKey = [{
required: true,
message: '请输入公钥文本'
}, {
maxLength: 65535,
message: '公钥文本长度不能大于65535位'
}] as FieldRule[];
export const privateKey = [{
required: true,
message: '请输入私钥文本'
}, {
maxLength: 65535,
message: '私钥文本长度不能大于65535位'
}] as FieldRule[];
export const password = [{
required: true,
message: '请输入密码'
}, {
maxLength: 512,
message: '密码长度不能大于512位'
}] as FieldRule[];
export default {
name,
publicKey,
privateKey,
password,
} as Record<string, FieldRule | FieldRule[]>;

View File

@@ -6,43 +6,18 @@ const columns = [
title: 'id',
dataIndex: 'id',
slotName: 'id',
width: 70,
width: 100,
align: 'left',
fixed: 'left',
}, {
title: '名称',
dataIndex: 'name',
slotName: 'name',
align: 'center',
ellipsis: true,
tooltip: true,
}, {
title: '公钥文本',
dataIndex: 'publicKey',
slotName: 'publicKey',
align: 'center',
ellipsis: true,
tooltip: true,
}, {
title: '私钥文本',
dataIndex: 'privateKey',
slotName: 'privateKey',
align: 'center',
ellipsis: true,
tooltip: true,
}, {
title: '密码',
dataIndex: 'password',
slotName: 'password',
align: 'center',
ellipsis: true,
tooltip: true,
}, {
title: '创建时间',
dataIndex: 'createTime',
slotName: 'createTime',
align: 'center',
width: 180,
render: ({ record }) => {
return dateFormat(new Date(record.createTime));
},
@@ -51,18 +26,9 @@ const columns = [
dataIndex: 'updateTime',
slotName: 'updateTime',
align: 'center',
width: 180,
render: ({ record }) => {
return dateFormat(new Date(record.updateTime));
},
}, {
title: '创建人',
dataIndex: 'creator',
slotName: 'creator',
}, {
title: '修改人',
dataIndex: 'updater',
slotName: 'updater',
}, {
title: '操作',
slotName: 'handle',