浏览代码

fix:修复系统单点登录功能错误启用的问题

wangzaijun 7 月之前
父节点
当前提交
af39c67d2f

+ 87 - 69
service-base/src/main/java/com/simuwang/base/common/util/ServletUtils.java

@@ -1,6 +1,6 @@
 package com.simuwang.base.common.util;
 package com.simuwang.base.common.util;
 
 
-import com.simuwang.base.common.conts.Constants;
+import cn.hutool.core.util.StrUtil;
 import com.simuwang.base.common.text.Convert;
 import com.simuwang.base.common.text.Convert;
 import jakarta.servlet.ServletRequest;
 import jakarta.servlet.ServletRequest;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletRequest;
@@ -12,64 +12,61 @@ import org.springframework.web.context.request.RequestContextHolder;
 import org.springframework.web.context.request.ServletRequestAttributes;
 import org.springframework.web.context.request.ServletRequestAttributes;
 
 
 import java.io.IOException;
 import java.io.IOException;
-import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.net.URLDecoder;
 import java.net.URLEncoder;
 import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
 import java.util.Collections;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Map;
+
 /**
 /**
  * 客户端工具类
  * 客户端工具类
- * 
+ *
  * @author ruoyi
  * @author ruoyi
  */
  */
-public class ServletUtils
-{
+public class ServletUtils {
+    public static final String IP_UNKNOWN = "unknown";
+    public static final String IP_LOCALHOST = "127.0.0.1";
+
     /**
     /**
      * 获取String参数
      * 获取String参数
      */
      */
-    public static String getParameter(String name)
-    {
+    public static String getParameter(String name) {
         return getRequest().getParameter(name);
         return getRequest().getParameter(name);
     }
     }
 
 
     /**
     /**
      * 获取String参数
      * 获取String参数
      */
      */
-    public static String getParameter(String name, String defaultValue)
-    {
+    public static String getParameter(String name, String defaultValue) {
         return Convert.toStr(getRequest().getParameter(name), defaultValue);
         return Convert.toStr(getRequest().getParameter(name), defaultValue);
     }
     }
 
 
     /**
     /**
      * 获取Integer参数
      * 获取Integer参数
      */
      */
-    public static Integer getParameterToInt(String name)
-    {
+    public static Integer getParameterToInt(String name) {
         return Convert.toInt(getRequest().getParameter(name));
         return Convert.toInt(getRequest().getParameter(name));
     }
     }
 
 
     /**
     /**
      * 获取Integer参数
      * 获取Integer参数
      */
      */
-    public static Integer getParameterToInt(String name, Integer defaultValue)
-    {
+    public static Integer getParameterToInt(String name, Integer defaultValue) {
         return Convert.toInt(getRequest().getParameter(name), defaultValue);
         return Convert.toInt(getRequest().getParameter(name), defaultValue);
     }
     }
 
 
     /**
     /**
      * 获取Boolean参数
      * 获取Boolean参数
      */
      */
-    public static Boolean getParameterToBool(String name)
-    {
+    public static Boolean getParameterToBool(String name) {
         return Convert.toBool(getRequest().getParameter(name));
         return Convert.toBool(getRequest().getParameter(name));
     }
     }
 
 
     /**
     /**
      * 获取Boolean参数
      * 获取Boolean参数
      */
      */
-    public static Boolean getParameterToBool(String name, Boolean defaultValue)
-    {
+    public static Boolean getParameterToBool(String name, Boolean defaultValue) {
         return Convert.toBool(getRequest().getParameter(name), defaultValue);
         return Convert.toBool(getRequest().getParameter(name), defaultValue);
     }
     }
 
 
@@ -79,8 +76,7 @@ public class ServletUtils
      * @param request 请求对象{@link ServletRequest}
      * @param request 请求对象{@link ServletRequest}
      * @return Map
      * @return Map
      */
      */
-    public static Map<String, String[]> getParams(ServletRequest request)
-    {
+    public static Map<String, String[]> getParams(ServletRequest request) {
         final Map<String, String[]> map = request.getParameterMap();
         final Map<String, String[]> map = request.getParameterMap();
         return Collections.unmodifiableMap(map);
         return Collections.unmodifiableMap(map);
     }
     }
@@ -91,11 +87,9 @@ public class ServletUtils
      * @param request 请求对象{@link ServletRequest}
      * @param request 请求对象{@link ServletRequest}
      * @return Map
      * @return Map
      */
      */
-    public static Map<String, String> getParamMap(ServletRequest request)
-    {
+    public static Map<String, String> getParamMap(ServletRequest request) {
         Map<String, String> params = new HashMap<>();
         Map<String, String> params = new HashMap<>();
-        for (Map.Entry<String, String[]> entry : getParams(request).entrySet())
-        {
+        for (Map.Entry<String, String[]> entry : getParams(request).entrySet()) {
             params.put(entry.getKey(), StringUtils.join(entry.getValue(), ","));
             params.put(entry.getKey(), StringUtils.join(entry.getValue(), ","));
         }
         }
         return params;
         return params;
@@ -104,50 +98,42 @@ public class ServletUtils
     /**
     /**
      * 获取request
      * 获取request
      */
      */
-    public static HttpServletRequest getRequest()
-    {
+    public static HttpServletRequest getRequest() {
         return getRequestAttributes().getRequest();
         return getRequestAttributes().getRequest();
     }
     }
 
 
     /**
     /**
      * 获取response
      * 获取response
      */
      */
-    public static HttpServletResponse getResponse()
-    {
+    public static HttpServletResponse getResponse() {
         return getRequestAttributes().getResponse();
         return getRequestAttributes().getResponse();
     }
     }
 
 
     /**
     /**
      * 获取session
      * 获取session
      */
      */
-    public static HttpSession getSession()
-    {
+    public static HttpSession getSession() {
         return getRequest().getSession();
         return getRequest().getSession();
     }
     }
 
 
-    public static ServletRequestAttributes getRequestAttributes()
-    {
+    public static ServletRequestAttributes getRequestAttributes() {
         RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
         RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
         return (ServletRequestAttributes) attributes;
         return (ServletRequestAttributes) attributes;
     }
     }
 
 
     /**
     /**
      * 将字符串渲染到客户端
      * 将字符串渲染到客户端
-     * 
+     *
      * @param response 渲染对象
      * @param response 渲染对象
-     * @param string 待渲染的字符串
+     * @param string   待渲染的字符串
      */
      */
-    public static String renderString(HttpServletResponse response, String string)
-    {
-        try
-        {
+    public static String renderString(HttpServletResponse response, String string) {
+        try {
             response.setStatus(200);
             response.setStatus(200);
             response.setContentType("application/json");
             response.setContentType("application/json");
             response.setCharacterEncoding("utf-8");
             response.setCharacterEncoding("utf-8");
             response.getWriter().print(string);
             response.getWriter().print(string);
-        }
-        catch (IOException e)
-        {
+        } catch (IOException e) {
             e.printStackTrace();
             e.printStackTrace();
         }
         }
         return null;
         return null;
@@ -155,26 +141,22 @@ public class ServletUtils
 
 
     /**
     /**
      * 是否是Ajax异步请求
      * 是否是Ajax异步请求
-     * 
+     *
      * @param request
      * @param request
      */
      */
-    public static boolean isAjaxRequest(HttpServletRequest request)
-    {
+    public static boolean isAjaxRequest(HttpServletRequest request) {
         String accept = request.getHeader("accept");
         String accept = request.getHeader("accept");
-        if (accept != null && accept.contains("application/json"))
-        {
+        if (accept != null && accept.contains("application/json")) {
             return true;
             return true;
         }
         }
 
 
         String xRequestedWith = request.getHeader("X-Requested-With");
         String xRequestedWith = request.getHeader("X-Requested-With");
-        if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest"))
-        {
+        if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
             return true;
             return true;
         }
         }
 
 
         String uri = request.getRequestURI();
         String uri = request.getRequestURI();
-        if (StringUtil.inStringIgnoreCase(uri, ".json", ".xml"))
-        {
+        if (StringUtil.inStringIgnoreCase(uri, ".json", ".xml")) {
             return true;
             return true;
         }
         }
 
 
@@ -184,37 +166,73 @@ public class ServletUtils
 
 
     /**
     /**
      * 内容编码
      * 内容编码
-     * 
+     *
      * @param str 内容
      * @param str 内容
      * @return 编码后的内容
      * @return 编码后的内容
      */
      */
-    public static String urlEncode(String str)
-    {
-        try
-        {
-            return URLEncoder.encode(str, Constants.UTF8);
-        }
-        catch (UnsupportedEncodingException e)
-        {
-            return StringUtils.EMPTY;
-        }
+    public static String urlEncode(String str) {
+        return URLEncoder.encode(str, StandardCharsets.UTF_8);
     }
     }
 
 
     /**
     /**
      * 内容解码
      * 内容解码
-     * 
+     *
      * @param str 内容
      * @param str 内容
      * @return 解码后的内容
      * @return 解码后的内容
      */
      */
-    public static String urlDecode(String str)
-    {
-        try
-        {
-            return URLDecoder.decode(str, Constants.UTF8);
+    public static String urlDecode(String str) {
+        return URLDecoder.decode(str, StandardCharsets.UTF_8);
+    }
+
+    public static String getIpAddr() {
+        HttpServletRequest request = ServletUtils.getRequest();
+        return ServletUtils.getIpAddr(request);
+    }
+
+    /**
+     * 获取请求的ip地址
+     *
+     * @param request 请求对象
+     * @return /
+     */
+    public static String getIpAddr(HttpServletRequest request) {
+        if (request == null) {
+            return IP_UNKNOWN;
+        }
+        String ip = request.getHeader("x-forwarded-for");
+        if (ip == null || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("X-Forwarded-For");
         }
         }
-        catch (UnsupportedEncodingException e)
-        {
-            return StringUtils.EMPTY;
+        if (ip == null || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("WL-Proxy-Client-IP");
         }
         }
+        if (ip == null || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("X-Real-IP");
+        }
+        if (ip == null || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getRemoteAddr();
+        }
+        return "0:0:0:0:0:0:0:1".equals(ip) ? IP_LOCALHOST : getMultistageReverseProxyIp(ip);
+    }
+
+    private static String getMultistageReverseProxyIp(String ip) {
+        // 多级反向代理检测
+        if (ip != null && ip.indexOf(",") > 0) {
+            final String[] ips = ip.trim().split(",");
+            for (String subIp : ips) {
+                if (!isUnknown(subIp)) {
+                    ip = subIp;
+                    break;
+                }
+            }
+        }
+        return ip;
+    }
+
+    private static boolean isUnknown(String checkString) {
+        return StrUtil.isBlank(checkString) || IP_UNKNOWN.equalsIgnoreCase(checkString);
     }
     }
 }
 }

+ 4 - 0
service-base/src/main/java/com/simuwang/base/config/DaqProperties.java

@@ -15,6 +15,10 @@ public class DaqProperties {
     public static final String DAQ_CONFIG_PREFIX = "simuwang";
     public static final String DAQ_CONFIG_PREFIX = "simuwang";
 
 
     /**
     /**
+     * 是否启用quartz定时任务功能
+     */
+    private Boolean enableQuartz = Boolean.FALSE;
+    /**
      * 是否启用操作日志记录功能
      * 是否启用操作日志记录功能
      */
      */
     private Boolean enableLogging = Boolean.TRUE;
     private Boolean enableLogging = Boolean.TRUE;

+ 0 - 1
service-base/src/main/java/com/simuwang/base/config/ShiroConfig.java

@@ -148,7 +148,6 @@ public class ShiroConfig {
         map.put("/static/**", "anon");
         map.put("/static/**", "anon");
         map.put("/v1/login", "anon");
         map.put("/v1/login", "anon");
         map.put("/v1/rsa-key", "anon");
         map.put("/v1/rsa-key", "anon");
-        map.put("/test/**", "anon");
         map.put("/v1/**", "jwt");
         map.put("/v1/**", "jwt");
         map.put("/**", "jwt");
         map.put("/**", "jwt");
         return map;
         return map;

+ 6 - 0
service-base/src/main/java/com/simuwang/base/mapper/system/SysLogMapper.java

@@ -2,8 +2,14 @@ package com.simuwang.base.mapper.system;
 
 
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.simuwang.base.pojo.dos.sys.SysLogDO;
 import com.simuwang.base.pojo.dos.sys.SysLogDO;
+import org.apache.ibatis.annotations.Delete;
 import org.springframework.stereotype.Repository;
 import org.springframework.stereotype.Repository;
 
 
 @Repository
 @Repository
 public interface SysLogMapper extends BaseMapper<SysLogDO> {
 public interface SysLogMapper extends BaseMapper<SysLogDO> {
+    /**
+     * 清空日志
+     */
+    @Delete("truncate table sys_log")
+    void truncateAll();
 }
 }

+ 17 - 9
service-base/src/main/java/com/simuwang/logging/Logging.java

@@ -34,15 +34,15 @@ public class Logging implements Serializable {
     /**
     /**
      * 提供一个包含所有参数的构造器,方便子类继承后扩展
      * 提供一个包含所有参数的构造器,方便子类继承后扩展
      *
      *
-     * @param title       标题
-     * @param type        日志类型
-     * @param requestUri  请求地址
-     * @param method      请求method
-     * @param params      请求参数
-     * @param result      执行结果
-     * @param executeTime 执行所用时间,单位:毫秒
-     * @param hasException   是否有异常
-     * @param exception   异常详情
+     * @param title        标题
+     * @param type         日志类型
+     * @param requestUri   请求地址
+     * @param method       请求method
+     * @param params       请求参数
+     * @param result       执行结果
+     * @param executeTime  执行所用时间,单位:毫秒
+     * @param hasException 是否有异常
+     * @param exception    异常详情
      */
      */
     public Logging(String title, Integer type, String requestUri, String method, String remoteAddr, Long executeTime,
     public Logging(String title, Integer type, String requestUri, String method, String remoteAddr, Long executeTime,
                    String params, String result, Boolean hasException, String exception) {
                    String params, String result, Boolean hasException, String exception) {
@@ -67,6 +67,14 @@ public class Logging implements Serializable {
         return new Builder();
         return new Builder();
     }
     }
 
 
+    @Override
+    public String toString() {
+        return "{title='" + title + '\'' +
+                ", requestUri='" + requestUri + '\'' +
+                ", remoteAddr='" + remoteAddr + '\'' +
+                ", executeTime=" + executeTime + '}';
+    }
+
     public String getTitle() {
     public String getTitle() {
         return title;
         return title;
     }
     }

+ 58 - 19
service-base/src/main/java/com/simuwang/shiro/core/jwt/JwtContext.java

@@ -1,5 +1,7 @@
 package com.simuwang.shiro.core.jwt;
 package com.simuwang.shiro.core.jwt;
 
 
+import cn.hutool.core.map.MapUtil;
+import cn.hutool.core.util.StrUtil;
 import com.auth0.jwt.JWT;
 import com.auth0.jwt.JWT;
 import com.auth0.jwt.exceptions.JWTDecodeException;
 import com.auth0.jwt.exceptions.JWTDecodeException;
 import com.auth0.jwt.interfaces.DecodedJWT;
 import com.auth0.jwt.interfaces.DecodedJWT;
@@ -23,8 +25,9 @@ public class JwtContext {
     public static final String HEADER = "Authorization";
     public static final String HEADER = "Authorization";
     //    private static final String SECRET = "qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm12";
     //    private static final String SECRET = "qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm12";
 //    private static final long EXPIRE = 60 * 24 * 7;
 //    private static final long EXPIRE = 60 * 24 * 7;
-    private static final Cache<String, String> USER_TOKEN_CACHE = Caffeine.newBuilder().maximumSize(16384L).build();
+    private static final Cache<String, Map<String, String>> USER_TOKEN_CACHE = Caffeine.newBuilder().maximumSize(16384L).build();
     private final DaqProperties properties;
     private final DaqProperties properties;
+
     public JwtContext(DaqProperties properties) {
     public JwtContext(DaqProperties properties) {
         this.properties = properties;
         this.properties = properties;
     }
     }
@@ -41,34 +44,70 @@ public class JwtContext {
 //        System.out.println("username = " + username);
 //        System.out.println("username = " + username);
 //    }
 //    }
 
 
-    public void setUserCache(String token) {
+    /**
+     * 设置用户token缓存
+     *
+     * @param requestIP 请求的ip地址
+     * @param token     用户登录token
+     */
+    private void setUserCache(String requestIP, String token) {
         String username = this.getClaimsByToken(token).getSubject();
         String username = this.getClaimsByToken(token).getSubject();
-        USER_TOKEN_CACHE.put(username, token);
+        Map<String, String> tokenMap = USER_TOKEN_CACHE.getIfPresent(username);
+        if (MapUtil.isEmpty(tokenMap)) {
+            tokenMap = MapUtil.newConcurrentHashMap(16);
+        }
+        tokenMap.putIfAbsent(requestIP, token);
+        USER_TOKEN_CACHE.put(username, tokenMap);
     }
     }
 
 
-    public String getUserCache(String username) {
-        return USER_TOKEN_CACHE.getIfPresent(username);
+    /**
+     * 获取用户token缓存
+     *
+     * @param username  用户账号
+     * @param requestIp 请求ip
+     * @return /
+     */
+    public String getUserCache(String username, String requestIp) {
+        Map<String, String> tokenMap = USER_TOKEN_CACHE.getIfPresent(username);
+        if (MapUtil.isNotEmpty(tokenMap)) {
+            return tokenMap.get(requestIp);
+        }
+        return null;
     }
     }
 
 
-    public void cleanUserCache(String username) {
-        USER_TOKEN_CACHE.invalidate(username);
+    /**
+     * 清理token缓存
+     *
+     * @param username  用户账号
+     * @param requestIp 请求ip
+     */
+    public void cleanUserCache(String username, String requestIp) {
+        Map<String, String> tokenMap = USER_TOKEN_CACHE.getIfPresent(username);
+        if (MapUtil.isNotEmpty(tokenMap)) {
+            tokenMap.remove(requestIp);
+        }
     }
     }
 
 
     /**
     /**
      * 生成jwt token
      * 生成jwt token
      */
      */
-    public String generateToken(String username) {
-        SecretKey signingKey = Keys.hmacShaKeyFor(this.properties.getTokenSecret().getBytes(StandardCharsets.UTF_8));
-        //过期时间
-        LocalDateTime tokenExpirationTime = LocalDateTime.now().plusMinutes(this.properties.getTokenExpire());
-        return Jwts.builder()
-                .signWith(signingKey, Jwts.SIG.HS512)
-                .header().add("typ", "JWT").and()
-                .issuedAt(Timestamp.valueOf(LocalDateTime.now()))
-                .subject(username)
-                .expiration(Timestamp.valueOf(tokenExpirationTime))
-                .claims(Map.of("username", username))
-                .compact();
+    public synchronized String generateToken(String username, String requestIp) {
+        String token = this.getUserCache(username, requestIp);
+        if (StrUtil.isBlank(token)) {
+            SecretKey signingKey = Keys.hmacShaKeyFor(this.properties.getTokenSecret().getBytes(StandardCharsets.UTF_8));
+            //过期时间
+            LocalDateTime tokenExpirationTime = LocalDateTime.now().plusMinutes(this.properties.getTokenExpire());
+            token = Jwts.builder()
+                    .signWith(signingKey, Jwts.SIG.HS512)
+                    .header().add("typ", "JWT").and()
+                    .issuedAt(Timestamp.valueOf(LocalDateTime.now()))
+                    .subject(username)
+                    .expiration(Timestamp.valueOf(tokenExpirationTime))
+                    .claims(Map.of("username", username))
+                    .compact();
+            this.setUserCache(requestIp, token);
+        }
+        return token;
     }
     }
 
 
     public Claims getClaimsByToken(String token) {
     public Claims getClaimsByToken(String token) {

+ 3 - 1
service-base/src/main/java/com/simuwang/shiro/core/jwt/JwtFilter.java

@@ -3,6 +3,7 @@ package com.simuwang.shiro.core.jwt;
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.json.JSONUtil;
 import cn.hutool.json.JSONUtil;
+import com.simuwang.base.common.util.ServletUtils;
 import com.simuwang.base.config.DaqProperties;
 import com.simuwang.base.config.DaqProperties;
 import com.smppw.common.pojo.ResultVo;
 import com.smppw.common.pojo.ResultVo;
 import io.jsonwebtoken.Claims;
 import io.jsonwebtoken.Claims;
@@ -82,7 +83,8 @@ public class JwtFilter extends AccessControlFilter {
             return false;
             return false;
         }
         }
         String username = claims.getSubject();
         String username = claims.getSubject();
-        String validToken = this.jwtContext.getUserCache(username);
+        String requestIp = ServletUtils.getIpAddr(request);
+        String validToken = this.jwtContext.getUserCache(username, requestIp);
         if (!token.equals(validToken)) {
         if (!token.equals(validToken)) {
             this.onLoginFail(servletResponse, requestURI, "token非法");
             this.onLoginFail(servletResponse, requestURI, "token非法");
             return false;
             return false;

+ 2 - 5
service-deploy/src/main/java/com/simuwang/deploy/components/ApiAop.java

@@ -1,6 +1,7 @@
 package com.simuwang.deploy.components;
 package com.simuwang.deploy.components;
 
 
 import cn.hutool.core.exceptions.ExceptionUtil;
 import cn.hutool.core.exceptions.ExceptionUtil;
+import com.simuwang.base.common.util.ServletUtils;
 import com.smppw.common.pojo.ResultVo;
 import com.smppw.common.pojo.ResultVo;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletRequest;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.ProceedingJoinPoint;
@@ -10,10 +11,6 @@ import org.aspectj.lang.annotation.Pointcut;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-
-import java.util.Objects;
 
 
 @Aspect
 @Aspect
 @Component
 @Component
@@ -39,7 +36,7 @@ public class ApiAop {
 
 
     @Around("pointcut()")
     @Around("pointcut()")
     public Object spentTime(ProceedingJoinPoint thisJoinPoint) throws Throwable {
     public Object spentTime(ProceedingJoinPoint thisJoinPoint) throws Throwable {
-        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
+        HttpServletRequest request = ServletUtils.getRequest();
         String url = request.getServletPath();
         String url = request.getServletPath();
         Object[] args = thisJoinPoint.getArgs();
         Object[] args = thisJoinPoint.getArgs();
         if (this.logger.isInfoEnabled()) {
         if (this.logger.isInfoEnabled()) {

+ 6 - 47
service-deploy/src/main/java/com/simuwang/deploy/components/LoggingAspect.java

@@ -4,6 +4,7 @@ import cn.hutool.core.exceptions.ExceptionUtil;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.core.util.URLUtil;
 import cn.hutool.core.util.URLUtil;
 import cn.hutool.json.JSONUtil;
 import cn.hutool.json.JSONUtil;
+import com.simuwang.base.common.util.ServletUtils;
 import com.simuwang.logging.Logging;
 import com.simuwang.logging.Logging;
 import com.simuwang.logging.LoggingService;
 import com.simuwang.logging.LoggingService;
 import com.simuwang.logging.SystemLog;
 import com.simuwang.logging.SystemLog;
@@ -16,8 +17,6 @@ import org.slf4j.LoggerFactory;
 import org.springframework.aop.support.AopUtils;
 import org.springframework.aop.support.AopUtils;
 import org.springframework.core.annotation.Order;
 import org.springframework.core.annotation.Order;
 import org.springframework.util.StopWatch;
 import org.springframework.util.StopWatch;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
 
 
 import java.util.Objects;
 import java.util.Objects;
 
 
@@ -44,9 +43,9 @@ public class LoggingAspect {
         if (systemLog != null && StrUtil.isNotBlank(systemLog.value())) {
         if (systemLog != null && StrUtil.isNotBlank(systemLog.value())) {
             title = systemLog.value() + "-" + title;
             title = systemLog.value() + "-" + title;
         }
         }
-        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
+        HttpServletRequest request = ServletUtils.getRequest();
         Logging.Builder builder = Logging.builder().title(title).type(annotation.type().getValue()).method(request.getMethod())
         Logging.Builder builder = Logging.builder().title(title).type(annotation.type().getValue()).method(request.getMethod())
-                .requestUri(URLUtil.getPath(request.getRequestURI())).remoteAddr(this.getIpAddr(request))
+                .requestUri(URLUtil.getPath(request.getRequestURI())).remoteAddr(ServletUtils.getIpAddr(request))
                 .params(joinPoint.getArgs() == null ? Objects.toString(request.getParameterMap()) : JSONUtil.toJsonStr(joinPoint.getArgs()));
                 .params(joinPoint.getArgs() == null ? Objects.toString(request.getParameterMap()) : JSONUtil.toJsonStr(joinPoint.getArgs()));
         StopWatch watch = new StopWatch();
         StopWatch watch = new StopWatch();
         watch.start();
         watch.start();
@@ -61,53 +60,13 @@ public class LoggingAspect {
         } finally {
         } finally {
             watch.stop();
             watch.stop();
             builder.executeTime(watch.getTotalTimeMillis());
             builder.executeTime(watch.getTotalTimeMillis());
+            Logging logging = builder.build();
             try {
             try {
-                this.service.asyncSave(builder.build());
+                this.service.asyncSave(logging);
             } catch (Exception e) {
             } catch (Exception e) {
-                this.logger.warn("日志保存报\n{}", ExceptionUtil.stacktraceToString(e));
+                this.logger.warn("请求{} 日志保存报\n{}", logging, ExceptionUtil.stacktraceToString(e));
             }
             }
         }
         }
         return result;
         return result;
     }
     }
-
-    public String getIpAddr(HttpServletRequest request) {
-        if (request == null) {
-            return "unknown";
-        }
-        String ip = request.getHeader("x-forwarded-for");
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
-            ip = request.getHeader("Proxy-Client-IP");
-        }
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
-            ip = request.getHeader("X-Forwarded-For");
-        }
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
-            ip = request.getHeader("WL-Proxy-Client-IP");
-        }
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
-            ip = request.getHeader("X-Real-IP");
-        }
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
-            ip = request.getRemoteAddr();
-        }
-        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
-    }
-
-    private String getMultistageReverseProxyIp(String ip) {
-        // 多级反向代理检测
-        if (ip != null && ip.indexOf(",") > 0) {
-            final String[] ips = ip.trim().split(",");
-            for (String subIp : ips) {
-                if (!isUnknown(subIp)) {
-                    ip = subIp;
-                    break;
-                }
-            }
-        }
-        return ip;
-    }
-
-    private boolean isUnknown(String checkString) {
-        return StrUtil.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
-    }
 }
 }

+ 2 - 0
service-deploy/src/main/resources/application.yml

@@ -56,6 +56,8 @@ email:
 
 
 # 配置
 # 配置
 simuwang:
 simuwang:
+  # 是否启用quartz定时任务功能
+  enable-quartz: false
   # 操作日志功能是否启用,启用了才会记录操作日志
   # 操作日志功能是否启用,启用了才会记录操作日志
   enable-logging: true
   enable-logging: true
   default-pwd: "QWER1234!@#$"
   default-pwd: "QWER1234!@#$"

+ 6 - 4
service-manage/src/main/java/com/simuwang/manage/api/LoginController.java

@@ -1,6 +1,7 @@
 package com.simuwang.manage.api;
 package com.simuwang.manage.api;
 
 
 import cn.hutool.core.map.MapUtil;
 import cn.hutool.core.map.MapUtil;
+import com.simuwang.base.common.util.ServletUtils;
 import com.simuwang.base.config.DaqProperties;
 import com.simuwang.base.config.DaqProperties;
 import com.simuwang.logging.SystemLog;
 import com.simuwang.logging.SystemLog;
 import com.simuwang.manage.dto.LoginUser;
 import com.simuwang.manage.dto.LoginUser;
@@ -40,7 +41,7 @@ public class LoginController {
      *
      *
      * @return /
      * @return /
      */
      */
-    @SystemLog(value = "获取公钥", type = SystemLog.Type.QUERY)
+//    @SystemLog(value = "获取公钥", type = SystemLog.Type.QUERY)
     @GetMapping("rsa-key")
     @GetMapping("rsa-key")
     public Map<String, Object> getRsaKey() {
     public Map<String, Object> getRsaKey() {
         return MapUtil.<String, Object>builder("rsaKey", this.properties.getSecurityRsa().getPublicKey()).build();
         return MapUtil.<String, Object>builder("rsaKey", this.properties.getSecurityRsa().getPublicKey()).build();
@@ -60,8 +61,8 @@ public class LoginController {
         Subject subject = UserUtils.getSubject();
         Subject subject = UserUtils.getSubject();
         subject.login(shiroToken);
         subject.login(shiroToken);
 
 
-        String token = jwtContext.generateToken(loginUser.getUsername());
-        this.jwtContext.setUserCache(token);
+        String requestIp = ServletUtils.getIpAddr();
+        String token = this.jwtContext.generateToken(loginUser.getUsername(), requestIp);
         // 加这response会导致响应头和shiro的默认字符集存在冲突,导致接口500
         // 加这response会导致响应头和shiro的默认字符集存在冲突,导致接口500
 //        response.setHeader(JwtContext.HEADER, token);
 //        response.setHeader(JwtContext.HEADER, token);
 //        response.setHeader("Access-control-Expost-Headers", JwtContext.HEADER);
 //        response.setHeader("Access-control-Expost-Headers", JwtContext.HEADER);
@@ -77,7 +78,8 @@ public class LoginController {
     public ResultVo<Boolean> logout() {
     public ResultVo<Boolean> logout() {
         Subject subject = UserUtils.getSubject();
         Subject subject = UserUtils.getSubject();
         ShiroUser shiroUser = UserUtils.getLoginUser(subject);
         ShiroUser shiroUser = UserUtils.getLoginUser(subject);
-        this.jwtContext.cleanUserCache(shiroUser.getUsername());
+        String requestIp = ServletUtils.getIpAddr();
+        this.jwtContext.cleanUserCache(shiroUser.getUsername(), requestIp);
         subject.logout();
         subject.logout();
         return ResultVo.ok(ResultCode.SUCCESS.getCode(), "退出成功", true);
         return ResultVo.ok(ResultCode.SUCCESS.getCode(), "退出成功", true);
     }
     }

+ 12 - 0
service-manage/src/main/java/com/simuwang/manage/init/QuartzConfig.java

@@ -3,6 +3,7 @@ package com.simuwang.manage.init;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSON;
 import com.simuwang.base.common.enums.OpenStatusType;
 import com.simuwang.base.common.enums.OpenStatusType;
 import com.simuwang.base.common.util.QuartzUtils;
 import com.simuwang.base.common.util.QuartzUtils;
+import com.simuwang.base.config.DaqProperties;
 import com.simuwang.base.pojo.dos.MailboxInfoDO;
 import com.simuwang.base.pojo.dos.MailboxInfoDO;
 import com.simuwang.base.pojo.dto.MailboxInfoDTO;
 import com.simuwang.base.pojo.dto.MailboxInfoDTO;
 import com.simuwang.base.pojo.dto.QuartzBean;
 import com.simuwang.base.pojo.dto.QuartzBean;
@@ -38,8 +39,19 @@ public class QuartzConfig implements ApplicationRunner {
     @Value("${spring.application.name}")
     @Value("${spring.application.name}")
     private String groupName;
     private String groupName;
     private String JOB_CLASS="com.simuwang.manage.task.ParseSchedulerTask";
     private String JOB_CLASS="com.simuwang.manage.task.ParseSchedulerTask";
+
+    private final Boolean enableQuartz;
+
+    public QuartzConfig(DaqProperties properties) {
+        this.enableQuartz = properties.getEnableQuartz();
+    }
+
     @Override
     @Override
     public void run(ApplicationArguments args){
     public void run(ApplicationArguments args){
+        // 没有开启定时任务功能时直接退出
+        if (!enableQuartz) {
+            return;
+        }
         List<MailboxInfoDO> mailboxInfoDOS = emailConfigService.getAll();
         List<MailboxInfoDO> mailboxInfoDOS = emailConfigService.getAll();
         for(MailboxInfoDO mailboxInfoDO : mailboxInfoDOS){
         for(MailboxInfoDO mailboxInfoDO : mailboxInfoDOS){
             try{
             try{

+ 2 - 1
service-manage/src/main/java/com/simuwang/manage/service/impl/system/SysLogServiceImpl.java

@@ -63,6 +63,7 @@ public class SysLogServiceImpl implements SysLogService {
 
 
     @Override
     @Override
     public boolean truncate() {
     public boolean truncate() {
-        return false;
+        this.mapper.truncateAll();
+        return true;
     }
     }
 }
 }