Files
dsapi_pub/src/main/java/com/dsapi/service/ApiKeyService.java
T
2026-12-05 18:03:58 +08:00

174 lines
6.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.dsapi.service;
import com.dsapi.constant.ErrorCodes;
import com.dsapi.constant.LogActions;
import com.dsapi.dto.ApiKeyView;
import com.dsapi.dto.CreateApiKeyRequest;
import com.dsapi.entity.BizApiKey;
import com.dsapi.entity.SysUser;
import com.dsapi.enums.RoleType;
import com.dsapi.exception.BusinessException;
import com.dsapi.repository.BizApiKeyRepository;
import com.dsapi.repository.SysUserRepository;
import com.dsapi.security.AuthContext;
import com.dsapi.util.ApiKeyGenerator;
import com.dsapi.util.ApiKeyMasker;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* API Key 管理(创建明文仅一次;列表掩码;硬删除)。
*/
@Service
public class ApiKeyService {
private final BizApiKeyRepository bizApiKeyRepository;
private final SysUserRepository sysUserRepository;
private final OperationLogService operationLogService;
public ApiKeyService(BizApiKeyRepository bizApiKeyRepository,
SysUserRepository sysUserRepository,
OperationLogService operationLogService) {
this.bizApiKeyRepository = bizApiKeyRepository;
this.sysUserRepository = sysUserRepository;
this.operationLogService = operationLogService;
}
@Transactional
public ApiKeyView create(CreateApiKeyRequest request) {
SysUser operator = AuthContext.getUser();
if (operator == null) {
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "未登录");
}
String keyName = request.getName() == null ? "" : request.getName().trim();
if (keyName.isEmpty()) {
throw new BusinessException(ErrorCodes.PARAM_INVALID, "备注名不能为空");
}
if (keyName.length() > 64) {
throw new BusinessException(ErrorCodes.PARAM_INVALID, "备注名长度须为 1~64");
}
Long ownerId = resolveOwnerId(operator, request.getOwnerUserId());
String rawKey = generateUniqueKey();
BizApiKey entity = new BizApiKey();
entity.setUserId(ownerId);
entity.setKeyName(keyName);
entity.setApiKey(rawKey);
entity.setCreateUser(operator.getId());
entity.setUpdateUser(operator.getId());
BizApiKey saved = bizApiKeyRepository.save(entity);
Map<String, Object> after = new HashMap<>();
after.put("id", saved.getId());
after.put("userId", saved.getUserId());
after.put("keyName", saved.getKeyName());
after.put("apiKey", ApiKeyMasker.mask(rawKey));
operationLogService.record(LogActions.BIZ_API_KEY, saved.getId(), LogActions.CREATE, null, after, operator.getId());
ApiKeyView view = toMaskedView(saved);
view.setApiKey(rawKey);
return view;
}
public List<ApiKeyView> list(Long ownerUserId) {
SysUser operator = AuthContext.getUser();
if (operator == null) {
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "未登录");
}
Long queryUserId = resolveListOwner(operator, ownerUserId);
return bizApiKeyRepository.findByUserIdOrderByIdDesc(queryUserId)
.stream()
.map(this::toMaskedView)
.collect(Collectors.toList());
}
@Transactional
public void hardDelete(Long apiKeyId) {
SysUser operator = AuthContext.getUser();
if (operator == null) {
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "未登录");
}
BizApiKey key = bizApiKeyRepository.findById(apiKeyId)
.orElseThrow(() -> new BusinessException(ErrorCodes.NOT_FOUND, "API Key 不存在"));
assertCanManageKey(operator, key.getUserId());
Map<String, Object> before = new HashMap<>();
before.put("id", key.getId());
before.put("userId", key.getUserId());
before.put("keyName", key.getKeyName());
before.put("apiKey", ApiKeyMasker.mask(key.getApiKey()));
bizApiKeyRepository.delete(key);
operationLogService.record(LogActions.BIZ_API_KEY, apiKeyId, LogActions.DELETE, before, null, operator.getId());
}
public BizApiKey requireValidKey(String apiKey) {
if (apiKey == null || apiKey.isBlank()) {
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "缺少 API Key");
}
return bizApiKeyRepository.findByApiKey(apiKey.trim())
.orElseThrow(() -> new BusinessException(ErrorCodes.UNAUTHORIZED, "API Key 无效"));
}
private Long resolveOwnerId(SysUser operator, Long ownerUserId) {
int role = operator.getRoleType();
if (role == RoleType.USER.getCode()) {
if (ownerUserId != null && !ownerUserId.equals(operator.getId())) {
throw new BusinessException(ErrorCodes.FORBIDDEN, "普通用户只能为自己创建 API Key");
}
return operator.getId();
}
if (ownerUserId == null) {
return operator.getId();
}
sysUserRepository.findByIdAndDeleteFlag(ownerUserId, LogActions.DELETE_FLAG_NORMAL)
.orElseThrow(() -> new BusinessException(ErrorCodes.NOT_FOUND, "目标用户不存在"));
return ownerUserId;
}
private Long resolveListOwner(SysUser operator, Long ownerUserId) {
if (operator.getRoleType() == RoleType.USER.getCode()) {
return operator.getId();
}
if (ownerUserId == null) {
return operator.getId();
}
return ownerUserId;
}
private void assertCanManageKey(SysUser operator, Long ownerUserId) {
int role = operator.getRoleType();
if (role == RoleType.SUPER_ADMIN.getCode() || role == RoleType.ADMIN.getCode()) {
return;
}
if (!operator.getId().equals(ownerUserId)) {
throw new BusinessException(ErrorCodes.FORBIDDEN, "无权删除他人 API Key");
}
}
private String generateUniqueKey() {
for (int i = 0; i < 20; i++) {
String key = ApiKeyGenerator.generate();
if (bizApiKeyRepository.findByApiKey(key).isEmpty()) {
return key;
}
}
throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "生成 API Key 失败,请重试");
}
private ApiKeyView toMaskedView(BizApiKey entity) {
ApiKeyView view = new ApiKeyView();
view.setId(entity.getId());
view.setUserId(entity.getUserId());
view.setName(entity.getKeyName());
view.setKeyMask(ApiKeyMasker.mask(entity.getApiKey()));
view.setCreateTime(entity.getCreateTime());
return view;
}
}