This commit is contained in:
77
2024-05-18 01:02:13 +08:00
parent 874b33557d
commit 32933c2840
47 changed files with 416 additions and 282 deletions

View File

@@ -1,51 +0,0 @@
package com.ruoyi.web.cache;
import com.ruoyi.component.core.constant.CacheConstants;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Set;
@Component
public class OnlineUserTodayCache {
@Autowired
private RedissonClient redissonClient;
private String getKey(LocalDate dateTime){
String today = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
return String.format(CacheConstants.ONLINE_TODAY_TOKEN_KEY,today);
}
public boolean addOnlineUserId(Long userId, LocalDate dateTime){
RSet<Long> set = redissonClient.getSet(getKey(dateTime));
boolean res = set.add(userId);
set.expire(Duration.ofDays(3));
return res;
}
public Set<Long> getAllOnlineToday(){
RSet<Long> set = redissonClient.getSet(getKey(LocalDate.now()));
return set.readAll();
}
public Long getOnlineNum(LocalDate time){
RSet<Long> set = redissonClient.getSet(getKey(time));
return (long) set.size();
}
public Long getOnlineTodayNum(){
RSet<Long> set = redissonClient.getSet(getKey(LocalDate.now()));
return (long) set.size();
}
public Long getOnlineLastNum(){
RSet<Long> set = redissonClient.getSet(getKey(LocalDate.now().plusDays(-1)));
return (long) set.size();
}
}

View File

