XuqmGroup-Server/tenant-service/src/main/java/com/xuqm/tenant/service/AppService.java

86 行
2.8 KiB
Java

2026-04-21 22:07:29 +08:00
package com.xuqm.tenant.service;
import com.xuqm.common.exception.BusinessException;
import com.xuqm.tenant.dto.CreateAppRequest;
import com.xuqm.tenant.entity.AppEntity;
import com.xuqm.tenant.repository.AppRepository;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
@Service
public class AppService {
private final AppRepository appRepository;
private static final SecureRandom random = new SecureRandom();
public AppService(AppRepository appRepository) {
this.appRepository = appRepository;
}
public List<AppEntity> listByTenant(String tenantId) {
return appRepository.findByTenantId(tenantId);
}
public AppEntity getById(String id, String tenantId) {
AppEntity app = appRepository.findById(id)
.orElseThrow(() -> new BusinessException(404, "应用不存在"));
if (!app.getTenantId().equals(tenantId)) {
throw new BusinessException(403, "无权访问该应用");
}
return app;
}
public AppEntity create(String tenantId, CreateAppRequest req) {
if (appRepository.existsByPackageNameAndTenantId(req.packageName(), tenantId)) {
throw new BusinessException("该包名下已存在同名应用");
}
AppEntity app = new AppEntity();
app.setId(UUID.randomUUID().toString());
app.setTenantId(tenantId);
app.setPackageName(req.packageName());
app.setName(req.name());
app.setDescription(req.description());
app.setIconUrl(req.iconUrl());
app.setAppKey(generateAppKey());
app.setAppSecret(generateSecret());
app.setCreatedAt(LocalDateTime.now());
return appRepository.save(app);
}
public AppEntity update(String id, String tenantId, CreateAppRequest req) {
AppEntity app = getById(id, tenantId);
app.setName(req.name());
app.setDescription(req.description());
app.setIconUrl(req.iconUrl());
return appRepository.save(app);
}
public void delete(String id, String tenantId) {
AppEntity app = getById(id, tenantId);
appRepository.delete(app);
}
public String resetSecret(String id, String tenantId) {
AppEntity app = getById(id, tenantId);
String newSecret = generateSecret();
app.setAppSecret(newSecret);
appRepository.save(app);
return newSecret;
}
2026-04-21 22:07:29 +08:00
private String generateAppKey() {
return "ak_" + UUID.randomUUID().toString().replace("-", "").substring(0, 24);
}
private String generateSecret() {
byte[] bytes = new byte[32];
random.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
}