65 行
2.5 KiB
Java
65 行
2.5 KiB
Java
|
|
package com.xuqm.tenant.service;
|
||
|
|
|
||
|
|
import com.xuqm.common.exception.BusinessException;
|
||
|
|
import com.xuqm.tenant.entity.FeatureServiceEntity;
|
||
|
|
import com.xuqm.tenant.repository.FeatureServiceRepository;
|
||
|
|
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 FeatureServiceManager {
|
||
|
|
|
||
|
|
private final FeatureServiceRepository repository;
|
||
|
|
private static final SecureRandom random = new SecureRandom();
|
||
|
|
|
||
|
|
public FeatureServiceManager(FeatureServiceRepository repository) {
|
||
|
|
this.repository = repository;
|
||
|
|
}
|
||
|
|
|
||
|
|
public List<FeatureServiceEntity> listByApp(String appId) {
|
||
|
|
return repository.findByAppId(appId);
|
||
|
|
}
|
||
|
|
|
||
|
|
public FeatureServiceEntity toggle(String appId, FeatureServiceEntity.Platform platform,
|
||
|
|
FeatureServiceEntity.ServiceType serviceType, boolean enable) {
|
||
|
|
FeatureServiceEntity entity = repository
|
||
|
|
.findByAppIdAndPlatformAndServiceType(appId, platform, serviceType)
|
||
|
|
.orElseGet(() -> {
|
||
|
|
FeatureServiceEntity e = new FeatureServiceEntity();
|
||
|
|
e.setId(UUID.randomUUID().toString());
|
||
|
|
e.setAppId(appId);
|
||
|
|
e.setPlatform(platform);
|
||
|
|
e.setServiceType(serviceType);
|
||
|
|
e.setSecretKey(generateSecretKey());
|
||
|
|
e.setCreatedAt(LocalDateTime.now());
|
||
|
|
return e;
|
||
|
|
});
|
||
|
|
entity.setEnabled(enable);
|
||
|
|
return repository.save(entity);
|
||
|
|
}
|
||
|
|
|
||
|
|
public FeatureServiceEntity getOrFail(String appId, FeatureServiceEntity.Platform platform,
|
||
|
|
FeatureServiceEntity.ServiceType serviceType) {
|
||
|
|
return repository.findByAppIdAndPlatformAndServiceType(appId, platform, serviceType)
|
||
|
|
.orElseThrow(() -> new BusinessException(404, "服务未配置"));
|
||
|
|
}
|
||
|
|
|
||
|
|
public FeatureServiceEntity regenerateKey(String id) {
|
||
|
|
FeatureServiceEntity entity = repository.findById(id)
|
||
|
|
.orElseThrow(() -> new BusinessException(404, "服务不存在"));
|
||
|
|
entity.setSecretKey(generateSecretKey());
|
||
|
|
return repository.save(entity);
|
||
|
|
}
|
||
|
|
|
||
|
|
private String generateSecretKey() {
|
||
|
|
byte[] bytes = new byte[32];
|
||
|
|
random.nextBytes(bytes);
|
||
|
|
return "sk_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||
|
|
}
|
||
|
|
}
|