refactor all
This commit is contained in:
@@ -1,84 +0,0 @@
|
||||
package com.imyeyu.api.util;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* AES 加解密
|
||||
*
|
||||
* @author 夜雨
|
||||
* @version 2021-08-11 00:52
|
||||
*/
|
||||
@Component
|
||||
public class AES {
|
||||
|
||||
/**
|
||||
* 生产密钥
|
||||
*
|
||||
* @return 密钥
|
||||
* @throws Exception 生产异常
|
||||
*/
|
||||
public byte[] initKey() throws Exception {
|
||||
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
|
||||
keyGen.init(256);
|
||||
return keyGen.generateKey().getEncoded();
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密字符串
|
||||
*
|
||||
* @param data 待加密字符串
|
||||
* @param key 密钥
|
||||
* @return 加密结果
|
||||
* @throws Exception 加密异常
|
||||
*/
|
||||
public byte[] encrypt(String data, byte[] key) throws Exception {
|
||||
return encrypt(data.getBytes(), key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密
|
||||
*
|
||||
* @param data 待加密字节数据
|
||||
* @param key 密钥
|
||||
* @return 加密结果
|
||||
* @throws Exception 加密异常
|
||||
*/
|
||||
public byte[] encrypt(byte[] data, byte[] key) throws Exception {
|
||||
SecretKey secretKey = new SecretKeySpec(key, "AES");
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey); // 密钥
|
||||
return cipher.doFinal(data); // 加密返回
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密字符串
|
||||
*
|
||||
* @param data 待解密字节数据
|
||||
* @param key 密钥
|
||||
* @return 解密结果
|
||||
* @throws Exception 解密异常
|
||||
*/
|
||||
public byte[] decrypt(String data, byte[] key) throws Exception {
|
||||
return decrypt(data.getBytes(), key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
*
|
||||
* @param data 待解密字节数据
|
||||
* @param key 密钥
|
||||
* @return 解密结果
|
||||
* @throws Exception 解密异常
|
||||
*/
|
||||
public byte[] decrypt(byte[] data, byte[] key) throws Exception {
|
||||
SecretKey secretKey = new SecretKeySpec(key, "AES");
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey);
|
||||
return cipher.doFinal(data);
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,17 @@ package com.imyeyu.api.util;
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.timi.TimiCode;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.api.bean.CaptchaFrom;
|
||||
import com.imyeyu.spring.TimiSpring;
|
||||
import com.imyeyu.spring.util.Redis;
|
||||
import com.imyeyu.utils.Calc;
|
||||
import com.imyeyu.utils.Encoder;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.AlphaComposite;
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
@@ -19,6 +22,9 @@ import java.awt.Graphics2D;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.geom.QuadCurve2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 验证码绘制
|
||||
@@ -28,15 +34,13 @@ import java.awt.image.BufferedImage;
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class CaptchaManager {
|
||||
|
||||
/** 会话频率限制时间,毫秒 */
|
||||
private static final int LOCK_TIME = 1000;
|
||||
|
||||
/** 会话频率限制键,插值会话 ID */
|
||||
private static final String LOCK_KEY = "CAPTCHA:LOCK:%s";
|
||||
|
||||
/** 会话值缓存键,插值验证码来源 */
|
||||
/** 会话值缓存键,插值唯一 ID */
|
||||
private static final String CACHE_KEY = "CAPTCHA:%s";
|
||||
|
||||
/** 绘制字符,移除 O,o,I,l */
|
||||
@@ -49,20 +53,22 @@ public class CaptchaManager {
|
||||
@Value("${spring.profiles.active}")
|
||||
private String env;
|
||||
|
||||
private final Redis<String, String> redisCaptcha;
|
||||
|
||||
public BufferedImage generate(CaptchaFrom from, int width, int height) throws InterruptedException {
|
||||
return generate(from, 4, width, height);
|
||||
public Result generate(int width, int height) {
|
||||
return generate(width, height, 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成并缓存验证码
|
||||
*
|
||||
* @param from 来自模块
|
||||
* @param width 宽度
|
||||
* @param height 高度
|
||||
* @param length 长度
|
||||
* @return 图片流
|
||||
*/
|
||||
public BufferedImage generate(CaptchaFrom from, int length, int width, int height) throws InterruptedException {
|
||||
public Result generate(int width, int height, int length) {
|
||||
long lockTime = 1000;
|
||||
// 加锁
|
||||
String lockKey = LOCK_KEY.formatted(TimiSpring.getSession().getId());
|
||||
Long lockAt = TimiSpring.getSessionAttr(lockKey, Long.class);
|
||||
@@ -70,17 +76,22 @@ public class CaptchaManager {
|
||||
TimiSpring.setSessionAttr(lockKey, Time.now());
|
||||
if (lockAt != null) {
|
||||
long diff = Time.now() - lockAt;
|
||||
if (diff < LOCK_TIME) {
|
||||
if (diff < lockTime) {
|
||||
// 限制频率
|
||||
synchronized (this) {
|
||||
wait(LOCK_TIME - diff);
|
||||
try {
|
||||
wait(lockTime - diff);
|
||||
} catch (InterruptedException e) {
|
||||
log.error("lock error", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int fontWidth = width / 4;
|
||||
int fontSize = (int) (height * .8);
|
||||
int yOffset = (int) (height * .2);
|
||||
int fontWidth = (int) (width * .9 / 4);
|
||||
int fontSize = (int) (height * .7);
|
||||
int yOffset = (int) (height * .4);
|
||||
StringBuilder value = new StringBuilder();
|
||||
|
||||
// 图片流
|
||||
@@ -139,9 +150,19 @@ public class CaptchaManager {
|
||||
g.draw(curve);
|
||||
}
|
||||
}
|
||||
// 写入缓存
|
||||
TimiSpring.setSessionAttr(CACHE_KEY.formatted(from), value.toString());
|
||||
return image;
|
||||
|
||||
try {
|
||||
String uniqueId = UUID.randomUUID().toString();
|
||||
// 写入缓存
|
||||
redisCaptcha.set(CACHE_KEY.formatted(uniqueId), value.toString(), Time.parseToMS("3m"));
|
||||
|
||||
// 返回
|
||||
ByteArrayOutputStream os = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, "png", os);
|
||||
return new Result(uniqueId, "data:image/png;base64," + Encoder.base64(os.toByteArray()));
|
||||
} catch (IOException e) {
|
||||
throw new TimiException(TimiCode.ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return 错误回调图像 */
|
||||
@@ -158,30 +179,40 @@ public class CaptchaManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>验证。通过验证不抛出任何异常也不返回任何内容,否则抛出相应异常
|
||||
* <p>会验证非空和期限
|
||||
* <p>测试环境总是通过验证
|
||||
* 验证
|
||||
*
|
||||
* @param captcha 提交的验证码
|
||||
* @param from 来自模块
|
||||
* <ul>
|
||||
* <li>通过验证不抛出任何异常也不返回任何内容,否则抛出相应异常</li>
|
||||
* <li>会验证非空和期限</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param uniqueId 唯一识别 ID
|
||||
* @param value 提交的验证码
|
||||
* @throws TimiException 验证异常
|
||||
*/
|
||||
public void test(String captcha, String from) {
|
||||
if (TimiJava.isEmpty(captcha)) {
|
||||
throw new TimiException(TimiCode.ARG_MISS).msgKey("captcha.miss");
|
||||
public void verify(String uniqueId, String value) {
|
||||
if (TimiJava.isEmpty(value)) {
|
||||
throw new TimiException(TimiCode.ARG_MISS, "not found value");
|
||||
}
|
||||
if (env.startsWith("dev")) {
|
||||
return;
|
||||
}
|
||||
// Session 验证
|
||||
String sessionCaptcha = TimiSpring.getSessionAttrAsString(CACHE_KEY.formatted(from));
|
||||
if (TimiJava.isEmpty(sessionCaptcha)) {
|
||||
String cacheKey = CACHE_KEY.formatted(uniqueId);
|
||||
String cacheValue = redisCaptcha.get(cacheKey);
|
||||
if (TimiJava.isEmpty(cacheValue)) {
|
||||
throw new TimiException(TimiCode.ARG_EXPIRED).msgKey("captcha.expire");
|
||||
}
|
||||
if (!captcha.trim().equalsIgnoreCase(sessionCaptcha)) {
|
||||
if (!value.trim().equalsIgnoreCase(cacheValue)) {
|
||||
throw new TimiException(TimiCode.RESULT_BAD).msgKey("captcha.error");
|
||||
}
|
||||
// 清除缓存
|
||||
TimiSpring.removeSessionAttr(CACHE_KEY.formatted(from));
|
||||
redisCaptcha.destroy(cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @author 夜雨
|
||||
* @since 2025-10-30 14:48
|
||||
*/
|
||||
public record Result(String id, String data) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,9 @@
|
||||
package com.imyeyu.api.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.imyeyu.api.modules.common.bean.SettingKey;
|
||||
import com.imyeyu.api.modules.common.entity.Multilingual;
|
||||
import com.imyeyu.api.modules.common.entity.Setting;
|
||||
import com.imyeyu.api.modules.common.service.SettingService;
|
||||
import com.imyeyu.api.modules.system.bean.ServerFile;
|
||||
import com.imyeyu.java.ref.Ref;
|
||||
import com.imyeyu.lang.mapper.AbstractLanguageMapper;
|
||||
import com.imyeyu.spring.TimiSpring;
|
||||
import com.imyeyu.spring.util.GlobalReturnHandler;
|
||||
import com.imyeyu.spring.util.Redis;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.eclipse.jgit.api.ArchiveCommand;
|
||||
@@ -23,10 +14,6 @@ import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* SpringBoot 启动事件,主要输出基本参数,避免混淆运行环境
|
||||
@@ -57,23 +44,6 @@ public class InitApplication implements ApplicationRunner {
|
||||
private final SettingService settingService;
|
||||
private final RedisMultilingual redisMultilingual;
|
||||
private final GlobalReturnHandler globalReturnHandler;
|
||||
private final Redis<Long, Multilingual> redisLanguage;
|
||||
|
||||
private void logBaseInfo() {
|
||||
log.info("JDBC URL: {}", jdbcURL);
|
||||
log.info("Redis URL: {}:{}", redisURL, redisPort);
|
||||
log.info("System Setting:");
|
||||
List<Setting> settings = settingService.listAll();
|
||||
for (Setting setting : settings) {
|
||||
String value = Objects.requireNonNullElse(setting.getValue(), "");
|
||||
if (64 < value.length()) {
|
||||
value = value.substring(0, 64) + "..";
|
||||
}
|
||||
value = value.replaceAll("[\\r\\n]+", "");
|
||||
log.info("\t{}: {}", setting.getKey(), value);
|
||||
}
|
||||
log.info("Init Application Finished.");
|
||||
}
|
||||
|
||||
private void initGitCommand() {
|
||||
ArchiveCommand.registerFormat("tar.gz", new TarFormat());
|
||||
@@ -86,38 +56,13 @@ public class InitApplication implements ApplicationRunner {
|
||||
});
|
||||
}
|
||||
|
||||
private void initFileType() {
|
||||
ObjectNode items = settingService.getAsJsonObject(SettingKey.SYSTEM_FILE_TYPE);
|
||||
|
||||
String[] extensions;
|
||||
ArrayNode extensionsArray;
|
||||
JsonNode itemObject;
|
||||
List<String> extensionsList;
|
||||
for (Map.Entry<String, JsonNode> item : (Iterable<Map.Entry<String, JsonNode>>) items::fields) {
|
||||
ServerFile.FileType fileType = Ref.toType(ServerFile.FileType.class, item.getKey());
|
||||
itemObject = item.getValue();
|
||||
extensionsList = new ArrayList<>();
|
||||
extensionsArray = (ArrayNode) itemObject.get("extensions");
|
||||
for (JsonNode extensionNode : extensionsArray) {
|
||||
if (extensionNode.isObject()) {
|
||||
extensionsList.add(extensionNode.path("value").asText());
|
||||
} else {
|
||||
extensionsList.add(extensionNode.asText());
|
||||
}
|
||||
}
|
||||
extensions = new String[extensionsList.size()];
|
||||
// 设置扩展名所属文件类型
|
||||
fileType.setExtensions(extensionsList.toArray(extensions));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
Method[] methods = getClass().getDeclaredMethods();
|
||||
for (int i = 0; i < methods.length; i++) {
|
||||
if (!methods[i].getName().equals("run") && !methods[i].getName().contains("$")) {
|
||||
methods[i].setAccessible(true);
|
||||
methods[i].invoke(this);
|
||||
for (Method method : methods) {
|
||||
if (!method.getName().equals("run") && !method.getName().contains("$")) {
|
||||
method.setAccessible(true);
|
||||
method.invoke(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.imyeyu.api.util;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.bean.ModuleCode;
|
||||
import com.imyeyu.api.modules.common.bean.ImageType;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
|
||||
import com.imyeyu.api.modules.system.service.LoggerService;
|
||||
import com.imyeyu.api.modules.user.bean.BootstrapData;
|
||||
import com.imyeyu.api.modules.user.bean.BuiltinAuthRegistry;
|
||||
import com.imyeyu.api.modules.user.bean.BuiltinPermissionCode;
|
||||
import com.imyeyu.api.modules.user.bean.BuiltinRoleCode;
|
||||
import com.imyeyu.api.modules.user.entity.Permission;
|
||||
import com.imyeyu.api.modules.user.entity.Role;
|
||||
import com.imyeyu.api.modules.user.entity.RolePermission;
|
||||
import com.imyeyu.api.modules.user.entity.RoleRelation;
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
import com.imyeyu.api.modules.user.entity.UserRole;
|
||||
import com.imyeyu.api.modules.user.mapper.PermissionMapper;
|
||||
import com.imyeyu.api.modules.user.mapper.RoleMapper;
|
||||
import com.imyeyu.api.modules.user.mapper.RolePermissionMapper;
|
||||
import com.imyeyu.api.modules.user.mapper.RoleRelationMapper;
|
||||
import com.imyeyu.api.modules.user.mapper.UserRoleMapper;
|
||||
import com.imyeyu.api.modules.user.service.PermissionService;
|
||||
import com.imyeyu.api.modules.user.service.RoleRelationService;
|
||||
import com.imyeyu.api.modules.user.service.RoleService;
|
||||
import com.imyeyu.api.modules.user.service.UserRoleService;
|
||||
import com.imyeyu.api.modules.user.service.UserService;
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.utils.Text;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 内建数据初始化器
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-06-05 15:45
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class InitBuiltinUser implements ApplicationRunner {
|
||||
|
||||
private final RoleService roleService;
|
||||
private final UserService userService;
|
||||
private final LoggerService loggerService;
|
||||
private final UserRoleService userRoleService;
|
||||
private final PermissionService permissionService;
|
||||
private final RoleRelationService roleRelationService;
|
||||
|
||||
private final RoleMapper roleMapper;
|
||||
private final UserRoleMapper userRoleMapper;
|
||||
private final PermissionMapper permissionMapper;
|
||||
private final RolePermissionMapper rolePermissionMapper;
|
||||
private final RoleRelationMapper roleRelationMapper;
|
||||
|
||||
/**
|
||||
* 初始化内建数据
|
||||
*
|
||||
* @param args 启动参数
|
||||
* @throws Exception 初始化异常
|
||||
*/
|
||||
@Override
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
// 先同步所有内建权限和角色,再补齐继承与默认授权关系
|
||||
Map<String, Permission> permissionMap = initBuiltinPermissionMap();
|
||||
Map<String, Role> roleMap = initBuiltinRoleMap();
|
||||
bindBuiltinRoleRelation(roleMap);
|
||||
bindBuiltinPermission(roleMap, permissionMap);
|
||||
|
||||
Role systemRole = roleMap.get(BuiltinAuthRegistry.toRoleKey(BootstrapData.SYS_ROLE_MODULE_CODE, BootstrapData.SYS_ROLE_CODE));
|
||||
// 初始化系统用户
|
||||
User user = userService.getByName(BootstrapData.SYS_USER_NAME);
|
||||
if (user == null) {
|
||||
// 创建
|
||||
String password = Text.randomPassword(32);
|
||||
|
||||
user = new User();
|
||||
user.setName(BootstrapData.SYS_USER_NAME);
|
||||
user.setNick(BootstrapData.SYS_USER_NICK);
|
||||
user.setPassword(password);
|
||||
user.setWrapperType(ImageType.PIXELATED);
|
||||
user.setAvatarType(ImageType.PIXELATED);
|
||||
user.setExp(0);
|
||||
userService.create(user);
|
||||
|
||||
String logContent = "初始化 %s 自举用户成功,请立即修改密码:%s".formatted(BootstrapData.SYS_USER_NAME, password);
|
||||
loggerService.info("SYSTEM", "INITIALIZE_SYSTEM_USER", user.getId(), logContent, null);
|
||||
}
|
||||
// 授权系统用户角色
|
||||
{
|
||||
UserRole example = new UserRole();
|
||||
example.setUserId(user.getId());
|
||||
example.setRoleId(systemRole.getId());
|
||||
if (userRoleMapper.selectByExample(example) != null) {
|
||||
return;
|
||||
}
|
||||
UserRole userRole = new UserRole();
|
||||
userRole.setUserId(user.getId());
|
||||
userRole.setRoleId(systemRole.getId());
|
||||
userRoleService.create(userRole);
|
||||
}
|
||||
}
|
||||
|
||||
/// 按内建定义补齐权限表,不存在才创建
|
||||
///
|
||||
/// @return 权限代码到权限实体的映射
|
||||
private Map<String, Permission> initBuiltinPermissionMap() {
|
||||
Map<String, Permission> permissionMap = new LinkedHashMap<>();
|
||||
for (BuiltinPermissionCode item : BuiltinAuthRegistry.PERMISSION_CODE_LIST) {
|
||||
Permission example = new Permission();
|
||||
example.setModuleCode(item.getModuleCode());
|
||||
example.setCode(item.getValue());
|
||||
Permission permission = permissionMapper.selectByExample(example);
|
||||
if (permission == null) {
|
||||
permission = new Permission();
|
||||
permission.setModuleCode(item.getModuleCode());
|
||||
permission.setCode(item.getValue());
|
||||
permission.setName(item.getDefaultName());
|
||||
permissionService.create(permission);
|
||||
permission = permissionMapper.selectByExample(example);
|
||||
}
|
||||
permissionMap.put(BuiltinAuthRegistry.toPermissionKey(item.getModuleCode(), item.getValue()), permission);
|
||||
}
|
||||
return permissionMap;
|
||||
}
|
||||
|
||||
/// 按内建定义补齐角色表,不存在才创建
|
||||
///
|
||||
/// @return 模块加角色代码到角色实体的映射
|
||||
private Map<String, Role> initBuiltinRoleMap() {
|
||||
Map<String, Role> roleMap = new LinkedHashMap<>();
|
||||
for (BuiltinRoleCode item : BuiltinAuthRegistry.ROLE_CODE_LIST) {
|
||||
String code = ((Enum<?>) item).name();
|
||||
Role example = new Role();
|
||||
example.setModuleCode(item.getModuleCode());
|
||||
example.setCode(code);
|
||||
Role role = roleMapper.selectByExample(example);
|
||||
if (role == null) {
|
||||
role = new Role();
|
||||
role.setModuleCode(item.getModuleCode());
|
||||
role.setCode(code);
|
||||
role.setName(item.getDefaultName());
|
||||
roleService.create(role);
|
||||
role = roleMapper.selectByExample(example);
|
||||
}
|
||||
roleMap.put(BuiltinAuthRegistry.toRoleKey(item.getModuleCode(), code), role);
|
||||
}
|
||||
return roleMap;
|
||||
}
|
||||
|
||||
/// 按角色定义补齐父子角色关系
|
||||
///
|
||||
/// @param roleMap 已同步的角色映射
|
||||
private void bindBuiltinRoleRelation(Map<String, Role> roleMap) {
|
||||
for (BuiltinRoleCode item : BuiltinAuthRegistry.ROLE_CODE_LIST) {
|
||||
if (TimiJava.isEmpty(item.getParentCode())) {
|
||||
continue;
|
||||
}
|
||||
Role parentRole = roleMap.get(BuiltinAuthRegistry.toRoleKey(item.getModuleCode(), item.getParentCode()));
|
||||
Role childRole = roleMap.get(BuiltinAuthRegistry.toRoleKey(item.getModuleCode(), ((Enum<?>) item).name()));
|
||||
if (parentRole == null || childRole == null) {
|
||||
continue;
|
||||
}
|
||||
RoleRelation relation = new RoleRelation();
|
||||
relation.setParentRoleId(parentRole.getId());
|
||||
relation.setChildRoleId(childRole.getId());
|
||||
if (roleRelationMapper.selectByExample(relation) == null) {
|
||||
roleRelationService.create(relation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按权限定义补齐 SYSTEM 和 ADMIN 的默认权限
|
||||
///
|
||||
/// @param roleMap 已同步的角色映射
|
||||
/// @param permissionMap 已同步的权限映射
|
||||
private void bindBuiltinPermission(Map<String, Role> roleMap, Map<String, Permission> permissionMap) {
|
||||
Role systemRole = roleMap.get(BuiltinAuthRegistry.toRoleKey(BootstrapData.SYS_ROLE_MODULE_CODE, BootstrapData.SYS_ROLE_CODE));
|
||||
Role adminRole = roleMap.get(BuiltinAuthRegistry.toRoleKey(BootstrapData.ADMIN_ROLE_MODULE_CODE, BootstrapData.ADMIN_ROLE_CODE));
|
||||
Role gaoStoreManagerRole = roleMap.get(BuiltinAuthRegistry.toRoleKey(ModuleCode.GAO, GaoRoleCode.STORE_MANAGER.name()));
|
||||
for (BuiltinPermissionCode item : BuiltinAuthRegistry.PERMISSION_CODE_LIST) {
|
||||
Permission permission = permissionMap.get(BuiltinAuthRegistry.toPermissionKey(item.getModuleCode(), item.getValue()));
|
||||
if (permission == null) {
|
||||
continue;
|
||||
}
|
||||
if (item.isGrantToSystem() && systemRole != null) {
|
||||
createRolePermissionIfAbsent(systemRole.getId(), permission.getId());
|
||||
}
|
||||
if (item.isGrantToAdmin() && adminRole != null) {
|
||||
createRolePermissionIfAbsent(adminRole.getId(), permission.getId());
|
||||
}
|
||||
if (item instanceof GaoPermissionCode gaoPermission && gaoPermission.isGrantToStoreManager() && gaoStoreManagerRole != null) {
|
||||
createRolePermissionIfAbsent(gaoStoreManagerRole.getId(), permission.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 角色权限关系不存在时才创建
|
||||
///
|
||||
/// @param roleId 角色 ID
|
||||
/// @param permissionId 权限 ID
|
||||
private void createRolePermissionIfAbsent(String roleId, String permissionId) {
|
||||
RolePermission example = new RolePermission();
|
||||
example.setRoleId(roleId);
|
||||
example.setPermissionId(permissionId);
|
||||
if (rolePermissionMapper.selectByExample(example) != null) {
|
||||
return;
|
||||
}
|
||||
RolePermission rolePermission = new RolePermission();
|
||||
rolePermission.setRoleId(roleId);
|
||||
rolePermission.setPermissionId(permissionId);
|
||||
rolePermissionMapper.insert(rolePermission);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package com.imyeyu.api.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.imyeyu.api.annotation.MultilingualField;
|
||||
import com.imyeyu.api.modules.common.entity.Multilingual;
|
||||
import com.imyeyu.api.modules.common.service.MultilingualService;
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.Language;
|
||||
import com.imyeyu.spring.TimiSpring;
|
||||
import com.imyeyu.utils.StringInterpolator;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.file.Path;
|
||||
import java.time.temporal.TemporalAccessor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 统一回填响应对象中的多语言字段
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-07-17 00:00
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class MultilingualFieldBinder {
|
||||
|
||||
private static final StringInterpolator INTERPOLATOR = new StringInterpolator(StringInterpolator.SIMPLE_OBJ);
|
||||
private static final Map<Class<?>, List<Field>> TRAVERSE_CACHE = new ConcurrentHashMap<>();
|
||||
private static final Map<Class<?>, List<BindingField>> BINDING_CACHE = new ConcurrentHashMap<>();
|
||||
|
||||
private final MultilingualService multilingualService;
|
||||
|
||||
/**
|
||||
* 根据当前请求语言回填对象中的多语言字段
|
||||
*
|
||||
* @param body 响应对象
|
||||
*/
|
||||
public void bind(Object body) {
|
||||
if (body == null) {
|
||||
return;
|
||||
}
|
||||
LinkedHashSet<String> langIdSet = new LinkedHashSet<>();
|
||||
// 第一遍只收集多语言 ID,避免递归回填时重复查询
|
||||
collectLangId(body, new IdentityHashMap<>(), langIdSet);
|
||||
if (langIdSet.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<String, Multilingual> multilingualMap = new LinkedHashMap<>();
|
||||
for (Multilingual item : multilingualService.listByIdList(new ArrayList<>(langIdSet))) {
|
||||
multilingualMap.put(item.getId(), item);
|
||||
}
|
||||
// 第二遍执行字段回填,模板替换也在这一遍统一完成
|
||||
fillValue(body, new IdentityHashMap<>(), multilingualMap, TimiSpring.getLanguage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归扫描响应对象,提取所有待翻译字段依赖的多语言 ID
|
||||
*
|
||||
* @param current 当前对象
|
||||
* @param visited 已访问对象,避免循环引用死递归
|
||||
* @param langIdSet 收集到的多语言 ID
|
||||
*/
|
||||
private void collectLangId(Object current, IdentityHashMap<Object, Boolean> visited, LinkedHashSet<String> langIdSet) {
|
||||
switch (current) {
|
||||
case null -> {
|
||||
return;
|
||||
}
|
||||
case Collection<?> collection -> {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (Object item : collection) {
|
||||
collectLangId(item, visited, langIdSet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case Map<?, ?> map -> {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (Object item : map.values()) {
|
||||
collectLangId(item, visited, langIdSet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
if (current.getClass().isArray()) {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
int length = Array.getLength(current);
|
||||
for (int i = 0; i < length; i++) {
|
||||
collectLangId(Array.get(current, i), visited, langIdSet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isSimpleValueType(current.getClass())) {
|
||||
return;
|
||||
}
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (BindingField field : getBindingFields(current.getClass())) {
|
||||
String langId = getStringValue(field.langIdField(), current);
|
||||
if (TimiJava.isNotEmpty(langId)) {
|
||||
langIdSet.add(langId);
|
||||
}
|
||||
}
|
||||
for (Field field : getTraverseFields(current.getClass())) {
|
||||
collectLangId(getFieldValue(field, current), visited, langIdSet);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归回填响应对象中的多语言展示字段
|
||||
*
|
||||
* @param current 当前对象
|
||||
* @param visited 已访问对象,避免循环引用死递归
|
||||
* @param multilingualMap 本次响应涉及的多语言缓存
|
||||
* @param language 当前请求语言
|
||||
*/
|
||||
private void fillValue(Object current, IdentityHashMap<Object, Boolean> visited, Map<String, Multilingual> multilingualMap, Language.Enum language) {
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
if (current instanceof Collection<?> collection) {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (Object item : collection) {
|
||||
fillValue(item, visited, multilingualMap, language);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (current instanceof Map<?, ?> map) {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (Object item : map.values()) {
|
||||
fillValue(item, visited, multilingualMap, language);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (current.getClass().isArray()) {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
int length = Array.getLength(current);
|
||||
for (int i = 0; i < length; i++) {
|
||||
fillValue(Array.get(current, i), visited, multilingualMap, language);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isSimpleValueType(current.getClass())) {
|
||||
return;
|
||||
}
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (BindingField field : getBindingFields(current.getClass())) {
|
||||
String langId = getStringValue(field.langIdField(), current);
|
||||
if (TimiJava.isEmpty(langId)) {
|
||||
continue;
|
||||
}
|
||||
Multilingual multilingual = multilingualMap.get(langId);
|
||||
if (multilingual == null) {
|
||||
continue;
|
||||
}
|
||||
String value = multilingual.getValue(language);
|
||||
if (TimiJava.isEmpty(value)) {
|
||||
value = multilingual.getZhCN();
|
||||
}
|
||||
if (TimiJava.isEmpty(value)) {
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> argMap = getArgMapValue(field.argMapField(), current);
|
||||
if (!argMap.isEmpty()) {
|
||||
value = INTERPOLATOR.inject(value, argMap);
|
||||
}
|
||||
if (TimiJava.isEmpty(value)) {
|
||||
continue;
|
||||
}
|
||||
setFieldValue(field.targetField(), current, value);
|
||||
}
|
||||
for (Field field : getTraverseFields(current.getClass())) {
|
||||
fillValue(getFieldValue(field, current), visited, multilingualMap, language);
|
||||
}
|
||||
}
|
||||
|
||||
private List<BindingField> getBindingFields(Class<?> clazz) {
|
||||
return BINDING_CACHE.computeIfAbsent(clazz, key -> {
|
||||
Map<String, Field> fieldMap = new LinkedHashMap<>();
|
||||
List<Field> declaredFieldList = getAllFields(key);
|
||||
for (Field field : declaredFieldList) {
|
||||
fieldMap.put(field.getName(), field);
|
||||
}
|
||||
List<BindingField> result = new ArrayList<>();
|
||||
for (Field field : declaredFieldList) {
|
||||
MultilingualField annotation = field.getAnnotation(MultilingualField.class);
|
||||
if (annotation == null) {
|
||||
continue;
|
||||
}
|
||||
Field langIdField = fieldMap.get(annotation.value());
|
||||
if (langIdField == null) {
|
||||
log.warn("MultilingualField 配置错误,类 {} 不存在字段 {}", key.getName(), annotation.value());
|
||||
continue;
|
||||
}
|
||||
Field argMapField = null;
|
||||
if (TimiJava.isNotEmpty(annotation.argMap())) {
|
||||
argMapField = fieldMap.get(annotation.argMap());
|
||||
if (argMapField == null) {
|
||||
log.warn("MultilingualField 配置错误,类 {} 不存在字段 {}", key.getName(), annotation.argMap());
|
||||
continue;
|
||||
}
|
||||
if (!Map.class.isAssignableFrom(argMapField.getType())) {
|
||||
log.warn("MultilingualField 配置错误,类 {} 字段 {} 不是 Map", key.getName(), annotation.argMap());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.add(new BindingField(field, langIdField, argMapField));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成需要继续向下遍历的字段列表
|
||||
*
|
||||
* @param clazz 目标类型
|
||||
* @return 可递归字段列表
|
||||
*/
|
||||
private List<Field> getTraverseFields(Class<?> clazz) {
|
||||
return TRAVERSE_CACHE.computeIfAbsent(clazz, key -> {
|
||||
List<Field> result = new ArrayList<>();
|
||||
for (Field field : getAllFields(key)) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
|
||||
continue;
|
||||
}
|
||||
if (field.getType().isArray()
|
||||
|| Collection.class.isAssignableFrom(field.getType())
|
||||
|| Map.class.isAssignableFrom(field.getType())) {
|
||||
field.setAccessible(true);
|
||||
result.add(field);
|
||||
continue;
|
||||
}
|
||||
if (isSimpleValueType(field.getType())) {
|
||||
continue;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
result.add(field);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
private List<Field> getAllFields(Class<?> clazz) {
|
||||
List<Field> result = new ArrayList<>();
|
||||
Class<?> current = clazz;
|
||||
while (current != null && current != Object.class) {
|
||||
for (Field field : current.getDeclaredFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
|
||||
continue;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
result.add(field);
|
||||
}
|
||||
current = current.getSuperclass();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅接受字符串类型的 langId 字段
|
||||
*
|
||||
* @param field 字段
|
||||
* @param target 对象
|
||||
* @return 多语言 ID
|
||||
*/
|
||||
private String getStringValue(Field field, Object target) {
|
||||
Object value = getFieldValue(field, target);
|
||||
if (value instanceof String string) {
|
||||
return string;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅读取 Map 类型模板参数字段,未配置时返回空 Map
|
||||
*
|
||||
* @param field 字段
|
||||
* @param target 对象
|
||||
* @return 模板参数
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> getArgMapValue(Field field, Object target) {
|
||||
if (field == null) {
|
||||
return Map.of();
|
||||
}
|
||||
Object value = getFieldValue(field, target);
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
return (Map<String, Object>) map;
|
||||
}
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
private Object getFieldValue(Field field, Object target) {
|
||||
try {
|
||||
return field.get(target);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new IllegalStateException("读取字段失败: %s#%s".formatted(target.getClass().getName(), field.getName()), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void setFieldValue(Field field, Object target, Object value) {
|
||||
try {
|
||||
field.set(target, value);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new IllegalStateException("写入字段失败: %s#%s".formatted(target.getClass().getName(), field.getName()), e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSimpleValueType(Class<?> clazz) {
|
||||
if (clazz.isPrimitive() || clazz.isEnum() || clazz.isAnnotation()) {
|
||||
return true;
|
||||
}
|
||||
if (CharSequence.class.isAssignableFrom(clazz)
|
||||
|| Number.class.isAssignableFrom(clazz)
|
||||
|| Boolean.class == clazz
|
||||
|| Character.class == clazz
|
||||
|| UUID.class == clazz
|
||||
|| TemporalAccessor.class.isAssignableFrom(clazz)
|
||||
|| Class.class == clazz
|
||||
|| JsonNode.class.isAssignableFrom(clazz)
|
||||
|| File.class.isAssignableFrom(clazz)
|
||||
|| Path.class.isAssignableFrom(clazz)
|
||||
|| InputStream.class.isAssignableFrom(clazz)
|
||||
|| OutputStream.class.isAssignableFrom(clazz)
|
||||
|| Reader.class.isAssignableFrom(clazz)
|
||||
|| Writer.class.isAssignableFrom(clazz)) {
|
||||
return true;
|
||||
}
|
||||
Package currentPackage = clazz.getPackage();
|
||||
if (currentPackage == null) {
|
||||
return false;
|
||||
}
|
||||
String packageName = currentPackage.getName();
|
||||
return packageName.startsWith("java.")
|
||||
|| packageName.startsWith("javax.")
|
||||
|| packageName.startsWith("jakarta.")
|
||||
|| packageName.startsWith("sun.")
|
||||
|| packageName.startsWith("com.fasterxml.jackson.");
|
||||
}
|
||||
|
||||
private record BindingField(Field targetField, Field langIdField, Field argMapField) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.imyeyu.api.util;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
|
||||
/**
|
||||
* 统一处理响应中的多语言字段回填
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-07-17 00:00
|
||||
*/
|
||||
@Component
|
||||
@RestControllerAdvice
|
||||
@RequiredArgsConstructor
|
||||
public class MultilingualResponseBodyAdvice implements ResponseBodyAdvice<Object> {
|
||||
|
||||
private final MultilingualFieldBinder multilingualFieldBinder;
|
||||
|
||||
@Override
|
||||
public boolean supports(@NotNull MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object beforeBodyWrite(Object body,
|
||||
@NotNull MethodParameter returnType,
|
||||
@NotNull MediaType selectedContentType,
|
||||
@NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
|
||||
@NotNull ServerHttpRequest request,
|
||||
@NotNull ServerHttpResponse response) {
|
||||
multilingualFieldBinder.bind(body);
|
||||
return body;
|
||||
}
|
||||
}
|
||||
@@ -4,44 +4,40 @@ import com.imyeyu.api.TimiServerAPI;
|
||||
import com.imyeyu.api.modules.common.service.MultilingualService;
|
||||
import com.imyeyu.java.bean.Language;
|
||||
import com.imyeyu.lang.mapper.AbstractLanguageMapper;
|
||||
import com.imyeyu.utils.StringInterpolator;
|
||||
import org.jcodec.api.NotSupportedException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author 夜雨
|
||||
* @version 2024-04-03 11:01
|
||||
*/
|
||||
public class RedisLanguage extends AbstractLanguageMapper {
|
||||
|
||||
private static final StringInterpolator INTERPOLATOR = new StringInterpolator(StringInterpolator.SIMPLE_OBJ);
|
||||
|
||||
public RedisLanguage(Language.Enum language) {
|
||||
super(language);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(String key, String value) {
|
||||
public void add(String id, String value) {
|
||||
throw new NotSupportedException("not supported to add value, MultilingualService will auto cache when not found value");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean has(String key) {
|
||||
return text(key).equals(key);
|
||||
public boolean has(String id) {
|
||||
return text(id).equals(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String text(String key) {
|
||||
String result = TimiServerAPI.applicationContext.getBean(MultilingualService.class).getByKey(language, key);
|
||||
if (result.startsWith("@")) {
|
||||
// 递归映射
|
||||
return text(result.substring(1));
|
||||
} else {
|
||||
if (result.startsWith("\\@")) {
|
||||
return result.substring(1);
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
public String text(String id) {
|
||||
return TimiServerAPI.applicationContext.getBean(MultilingualService.class).get(id).getValue(language);
|
||||
}
|
||||
|
||||
public String text(Long id) {
|
||||
return TimiServerAPI.applicationContext.getBean(MultilingualService.class).get(language, id);
|
||||
@Override
|
||||
public String textArgs(String id, Map<String, Object> args) {
|
||||
return INTERPOLATOR.inject(text(id), args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.imyeyu.api.util;
|
||||
|
||||
import com.imyeyu.api.modules.common.service.MultilingualService;
|
||||
import com.imyeyu.java.bean.Language;
|
||||
import com.imyeyu.lang.multi.Multilingual;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
@@ -15,13 +14,11 @@ import org.springframework.stereotype.Component;
|
||||
@RequiredArgsConstructor
|
||||
public class RedisMultilingual extends Multilingual {
|
||||
|
||||
private final MultilingualService service;
|
||||
|
||||
@PostConstruct
|
||||
private void postConstruct() {
|
||||
Language.Enum[] languages = Language.Enum.values();
|
||||
for (int i = 0; i < languages.length; i++) {
|
||||
add(languages[i], new RedisLanguage(languages[i]));
|
||||
for (Language.Enum language : languages) {
|
||||
add(language, new RedisLanguage(language));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user