@@ -7,6 +7,7 @@ import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.constant.Constants;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.domain.R;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.component.core.util.reflect.ReflectUtils;
@@ -59,7 +60,7 @@ public class CaptchaController {
*/
@GetMapping("/captchaSms")
public R<Void> smsCaptcha(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
String key = CacheConstants.CAPTCHA_CODE_KEY + phonenumber;
String key = GlobalConstants.CAPTCHA_CODE_KEY + phonenumber;
String code = RandomUtil.randomNumbers(4);
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
// 验证码模板id 自行处理 (查数据库或写死均可)
@@ -85,7 +86,7 @@ public class CaptchaController {
if (!mailProperties.getEnabled()) {
return R.fail("当前系统没有开启邮箱功能!");
}
String key = CacheConstants.CAPTCHA_CODE_KEY + email;
String key = GlobalConstants.CAPTCHA_CODE_KEY + email;
String code = RandomUtil.randomNumbers(4);
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
try {
@@ -110,7 +111,7 @@ public class CaptchaController {
}
// 保存验证码信息
String uuid = IdUtil.simpleUUID();
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + uuid;
// 生成验证码
CaptchaType captchaType = captchaProperties.getType();
boolean isMath = CaptchaType.MATH == captchaType;

View File

@@ -3,17 +3,18 @@ package com.ruoyi.web.listener;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.listener.SaTokenListener;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.domain.dto.UserOnlineDTO;
import com.ruoyi.component.core.domain.model.LoginUser;
import com.ruoyi.component.core.enums.UserType;
import com.ruoyi.component.redis.util.RedisUtils;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.core.util.ServletUtils;
import com.ruoyi.component.core.util.ip.AddressUtils;
import com.ruoyi.web.cache.OnlineUserTodayCache;
import com.ruoyi.component.redis.util.RedisUtils;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.tenant.helper.TenantHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@@ -31,7 +32,6 @@ import java.time.Duration;
public class UserActionListener implements SaTokenListener {
private final SaTokenConfig tokenConfig;
private final OnlineUserTodayCache onlineUserTodayCache;
/**
* 每次登录时触发
@@ -54,9 +54,13 @@ public class UserActionListener implements SaTokenListener {
dto.setDeptName(user.getDeptName());
dto.setUserType(UserType.SYS_USER.getUserType());
if(tokenConfig.getTimeout() == -1) {
TenantHelper.dynamic(user.getTenantId(),() -> {
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto);
});
} else {
TenantHelper.dynamic(user.getTenantId(),() -> {
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto, Duration.ofSeconds(tokenConfig.getTimeout()));
});
}
log.info("user doLogin, userId:{}, token:{}", loginId, tokenValue);
} else if (userType == UserType.APP_USER) {
@@ -74,9 +78,13 @@ public class UserActionListener implements SaTokenListener {
dto.setUserName(user.getUsername());
dto.setDeptName(user.getDeptName());
if(tokenConfig.getTimeout() == -1) {
TenantHelper.dynamic(user.getTenantId(),() -> {
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto);
});
} else {
TenantHelper.dynamic(user.getTenantId(),() -> {
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto, Duration.ofSeconds(tokenConfig.getTimeout()));
});
}
}
}
@@ -86,7 +94,12 @@ public class UserActionListener implements SaTokenListener {
*/
@Override
public void doLogout(String loginType, Object loginId, String tokenValue) {
String tenantId = LoginHelper.getTenantIdByToken(tokenValue);
if(tenantId != null){
TenantHelper.dynamic(tenantId,() -> {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
});
}
log.info("user doLogout, userId:{}, token:{}", loginId, tokenValue);
}
@@ -95,7 +108,12 @@ public class UserActionListener implements SaTokenListener {
*/
@Override
public void doKickout(String loginType, Object loginId, String tokenValue) {
String tenantId = LoginHelper.getTenantIdByToken(tokenValue);
if(tenantId != null){
TenantHelper.dynamic(tenantId,() -> {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
});
}
log.info("user doLogoutByLoginId, userId:{}, token:{}", loginId, tokenValue);
}
@@ -104,7 +122,12 @@ public class UserActionListener implements SaTokenListener {
*/
@Override
public void doReplaced(String loginType, Object loginId, String tokenValue) {
String tenantId = LoginHelper.getTenantIdByToken(tokenValue);
if(tenantId != null){
TenantHelper.dynamic(tenantId,() -> {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
});
}
log.info("user doReplaced, userId:{}, token:{}", loginId, tokenValue);
}

View File

@@ -21,7 +21,7 @@ spring:
driverClassName: com.mysql.cj.jdbc.Driver
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
url: jdbc:mysql://localhost:4306/cai-v2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true
url: jdbc:mysql://localhost:5306/dk-sass?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true
username: root
password: 383200134
# 从库数据源
@@ -92,18 +92,6 @@ redisson:
subscriptionConnectionPoolSize: 50
mail:
enabled: false
agora:
app-id: 58ff3a37d91d48c7a8ef7a56fb8f62d0
key: 0cca1a53262c4c74b0a8c653a9b7540e
secret: 4a4f734285f34aea86cef63b2a186f27
yunxin:
app-key: 0aaefeb8a80a9889987c5346244b58e2
app-secret: 470345ca2832
cai:
enable-api-encryption: true
open-pay-proxy: false
proxy-ip: 159.75.218.177
proxy-host: 7693
springdoc:
api-docs:
enabled: false

View File

@@ -144,6 +144,25 @@ security:
# - /actuator
# - /actuator/**
# 多租户配置
tenant:
# 是否开启
enable: true
# 排除表
excludes:
- sys_menu
- sys_tenant
- sys_tenant_package
- sys_role_dept
- sys_role_menu
- sys_user_post
- sys_user_role
- sys_client
- sys_oss_config
- sys_dict_type
- sys_dict_data
- sys_config
# MyBatisPlus配置
# https://baomidou.com/config/
mybatis-plus:

View File

@@ -80,5 +80,9 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -25,10 +25,9 @@ import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPoolConfig {
/**
* 核心线程数 = cpu 核心数 + 1
* 核心线程数 = cpu 核心数 + 1 TODO 线程池
*/
// private final int core = Runtime.getRuntime().availableProcessors() + 1;
private final int core = 6 + 1;
private final int core = Runtime.getRuntime().availableProcessors() + 1;
@Bean(name = "threadPoolTaskExecutor")

View File

@@ -12,38 +12,4 @@ public interface CacheConstants {
*/
String ONLINE_TOKEN_KEY = "online_tokens:";
/**
* 单天在线APP用户
*/
String ONLINE_TODAY_TOKEN_KEY = "online_tokens_today:%s";
/**
* 验证码 redis key
*/
String CAPTCHA_CODE_KEY = "captcha_codes:";
/**
* 参数管理 cache key
*/
String SYS_CONFIG_KEY = "sys_config:";
/**
* 字典管理 cache key
*/
String SYS_DICT_KEY = "sys_dict:";
/**
* 防重提交 redis key
*/
String REPEAT_SUBMIT_KEY = "repeat_submit:";
/**
* 限流 redis key
*/
String RATE_LIMIT_KEY = "rate_limit:";
/**
* 登录账户密码错误次数 redis key
*/
String PWD_ERR_CNT_KEY = "pwd_err_cnt:";
}

View File

@@ -15,20 +15,15 @@ package com.ruoyi.component.core.constant;
*/
public interface CacheNames {
/**
* 演示案例
*/
String DEMO_CACHE = "demo:cache#60s#10m#20";
/**
* 系统配置
*/
String SYS_CONFIG = "sys_config";
String SYS_CONFIG = GlobalConstants.GLOBAL_REDIS_KEY + "sys_config";
/**
* 数据字典
*/
String SYS_DICT = "sys_dict";
String SYS_DICT = GlobalConstants.GLOBAL_REDIS_KEY + "sys_dict";
/**
* 用户账户
@@ -52,9 +47,4 @@ public interface CacheNames {
*/
String SYS_OSS_CONFIG = GlobalConstants.GLOBAL_REDIS_KEY + "sys_oss_config";
/**
* 在线用户
*/
String ONLINE_TOKEN = "online_tokens";
}

View File

@@ -36,4 +36,14 @@ public interface GlobalConstants {
* 三方认证 redis key
*/
String SOCIAL_AUTH_CODE_KEY = GLOBAL_REDIS_KEY + "social_auth_codes:";
/**
* 字典管理 cache key
*/
String SYS_DICT_KEY = GLOBAL_REDIS_KEY + "sys_dict:";
/**
* 参数管理 cache key
*/
String SYS_CONFIG_KEY = GLOBAL_REDIS_KEY + "sys_config:";
}

View File

@@ -139,9 +139,4 @@ public interface UserConstants {
*/
Long ADMIN_ID = 1L;
/**
* 管理员角色key
*/
String ADMIN_ROLE_KEY = "admin";
}

View File

@@ -100,6 +100,8 @@ public class LoginUser implements Serializable {
*/
private Long roleId;
private String tenantId;
/**
* 获取登录id
*/

View File

@@ -0,0 +1,34 @@
package com.ruoyi.component.core.executor;
import com.alibaba.ttl.threadpool.TtlExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
public class ExecutorConstant {
private final static int CPU_NUM = Runtime.getRuntime().availableProcessors();
public static Executor COMMON_EXECUTOR;
static {
ThreadPoolExecutor commonExecutor = new ThreadPoolExecutor(CPU_NUM,
CPU_NUM << 2,
5,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(50),
init("commonThreadPool-%d"),
new ThreadPoolExecutor.CallerRunsPolicy());
COMMON_EXECUTOR = TtlExecutors.getTtlExecutor(commonExecutor);
}
private static ThreadFactory init(String nameFormat){
return new ThreadFactoryBuilder().setNameFormat(nameFormat).build();
}
private static ThreadPoolExecutor initExecutor(int corePoolSize, int maxPoolSize, int keepAliveTime, TimeUnit timeUnit,
BlockingQueue<Runnable> workQueue, String nameFormat){
return new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue,
init(nameFormat));
}
}

View File

@@ -30,7 +30,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<select id="selectDbTableColumnsByName" parameterType="String" resultMap="GenTableColumnResult">
<if test="@com.ruoyi.common.helper.DataBaseHelper@isMySql()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isMySql()">
select column_name,
(case when (is_nullable = 'no' <![CDATA[ && ]]> column_key != 'PRI') then '1' else '0' end) as is_required,
(case when column_key = 'PRI' then '1' else '0' end) as is_pk,
@@ -41,7 +41,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
from information_schema.columns where table_schema = (select database()) and table_name = (#{tableName})
order by ordinal_position
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isOracle()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isOracle()">
select lower(temp.column_name) as column_name,
(case when (temp.nullable = 'N' and temp.constraint_type != 'P') then '1' else '0' end) as is_required,
(case when temp.constraint_type = 'P' then '1' else '0' end) as is_pk,
@@ -61,7 +61,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
WHERE temp.row_flg = 1
ORDER BY temp.column_id
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isPostgerSql()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isPostgerSql()">
SELECT column_name, is_required, is_pk, sort, column_comment, is_increment, column_type
FROM (
SELECT c.relname AS table_name,
@@ -95,7 +95,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
WHERE table_name = (#{tableName})
AND column_type <![CDATA[ <> ]]> '-'
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isSqlServer()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isSqlServer()">
SELECT
cast(A.NAME as nvarchar) as column_name,
cast(B.NAME as nvarchar) + (case when B.NAME = 'numeric' then '(' + cast(A.prec as nvarchar) + ',' + cast(A.scale as nvarchar) + ')' else '' end) as column_type,

View File

@@ -54,7 +54,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<select id="selectPageDbTableList" resultMap="GenTableResult">
<if test="@com.ruoyi.common.helper.DataBaseHelper@isMySql()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isMySql()">
select table_name, table_comment, create_time, update_time
from information_schema.tables
where table_schema = (select database())
@@ -68,7 +68,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</if>
order by create_time desc
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isOracle()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isOracle()">
select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time
from user_tables dt, user_tab_comments dtc, user_objects uo
where dt.table_name = dtc.table_name
@@ -84,7 +84,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</if>
order by create_time desc
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isPostgerSql()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isPostgerSql()">
select table_name, table_comment, create_time, update_time
from (
SELECT c.relname AS table_name,
@@ -108,7 +108,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</if>
order by create_time desc
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isSqlServer()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isSqlServer()">
SELECT cast(D.NAME as nvarchar) as table_name,
cast(F.VALUE as nvarchar) as table_comment,
crdate as create_time,
@@ -129,7 +129,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select>
<select id="selectDbTableListByNames" resultMap="GenTableResult">
<if test="@com.ruoyi.common.helper.DataBaseHelper@isMySql()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isMySql()">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_name NOT LIKE 'xxl_job_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database())
and table_name in
@@ -137,7 +137,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
#{name}
</foreach>
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isOracle()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isOracle()">
select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time
from user_tables dt, user_tab_comments dtc, user_objects uo
where dt.table_name = dtc.table_name
@@ -150,7 +150,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
#{name}
</foreach>
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isPostgerSql()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isPostgerSql()">
select table_name, table_comment, create_time, update_time
from (
SELECT c.relname AS table_name,
@@ -170,7 +170,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
#{name}
</foreach>
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isSqlServer()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isSqlServer()">
SELECT cast(D.NAME as nvarchar) as table_name,
cast(F.VALUE as nvarchar) as table_comment,
crdate as create_time,
@@ -187,12 +187,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select>
<select id="selectTableByName" parameterType="String" resultMap="GenTableResult">
<if test="@com.ruoyi.common.helper.DataBaseHelper@isMySql()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isMySql()">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_name NOT LIKE 'xxl_job_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database())
and table_name = #{tableName}
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isOracle()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isOracle()">
select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time
from user_tables dt, user_tab_comments dtc, user_objects uo
where dt.table_name = dtc.table_name
@@ -202,7 +202,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
AND dt.table_name NOT IN (select table_name from gen_table)
and lower(dt.table_name) = #{tableName}
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isPostgerSql()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isPostgerSql()">
select table_name, table_comment, create_time, update_time
from (
SELECT c.relname AS table_name,
@@ -219,7 +219,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where table_name NOT LIKE 'xxl_job_%' and table_name NOT LIKE 'gen_%'
and table_name = #{tableName}
</if>
<if test="@com.ruoyi.common.helper.DataBaseHelper@isSqlServer()">
<if test="@com.ruoyi.component.mybatis.helper.DataBaseHelper@isSqlServer()">
SELECT cast(D.NAME as nvarchar) as table_name,
cast(F.VALUE as nvarchar) as table_comment,
crdate as create_time,

View File

@@ -5,6 +5,7 @@ import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.domain.R;
import com.ruoyi.component.core.exception.ServiceException;
import com.ruoyi.component.core.util.MessageUtils;
@@ -57,7 +58,7 @@ public class RepeatSubmitAspect {
submitKey = SecureUtil.md5(submitKey + ":" + nowParams);
// 唯一标识指定key + url + 消息头)
String cacheRepeatKey = CacheConstants.REPEAT_SUBMIT_KEY + url + submitKey;
String cacheRepeatKey = GlobalConstants.REPEAT_SUBMIT_KEY + url + submitKey;
if (RedisUtils.setObjectIfAbsent(cacheRepeatKey, "", Duration.ofMillis(interval))) {
KEY_CACHE.set(cacheRepeatKey);
} else {

View File

@@ -1,5 +1,7 @@
package com.ruoyi.component.oss.constant;
import com.ruoyi.component.core.constant.GlobalConstants;
import java.util.Arrays;
import java.util.List;
@@ -13,7 +15,7 @@ public interface OssConstant {
/**
* 默认配置KEY
*/
String DEFAULT_CONFIG_KEY = "sys_oss:default_config";
String DEFAULT_CONFIG_KEY = GlobalConstants.GLOBAL_REDIS_KEY + "sys_oss:default_config";
/**
* 预览列表资源开关Key

View File

@@ -2,6 +2,7 @@ package com.ruoyi.component.ratelimiter.aspectj;
import cn.hutool.core.util.ArrayUtil;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.exception.ServiceException;
import com.ruoyi.component.core.util.MessageUtils;
import com.ruoyi.component.core.util.ServletUtils;
@@ -113,7 +114,7 @@ public class RateLimiterAspect {
throw new ServiceException("限流key解析异常!请联系管理员!");
}
}
StringBuilder stringBuffer = new StringBuilder(CacheConstants.RATE_LIMIT_KEY);
StringBuilder stringBuffer = new StringBuilder(GlobalConstants.RATE_LIMIT_KEY);
stringBuffer.append(ServletUtils.getRequest().getRequestURI()).append(":");
if (rateLimiter.limitType() == LimitType.IP) {
// 获取请求ip

View File

@@ -35,9 +35,11 @@ public class LoginHelper {
public static final String LOGIN_USER_KEY = "loginUser";
public static final String USER_KEY = "userId";
public static final String TENANT_KEY = "tenantId";
public static String getTenantIdByToken(String token) {
return Convert.toStr(StpUtil.getExtra(token,TENANT_KEY));
}
/**
* 获取租户ID
@@ -83,6 +85,7 @@ public class LoginHelper {
SaStorage storage = SaHolder.getStorage();
storage.set(LOGIN_USER_KEY, loginUser);
storage.set(USER_KEY, loginUser.getUserId());
storage.set(TENANT_KEY, loginUser.getTenantId());
SaLoginModel model = new SaLoginModel();
if (ObjectUtil.isNotNull(deviceType)) {
model.setDevice(deviceType.getDevice());
@@ -95,7 +98,9 @@ public class LoginHelper {
// } else if (userType == UserType.APP_USER) {
// model.setTimeout(86400).setActiveTimeout(1800);
// }
StpUtil.login(loginUser.getLoginId(), model.setExtra(USER_KEY, loginUser.getUserId()));
model.setExtra(USER_KEY, loginUser.getUserId());
model.setExtra(TENANT_KEY,loginUser.getTenantId());
StpUtil.login(loginUser.getLoginId(), model);
StpUtil.getTokenSession().set(LOGIN_USER_KEY, loginUser);
}

View File

@@ -4,7 +4,9 @@ import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.component.core.util.ServletUtils;
import com.ruoyi.component.core.util.spring.SpringUtils;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.security.config.properties.SecurityProperties;
import com.ruoyi.component.security.handler.AllUrlHandler;
import lombok.RequiredArgsConstructor;
@@ -44,24 +46,6 @@ public class SecurityConfig implements WebMvcConfigurer {
.check(() -> {
// 检查是否登录 是否有token
StpUtil.checkLogin();
// 检查 header 与 param 里的 clientid 与 token 里的是否一致 TODO
// String headerCid = ServletUtils.getRequest().getHeader(LoginHelper.CLIENT_KEY);
// String paramCid = ServletUtils.getParameter(LoginHelper.CLIENT_KEY);
// String clientId = StpUtil.getExtra(LoginHelper.CLIENT_KEY).toString();
// if (!StringUtils.equalsAny(clientId, headerCid, paramCid)) {
// // token 无效
// throw NotLoginException.newInstance(StpUtil.getLoginType(),
// "-100", "客户端ID与Token不匹配",
// StpUtil.getTokenValue());
// }
// 有效率影响 用于临时测试
// if (log.isDebugEnabled()) {
// log.info("剩余有效时间: {}", StpUtil.getTokenTimeout());
// log.info("临时有效时间: {}", StpUtil.getTokenActivityTimeout());
// }
});
})).addPathPatterns("/**")
// 排除不需要拦截的路径

View File

@@ -10,6 +10,7 @@ import com.ruoyi.component.mybatis.config.MybatisPlusConfig;
import com.ruoyi.component.redis.config.RedisConfig;
import com.ruoyi.component.redis.properties.RedissonProperties;
import com.ruoyi.component.tenant.core.TenantSaTokenDao;
import com.ruoyi.component.tenant.filter.TenantFilter;
import com.ruoyi.component.tenant.handle.PlusTenantLineHandler;
import com.ruoyi.component.tenant.handle.TenantKeyPrefixHandler;
import com.ruoyi.component.tenant.manager.TenantSpringCacheManager;
@@ -20,6 +21,7 @@ import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
@@ -88,6 +90,17 @@ public class TenantConfig {
return new TenantSpringCacheManager();
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public FilterRegistrationBean tenantFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new TenantFilter());
registration.addUrlPatterns("/*");
registration.setName("tenantFilter");
registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
return registration;
}
/**
* 多租户鉴权dao实现
*/

View File

@@ -0,0 +1,86 @@
package com.ruoyi.component.tenant.filter;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.ruoyi.component.core.constant.TenantConstants;
import com.ruoyi.component.core.domain.R;
import com.ruoyi.component.core.util.ServletUtils;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.tenant.helper.TenantHelper;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class TenantFilter implements Filter {
public static final String TENANT_ID_HEADER = "Tenant-ID";
private static final Set<String> IGNORE_URL = new HashSet<>();
static {
IGNORE_URL.add("/login");
IGNORE_URL.add("/captchaImage");
}
private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if(!(servletRequest instanceof HttpServletRequest)){
filterChain.doFilter(servletRequest, servletResponse);
return;
}
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
try {
String requestURI = request.getRequestURI();
for (String ignoreUrlMatch : IGNORE_URL) {
boolean match = ANT_PATH_MATCHER.match(ignoreUrlMatch, requestURI);
if(match){
filterChain.doFilter(servletRequest, servletResponse);
return;
}
}
String tenantHeader = request.getHeader(TENANT_ID_HEADER);
boolean login = TenantHelper.isLogin();
if(login){
Long userId = LoginHelper.getUserId();
if(TenantConstants.SUPER_ADMIN_ID.equals(userId)){
TenantHelper.setTenantId(tenantHeader);
filterChain.doFilter(servletRequest, servletResponse);
return;
}
}
if(!StringUtils.isBlank(tenantHeader)){
if(login){
String tenantId = LoginHelper.getTenantId();
if(tenantId == null || !tenantId.equals(tenantHeader)){
ServletUtils.renderString(response, JSONUtil.toJsonStr(R.fail("平台错误")));
return;
}
TenantHelper.setTenantId(tenantId);
}else{
TenantHelper.setTenantId(tenantHeader);
}
} else {
if(login){
String tenantId = LoginHelper.getTenantId();
if(tenantId == null){
ServletUtils.renderString(response, JSONUtil.toJsonStr(R.fail("平台错误")));
return;
}
TenantHelper.setTenantId(tenantId);
}
}
filterChain.doFilter(servletRequest, servletResponse);
} finally {
TenantHelper.clearTenant();
}
}
}

View File

@@ -2,6 +2,7 @@ package com.ruoyi.component.tenant.handle;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.ruoyi.component.core.exception.ServiceException;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.component.tenant.helper.TenantHelper;
import com.ruoyi.component.tenant.properties.TenantProperties;
@@ -29,7 +30,8 @@ public class PlusTenantLineHandler implements TenantLineHandler {
String tenantId = TenantHelper.getTenantId();
if (StringUtils.isBlank(tenantId)) {
log.error("无法获取有效的租户id -> Null");
return new NullValue();
throw new ServiceException("无法获取有效的平台");
// return new NullValue();
}
// 返回固定租户
return new StringValue(tenantId);
@@ -37,9 +39,6 @@ public class PlusTenantLineHandler implements TenantLineHandler {
@Override
public boolean ignoreTable(String tableName) {
String tenantId = TenantHelper.getTenantId();
// 判断是否有租户
if (StringUtils.isNotBlank(tenantId)) {
// 不需要过滤租户的表
List<String> excludes = tenantProperties.getExcludes();
// 非业务表
@@ -50,7 +49,5 @@ public class PlusTenantLineHandler implements TenantLineHandler {
tables.addAll(excludes);
return tables.contains(tableName);
}
return true;
}
}

View File

@@ -1,6 +1,7 @@
package com.ruoyi.component.tenant.handle;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.exception.ServiceException;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.component.redis.handler.KeyPrefixHandler;
import com.ruoyi.component.tenant.helper.TenantHelper;
@@ -32,6 +33,7 @@ public class TenantKeyPrefixHandler extends KeyPrefixHandler {
String tenantId = TenantHelper.getTenantId();
if (StringUtils.isBlank(tenantId)) {
log.error("无法获取有效的租户id -> Null");
throw new ServiceException("无法获取有效的平台");
}
if (StringUtils.startsWith(name, tenantId + "")) {
// 如果存在则直接返回
@@ -55,6 +57,7 @@ public class TenantKeyPrefixHandler extends KeyPrefixHandler {
String tenantId = TenantHelper.getTenantId();
if (StringUtils.isBlank(tenantId)) {
log.error("无法获取有效的租户id -> Null");
throw new ServiceException("无法获取有效的平台");
}
if (StringUtils.startsWith(unmap, tenantId + "")) {
// 如果存在则删除

View File

@@ -6,11 +6,10 @@ import cn.hutool.core.convert.Convert;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.baomidou.mybatisplus.core.plugins.IgnoreStrategy;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.component.core.util.spring.SpringUtils;
import com.ruoyi.component.redis.util.RedisUtils;
import com.ruoyi.component.satoken.utils.LoginHelper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -26,10 +25,7 @@ import java.util.function.Supplier;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TenantHelper {
private static final String DYNAMIC_TENANT_KEY = GlobalConstants.GLOBAL_REDIS_KEY + "dynamicTenant";
private static final ThreadLocal<String> TEMP_DYNAMIC_TENANT = new TransmittableThreadLocal<>();
private static final ThreadLocal<String> DYNAMIC_TENANT = new TransmittableThreadLocal<>();
/**
* 租户功能是否启用
*/
@@ -79,22 +75,11 @@ public class TenantHelper {
}
}
/**
* 设置动态租户(一直有效 需要手动清理)
* <p>
* 如果为未登录状态下 那么只在当前线程内生效
*/
public static void setDynamic(String tenantId) {
public static void setTenantId(String tenantId) {
if (!isEnable()) {
return;
}
if (!isLogin()) {
TEMP_DYNAMIC_TENANT.set(tenantId);
return;
}
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
RedisUtils.setCacheObject(cacheKey, tenantId);
SaHolder.getStorage().set(cacheKey, tenantId);
DYNAMIC_TENANT.set(tenantId);
}
/**
@@ -102,37 +87,21 @@ public class TenantHelper {
* <p>
* 如果为未登录状态下 那么只在当前线程内生效
*/
public static String getDynamic() {
public static String getTenantId() {
if (!isEnable()) {
return null;
}
if (!isLogin()) {
return TEMP_DYNAMIC_TENANT.get();
}
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
String tenantId = (String) SaHolder.getStorage().get(cacheKey);
if (StringUtils.isNotBlank(tenantId)) {
return tenantId;
}
tenantId = RedisUtils.getCacheObject(cacheKey);
SaHolder.getStorage().set(cacheKey, tenantId);
return tenantId;
return DYNAMIC_TENANT.get();
}
/**
* 清除动态租户
*/
public static void clearDynamic() {
public static void clearTenant() {
if (!isEnable()) {
return;
}
if (!isLogin()) {
TEMP_DYNAMIC_TENANT.remove();
return;
}
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
RedisUtils.deleteObject(cacheKey);
SaHolder.getStorage().delete(cacheKey);
DYNAMIC_TENANT.remove();
}
/**
@@ -141,11 +110,11 @@ public class TenantHelper {
* @param handle 处理执行方法
*/
public static void dynamic(String tenantId, Runnable handle) {
setDynamic(tenantId);
setTenantId(tenantId);
try {
handle.run();
} finally {
clearDynamic();
clearTenant();
}
}
@@ -155,29 +124,15 @@ public class TenantHelper {
* @param handle 处理执行方法
*/
public static <T> T dynamic(String tenantId, Supplier<T> handle) {
setDynamic(tenantId);
setTenantId(tenantId);
try {
return handle.get();
} finally {
clearDynamic();
clearTenant();
}
}
/**
* 获取当前租户id(动态租户优先)
*/
public static String getTenantId() {
if (!isEnable()) {
return null;
}
String tenantId = TenantHelper.getDynamic();
if (StringUtils.isBlank(tenantId)) {
tenantId = LoginHelper.getTenantId();
}
return tenantId;
}
private static boolean isLogin() {
public static boolean isLogin() {
try {
StpUtil.checkLogin();
return true;

View File

@@ -67,6 +67,7 @@ public class DkLoginKit {
loginUser.setRoleId(null);
loginUser.setUserId(user.getId());
loginUser.setUserType(UserType.APP_USER.getUserType());
// loginUser.setTenantId(user);
LoginHelper.login(loginUser);
sysLoginService.recordLogininfor(loginUser.getUsername(), UserType.APP_USER.getUserType(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
return StpUtil.getTokenValue();

View File

@@ -2,16 +2,21 @@ package com.ruoyi.system.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.component.core.constant.Constants;
import com.ruoyi.component.core.constant.TenantConstants;
import com.ruoyi.component.core.domain.R;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.component.core.domain.model.EmailLoginBody;
import com.ruoyi.component.core.domain.model.LoginBody;
import com.ruoyi.component.core.domain.model.LoginUser;
import com.ruoyi.component.core.domain.model.SmsLoginBody;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.tenant.helper.TenantHelper;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.bo.SysTenantBo;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.domain.vo.SysTenantVo;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysTenantService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
@@ -21,6 +26,7 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
@@ -39,6 +45,7 @@ public class SysLoginController {
private final SysLoginService loginService;
private final ISysMenuService menuService;
private final ISysUserService userService;
private final ISysTenantService tenantService;
/**
* 登录方法
@@ -141,4 +148,18 @@ public class SysLoginController {
List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
return R.ok(menuService.buildMenus(menus));
}
@GetMapping("auth/tenant/list")
public R<List<SysTenantVo>> tenantList(HttpServletRequest request){
Long userId = LoginHelper.getUserId();
if(TenantConstants.SUPER_ADMIN_ID.equals(userId)){
List<SysTenantVo> tenantList = tenantService.queryList(new SysTenantBo());
return R.ok(tenantList);
}else {
SysTenantBo sysTenantBo = new SysTenantBo();
sysTenantBo.setTenantId(TenantHelper.getTenantId());
List<SysTenantVo> tenantList = tenantService.queryList(sysTenantBo);
return R.ok(tenantList);
}
}
}

View File

@@ -1,7 +1,9 @@
package com.ruoyi.system.controller;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.core.lang.tree.Tree;
import com.ruoyi.component.core.constant.TenantConstants;
import com.ruoyi.component.core.constant.UserConstants;
import com.ruoyi.component.core.domain.R;
import com.ruoyi.component.log.annotation.Log;
@@ -10,6 +12,7 @@ import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.web.core.BaseController;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.system.domain.vo.MenuTreeSelectVo;
import com.ruoyi.system.service.ISysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
@@ -76,6 +79,22 @@ public class SysMenuController extends BaseController {
return R.ok(ajax);
}
/**
* 加载对应租户套餐菜单列表树
*
* @param packageId 租户套餐ID
*/
@SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
@SaCheckPermission("system:menu:query")
@GetMapping(value = "/tenantPackageMenuTreeselect/{packageId}")
public R<MenuTreeSelectVo> tenantPackageMenuTreeselect(@PathVariable("packageId") Long packageId) {
List<SysMenu> menus = menuService.selectMenuList(LoginHelper.getUserId());
MenuTreeSelectVo selectVo = new MenuTreeSelectVo();
selectVo.setCheckedKeys(menuService.selectMenuListByPackageId(packageId));
selectVo.setMenus(menuService.buildMenuTreeSelect(menus));
return R.ok(selectVo);
}
/**
* 新增菜单
*/

View File

@@ -143,7 +143,7 @@ public class SysTenantController extends BaseController {
@SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
@GetMapping("/dynamic/{tenantId}")
public R<Void> dynamicTenant(@NotBlank(message = "租户ID不能为空") @PathVariable String tenantId) {
TenantHelper.setDynamic(tenantId);
// TenantHelper.setDynamic(tenantId);
return R.ok();
}
@@ -153,7 +153,7 @@ public class SysTenantController extends BaseController {
@SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
@GetMapping("/dynamic/clear")
public R<Void> dynamicClear() {
TenantHelper.clearDynamic();
TenantHelper.clearTenant();
return R.ok();
}

View File

@@ -4,6 +4,7 @@ import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.constant.CacheNames;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.domain.R;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.component.json.utils.JsonUtils;
@@ -36,11 +37,11 @@ public class CacheController {
CACHES.add(new SysCache(CacheConstants.ONLINE_TOKEN_KEY, "在线用户"));
CACHES.add(new SysCache(CacheNames.SYS_CONFIG, "配置信息"));
CACHES.add(new SysCache(CacheNames.SYS_DICT, "数据字典"));
CACHES.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
CACHES.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
CACHES.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
CACHES.add(new SysCache(GlobalConstants.CAPTCHA_CODE_KEY, "验证码"));
CACHES.add(new SysCache(GlobalConstants.REPEAT_SUBMIT_KEY, "防重提交"));
CACHES.add(new SysCache(GlobalConstants.RATE_LIMIT_KEY, "限流处理"));
CACHES.add(new SysCache(CacheNames.SYS_OSS_CONFIG, "OSS配置"));
CACHES.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
CACHES.add(new SysCache(GlobalConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
}
/**

View File

@@ -2,6 +2,7 @@ package com.ruoyi.system.controller.monitor;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.domain.R;
import com.ruoyi.component.excel.utils.ExcelUtil;
import com.ruoyi.component.log.annotation.Log;
@@ -78,7 +79,7 @@ public class SysLogininforController extends BaseController {
@Log(title = "账户解锁", businessType = BusinessType.OTHER)
@GetMapping("/unlock/{userName}")
public R<Void> unlock(@PathVariable("userName") String userName) {
String loginName = CacheConstants.PWD_ERR_CNT_KEY + userName;
String loginName = GlobalConstants.PWD_ERR_CNT_KEY + userName;
if (RedisUtils.hasKey(loginName)) {
RedisUtils.deleteObject(loginName);
}

View File

@@ -16,7 +16,7 @@ import javax.validation.constraints.Size;
/**
* 参数配置表 sys_config
*
* 忽略租户
* @author Lion Li
*/

View File

@@ -17,10 +17,9 @@ import javax.validation.constraints.Size;
/**
* 字典数据表 sys_dict_data
*
* 忽略租户
* @author Lion Li
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_dict_data")

View File

@@ -17,7 +17,7 @@ import javax.validation.constraints.Size;
/**
* 字典类型表 sys_dict_type
*
* 忽略租户
* @author Lion Li
*/

View File

@@ -3,7 +3,7 @@ package com.ruoyi.system.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.component.core.xss.Xss;
import com.ruoyi.component.mybatis.core.domain.BaseEntity;
import com.ruoyi.component.tenant.core.TenantEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -19,7 +19,7 @@ import javax.validation.constraints.Size;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_notice")
public class SysNotice extends BaseEntity {
public class SysNotice extends TenantEntity {
/**
* 公告ID

View File

@@ -136,6 +136,8 @@ public class SysOperLog implements Serializable {
@ExcelProperty(value = "操作时间")
private Date operTime;
private String tenantId;
/**
* 请求参数

View File

@@ -8,6 +8,7 @@ import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.component.excel.annotation.ExcelDictFormat;
import com.ruoyi.component.excel.convert.ExcelDictConvert;
import com.ruoyi.component.mybatis.core.domain.BaseEntity;
import com.ruoyi.component.tenant.core.TenantEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -25,7 +26,7 @@ import javax.validation.constraints.Size;
@EqualsAndHashCode(callSuper = true)
@TableName("sys_post")
@ExcelIgnoreUnannotated
public class SysPost extends BaseEntity {
public class SysPost extends TenantEntity {
/**
* 岗位序号

View File

@@ -0,0 +1,26 @@
package com.ruoyi.system.domain.vo;
import cn.hutool.core.lang.tree.Tree;
import lombok.Data;
import java.util.List;
/**
* 角色菜单列表树信息
*
* @author Michelle.Chung
*/
@Data
public class MenuTreeSelectVo {
/**
* 选中菜单列表
*/
private List<Long> checkedKeys;
/**
* 菜单下拉树结构列表
*/
private List<Tree<Long>> menus;
}

View File

@@ -39,6 +39,7 @@ public interface ISysMenuService {
*/
Set<String> selectMenuPermsByUserId(Long userId);
/**
* 根据角色ID查询权限
*
@@ -62,6 +63,7 @@ public interface ISysMenuService {
* @return 选中菜单列表
*/
List<Long> selectMenuListByRoleId(Long roleId);
List<Long> selectMenuListByPackageId(Long packageId);
/**
* 构建前端路由所需要的菜单
@@ -134,4 +136,6 @@ public interface ISysMenuService {
* @return 结果
*/
boolean checkMenuNameUnique(SysMenu menu);
}

View File

@@ -8,9 +8,12 @@ import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.constant.Constants;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.domain.dto.RoleDTO;
import com.ruoyi.component.log.event.LogininforEvent;
import com.ruoyi.component.redis.util.RedisUtils;
import com.ruoyi.component.tenant.core.TenantEntity;
import com.ruoyi.component.tenant.helper.TenantHelper;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.component.core.domain.model.LoginUser;
import com.ruoyi.component.core.domain.model.XcxLoginUser;
@@ -73,13 +76,13 @@ public class SysLoginService {
validateCaptcha(username, UserType.SYS_USER.getUserType(), code, uuid);
}
// 框架登录不限制从什么表查询 只要最终构建出 LoginUser 即可
SysUser user = loadUserByUsername(username);
SysUser user = TenantHelper.ignore(() -> loadUserByUsername(username));
checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, user.getPassword()));
// 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
LoginUser loginUser = buildLoginUser(user);
// 生成token
LoginHelper.loginByDevice(loginUser, DeviceType.PC);
TenantHelper.setTenantId(loginUser.getTenantId());
recordLogininfor(username,loginUser.getUserType(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
recordLoginInfo(user.getUserId(), username);
return StpUtil.getTokenValue();
@@ -175,7 +178,7 @@ public class SysLoginService {
* 校验短信验证码
*/
private boolean validateSmsCode(String phonenumber, String smsCode) {
String code = RedisUtils.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY + phonenumber);
String code = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + phonenumber);
if (StringUtils.isBlank(code)) {
recordLogininfor(phonenumber, UserType.SYS_USER.getUserType(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
@@ -187,7 +190,7 @@ public class SysLoginService {
* 校验邮箱验证码
*/
private boolean validateEmailCode(String email, String emailCode) {
String code = RedisUtils.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY + email);
String code = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + email);
if (StringUtils.isBlank(code)) {
recordLogininfor(email, UserType.SYS_USER.getUserType(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
@@ -203,7 +206,7 @@ public class SysLoginService {
* @param uuid 唯一标识
*/
public void validateCaptcha(String username, String userType, String code, String uuid) {
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
String captcha = RedisUtils.getCacheObject(verifyKey);
RedisUtils.deleteObject(verifyKey);
if (captcha == null) {
@@ -218,7 +221,7 @@ public class SysLoginService {
private SysUser loadUserByUsername(String username) {
SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
.select(SysUser::getUserName, SysUser::getStatus)
.select(SysUser::getUserName, SysUser::getStatus, SysUser::getTenantId)
.eq(SysUser::getUserName, username));
if (ObjectUtil.isNull(user)) {
log.info("登录用户:{} 不存在.", username);
@@ -232,7 +235,7 @@ public class SysLoginService {
private SysUser loadUserByPhonenumber(String phonenumber) {
SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
.select(SysUser::getPhonenumber, SysUser::getStatus)
.select(SysUser::getPhonenumber, SysUser::getStatus, SysUser::getTenantId)
.eq(SysUser::getPhonenumber, phonenumber));
if (ObjectUtil.isNull(user)) {
log.info("登录用户:{} 不存在.", phonenumber);
@@ -246,7 +249,7 @@ public class SysLoginService {
private SysUser loadUserByEmail(String email) {
SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
.select(SysUser::getPhonenumber, SysUser::getStatus)
.select(SysUser::getPhonenumber, SysUser::getStatus,SysUser::getTenantId)
.eq(SysUser::getEmail, email));
if (ObjectUtil.isNull(user)) {
log.info("登录用户:{} 不存在.", email);
@@ -283,6 +286,7 @@ public class SysLoginService {
loginUser.setUserType(user.getUserType());
loginUser.setMenuPermission(permissionService.getMenuPermission(user));
loginUser.setRolePermission(permissionService.getRolePermission(user));
loginUser.setTenantId(user.getTenantId());
loginUser.setDeptName(ObjectUtil.isNull(user.getDept()) ? "" : user.getDept().getDeptName());
List<RoleDTO> roles = BeanUtil.copyToList(user.getRoles(), RoleDTO.class);
loginUser.setRoles(roles);
@@ -307,7 +311,7 @@ public class SysLoginService {
* 登录校验
*/
private void checkLogin(LoginType loginType, String username, Supplier<Boolean> supplier) {
String errorKey = CacheConstants.PWD_ERR_CNT_KEY + username;
String errorKey = GlobalConstants.PWD_ERR_CNT_KEY + username;
String loginFail = Constants.LOGIN_FAIL;
// 获取用户登录错误次数默认为0 (可自定义限制策略 例如: key + username + ip)

View File

@@ -1,5 +1,6 @@
package com.ruoyi.system.service;
import com.ruoyi.component.core.constant.TenantConstants;
import com.ruoyi.system.domain.SysUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -29,7 +30,7 @@ public class SysPermissionService {
Set<String> roles = new HashSet<>();
// 管理员拥有所有权限
if (user.isAdmin()) {
roles.add("admin");
roles.add(TenantConstants.SUPER_ADMIN_ROLE_KEY);
} else {
roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
}

View File

@@ -3,6 +3,7 @@ package com.ruoyi.system.service;
import cn.dev33.satoken.secure.BCrypt;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.constant.Constants;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.log.event.LogininforEvent;
import com.ruoyi.component.redis.util.RedisUtils;
import com.ruoyi.system.domain.SysUser;
@@ -68,7 +69,7 @@ public class SysRegisterService {
* @param uuid 唯一标识
*/
public void validateCaptcha(String username, String code, String uuid) {
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
String captcha = RedisUtils.getCacheObject(verifyKey);
RedisUtils.deleteObject(verifyKey);
if (captcha == null) {

View File

@@ -8,6 +8,7 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.component.core.constant.CacheConstants;
import com.ruoyi.component.core.constant.CacheNames;
import com.ruoyi.component.core.constant.GlobalConstants;
import com.ruoyi.component.core.constant.UserConstants;
import com.ruoyi.component.mybatis.core.page.PageQuery;
import com.ruoyi.component.mybatis.core.page.TableDataInfo;
@@ -235,10 +236,10 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService, DictService
@Override
public String getDictLabel(String dictType, String dictValue, String separator) {
// 优先从本地缓存获取
List<SysDictData> datas = (List<SysDictData>) SaHolder.getStorage().get(CacheConstants.SYS_DICT_KEY + dictType);
List<SysDictData> datas = (List<SysDictData>) SaHolder.getStorage().get(GlobalConstants.SYS_DICT_KEY + dictType);
if (ObjectUtil.isNull(datas)) {
datas = SpringUtils.getAopProxy(this).selectDictDataByType(dictType);
SaHolder.getStorage().set(CacheConstants.SYS_DICT_KEY + dictType, datas);
SaHolder.getStorage().set(GlobalConstants.SYS_DICT_KEY + dictType, datas);
}
Map<String, String> map = StreamUtils.toMap(datas, SysDictData::getDictValue, SysDictData::getDictLabel);
@@ -263,10 +264,10 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService, DictService
@Override
public String getDictValue(String dictType, String dictLabel, String separator) {
// 优先从本地缓存获取
List<SysDictData> datas = (List<SysDictData>) SaHolder.getStorage().get(CacheConstants.SYS_DICT_KEY + dictType);
List<SysDictData> datas = (List<SysDictData>) SaHolder.getStorage().get(GlobalConstants.SYS_DICT_KEY + dictType);
if (ObjectUtil.isNull(datas)) {
datas = SpringUtils.getAopProxy(this).selectDictDataByType(dictType);
SaHolder.getStorage().set(CacheConstants.SYS_DICT_KEY + dictType, datas);
SaHolder.getStorage().set(GlobalConstants.SYS_DICT_KEY + dictType, datas);
}
Map<String, String> map = StreamUtils.toMap(datas, SysDictData::getDictLabel, SysDictData::getDictValue);

View File

@@ -1,6 +1,7 @@
package com.ruoyi.system.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
@@ -15,11 +16,13 @@ import com.ruoyi.component.core.util.StreamUtils;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.component.core.util.TreeBuildUtils;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.domain.SysTenantPackage;
import com.ruoyi.system.domain.vo.MetaVo;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.mapper.SysMenuMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.mapper.SysTenantPackageMapper;
import com.ruoyi.system.service.ISysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -38,6 +41,7 @@ public class SysMenuServiceImpl implements ISysMenuService {
private final SysMenuMapper baseMapper;
private final SysRoleMapper roleMapper;
private final SysRoleMenuMapper roleMenuMapper;
private final SysTenantPackageMapper tenantPackageMapper;
/**
* 根据用户查询系统菜单列表
@@ -145,6 +149,24 @@ public class SysMenuServiceImpl implements ISysMenuService {
return baseMapper.selectMenuListByRoleId(roleId, role.getMenuCheckStrictly());
}
@Override
public List<Long> selectMenuListByPackageId(Long packageId) {
SysTenantPackage tenantPackage = tenantPackageMapper.selectById(packageId);
List<Long> menuIds = StringUtils.splitTo(tenantPackage.getMenuIds(), Convert::toLong);
if (CollUtil.isEmpty(menuIds)) {
return Collections.emptyList();
}
List<Long> parentIds = null;
if (tenantPackage.getMenuCheckStrictly()) {
parentIds = baseMapper.selectObjs(new LambdaQueryWrapper<SysMenu>()
.select(SysMenu::getParentId)
.in(SysMenu::getMenuId, menuIds));
}
return baseMapper.selectObjs(new LambdaQueryWrapper<SysMenu>()
.in(SysMenu::getMenuId, menuIds)
.notIn(CollUtil.isNotEmpty(parentIds), SysMenu::getMenuId, parentIds));
}
/**
* 构建前端路由所需要的菜单
*

View File

@@ -9,6 +9,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.component.core.constant.TenantConstants;
import com.ruoyi.component.core.constant.UserConstants;
import com.ruoyi.component.mybatis.core.page.PageQuery;
import com.ruoyi.component.mybatis.core.page.TableDataInfo;
@@ -186,9 +187,10 @@ public class SysRoleServiceImpl implements ISysRoleService {
if (ObjectUtil.isNotNull(role.getRoleId()) && role.isAdmin()) {
throw new ServiceException("不允许操作超级管理员角色");
}
String[] keys = new String[]{TenantConstants.SUPER_ADMIN_ROLE_KEY, TenantConstants.TENANT_ADMIN_ROLE_KEY};
// 新增不允许使用 管理员标识符
if (ObjectUtil.isNull(role.getRoleId())
&& StringUtils.equals(role.getRoleKey(), UserConstants.ADMIN_ROLE_KEY)) {
&& StringUtils.equalsAny(role.getRoleKey(), keys)) {
throw new ServiceException("不允许使用系统内置管理员角色标识符!");
}
// 修改不允许修改 管理员标识符
@@ -196,9 +198,9 @@ public class SysRoleServiceImpl implements ISysRoleService {
SysRole sysRole = baseMapper.selectById(role.getRoleId());
// 如果标识符不相等 判断为修改了管理员标识符
if (!StringUtils.equals(sysRole.getRoleKey(), role.getRoleKey())) {
if (StringUtils.equals(sysRole.getRoleKey(), UserConstants.ADMIN_ROLE_KEY)) {
if (StringUtils.equalsAny(sysRole.getRoleKey(), keys)) {
throw new ServiceException("不允许修改系统内置管理员角色标识符!");
} else if (StringUtils.equals(role.getRoleKey(), UserConstants.ADMIN_ROLE_KEY)) {
} else if (StringUtils.equalsAny(role.getRoleKey(), keys)) {
throw new ServiceException("不允许使用系统内置管理员角色标识符!");
}
}

View File

@@ -124,7 +124,6 @@ public class SysTenantServiceImpl implements ISysTenantService {
@Transactional(rollbackFor = Exception.class)
public Boolean insertByBo(SysTenantBo bo) {
SysTenant add = BeanConvertUtil.convertTo(bo, SysTenant::new);
// 获取所有租户编号
List<String> tenantIds = baseMapper.selectObjs(
new LambdaQueryWrapper<SysTenant>().select(SysTenant::getTenantId));
@@ -187,8 +186,8 @@ public class SysTenantServiceImpl implements ISysTenantService {
dictData.setDictCode(null);
dictData.setTenantId(tenantId);
}
dictTypeMapper.insertBatch(dictTypeList);
dictDataMapper.insertBatch(dictDataList);
// dictTypeMapper.insertBatch(dictTypeList);
// dictDataMapper.insertBatch(dictDataList);
List<SysConfig> sysConfigList = configMapper.selectList(
new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getTenantId, defaultTenantId));
@@ -196,7 +195,7 @@ public class SysTenantServiceImpl implements ISysTenantService {
config.setConfigId(null);
config.setTenantId(tenantId);
}
configMapper.insertBatch(sysConfigList);
// configMapper.insertBatch(sysConfigList);
return true;
}

View File

@@ -24,6 +24,7 @@
<result property="updateBy" column="update_by"/>
<result property="updateTime" column="update_time"/>
<result property="remark" column="remark"/>
<result property="tenantId" column="tenant_id"/>
<association property="dept" column="dept_id" javaType="SysDept" resultMap="deptResult"/>
<collection property="roles" javaType="java.util.List" resultMap="RoleResult"/>
</resultMap>
@@ -65,6 +66,7 @@
u.create_by,
u.create_time,
u.remark,
u.tenant_id,
d.dept_id,
d.parent_id,
d.ancestors,