瀏覽代碼

代码优化

24282 1 年之前
父節點
當前提交
c209c5f7a7
共有 15 個文件被更改,包括 31 次插入86 次删除
  1. 0 1
      ruoyi-framework/src/main/java/com/ruoyi/framework/aspect/LogAspect.java
  2. 2 0
      ruoyi-framework/src/main/java/com/ruoyi/framework/mybatis/MybatisPlusConfig.java
  3. 0 6
      ruoyi-framework/src/main/java/com/ruoyi/framework/mybatis/RemoveParam.java
  4. 2 0
      ruoyi-framework/src/main/java/com/ruoyi/framework/security/context/AuthenticationContextHolder.java
  5. 2 0
      ruoyi-framework/src/main/java/com/ruoyi/framework/security/context/PermissionContextHolder.java
  6. 2 0
      ruoyi-framework/src/main/java/com/ruoyi/framework/security/filter/JwtAuthenticationTokenFilter.java
  7. 3 3
      ruoyi-framework/src/main/java/com/ruoyi/framework/security/handle/AuthenticationEntryPointImpl.java
  8. 3 10
      ruoyi-framework/src/main/java/com/ruoyi/framework/security/handle/LogoutSuccessHandlerImpl.java
  9. 1 1
      ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java
  10. 2 2
      ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/PermissionService.java
  11. 4 2
      ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java
  12. 1 1
      ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java
  13. 3 2
      ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPermissionService.java
  14. 4 5
      ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java
  15. 2 53
      ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java

+ 0 - 1
ruoyi-framework/src/main/java/com/ruoyi/framework/aspect/LogAspect.java

@@ -113,7 +113,6 @@ public class LogAspect {
         } catch (Exception exp) {
             // 记录本地异常日志
             log.error("异常信息:{}", exp.getMessage());
-            exp.printStackTrace();
         } finally {
             TIME_THREADLOCAL.remove();
         }

+ 2 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/mybatis/MybatisPlusConfig.java

@@ -69,6 +69,8 @@ public class MybatisPlusConfig {
         paginationInnerInterceptor.setMaxLimit(-1L);
         // 翻页溢出处理
         paginationInnerInterceptor.setOverflow(true);
+        // count优化
+        paginationInnerInterceptor.setOptimizeJoin(true);
         return paginationInnerInterceptor;
     }
 

+ 0 - 6
ruoyi-framework/src/main/java/com/ruoyi/framework/mybatis/RemoveParam.java

@@ -26,7 +26,6 @@ public class RemoveParam implements BeanPostProcessor {
 
         if (bean instanceof IService) {
             Class<?> entityClass = ((IService<?>) bean).getEntityClass();
-
             TableName annotation = entityClass.getAnnotation(TableName.class);
             String tableName;
             if (annotation != null && StrUtil.isNotBlank(annotation.value())) {
@@ -34,26 +33,21 @@ public class RemoveParam implements BeanPostProcessor {
             } else {
                 tableName = StrUtil.toUnderlineCase(entityClass.getSimpleName());
             }
-
             Field[] fields = ReflectUtil.getFields(entityClass);
             for (Field field : fields) {
-
                 TableField tableField = field.getAnnotation(TableField.class);
                 if (tableField == null) {
                     continue;
                 }
-
                 FieldFill fill = tableField.fill();
                 if (ObjectUtil.notEqual(fill, FieldFill.INSERT_UPDATE) && ObjectUtil.notEqual(fill, FieldFill.UPDATE)) {
                     continue;
                 }
-
                 if ("update_time".equals(tableField.value()) || "updateTime".equals(field.getName())) {
                     RemoveParam.updateTimeMap.put(tableName, true);
                 } else if ("update_user".equals(tableField.value()) || "updateUser".equals(field.getName())) {
                     RemoveParam.updateUserMap.put(tableName, true);
                 }
-
             }
         }
 

+ 2 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/security/context/AuthenticationContextHolder.java

@@ -8,6 +8,7 @@ import org.springframework.security.core.Authentication;
  * @author ruoyi
  */
 public class AuthenticationContextHolder {
+
     private static final ThreadLocal<Authentication> contextHolder = new ThreadLocal<>();
 
     public static Authentication getContext() {
@@ -21,4 +22,5 @@ public class AuthenticationContextHolder {
     public static void clearContext() {
         contextHolder.remove();
     }
+
 }

+ 2 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/security/context/PermissionContextHolder.java

@@ -10,6 +10,7 @@ import org.springframework.web.context.request.RequestContextHolder;
  * @author ruoyi
  */
 public class PermissionContextHolder {
+
     private static final String PERMISSION_CONTEXT_ATTRIBUTES = "PERMISSION_CONTEXT";
 
     public static String getContext() {
@@ -21,4 +22,5 @@ public class PermissionContextHolder {
         RequestContextHolder.currentRequestAttributes().setAttribute(PERMISSION_CONTEXT_ATTRIBUTES, permission,
                 RequestAttributes.SCOPE_REQUEST);
     }
+
 }

+ 2 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/security/filter/JwtAuthenticationTokenFilter.java

@@ -24,6 +24,7 @@ import java.io.IOException;
  */
 @Component
 public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
+
     @Autowired
     private TokenService tokenService;
 
@@ -39,4 +40,5 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
         }
         chain.doFilter(request, response);
     }
+
 }

+ 3 - 3
ruoyi-framework/src/main/java/com/ruoyi/framework/security/handle/AuthenticationEntryPointImpl.java

@@ -11,7 +11,6 @@ import org.springframework.stereotype.Component;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
 import java.io.Serializable;
 
 /**
@@ -21,13 +20,14 @@ import java.io.Serializable;
  */
 @Component
 public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
+
     private static final long serialVersionUID = -8970718410437077606L;
 
     @Override
-    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
-            throws IOException {
+    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
         int code = HttpStatus.UNAUTHORIZED;
         String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
         ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
     }
+
 }

+ 3 - 10
ruoyi-framework/src/main/java/com/ruoyi/framework/security/handle/LogoutSuccessHandlerImpl.java

@@ -1,23 +1,18 @@
 package com.ruoyi.framework.security.handle;
 
 import com.alibaba.fastjson2.JSON;
-import com.ruoyi.common.constant.Constants;
 import com.ruoyi.common.core.domain.AjaxResult;
 import com.ruoyi.common.core.domain.model.LoginUser;
 import com.ruoyi.common.utils.ServletUtils;
 import com.ruoyi.common.utils.StringUtils;
-import com.ruoyi.framework.manager.AsyncManager;
-import com.ruoyi.framework.manager.factory.AsyncFactory;
 import com.ruoyi.framework.web.service.TokenService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
 
-import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
 
 /**
  * 自定义退出处理类 返回成功
@@ -26,6 +21,7 @@ import java.io.IOException;
  */
 @Configuration
 public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
+
     @Autowired
     private TokenService tokenService;
 
@@ -35,16 +31,13 @@ public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
      * @return
      */
     @Override
-    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
-            throws IOException, ServletException {
+    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
         LoginUser loginUser = tokenService.getLoginUser(request);
         if (StringUtils.isNotNull(loginUser)) {
-            // String userName = loginUser.getUsername();
             // 删除用户缓存记录
             tokenService.delLoginUser(loginUser.getToken());
-            // 记录用户退出日志
-            // AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
         }
         ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success("退出成功")));
     }
+
 }

+ 1 - 1
ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java

@@ -61,7 +61,7 @@ public class GlobalExceptionHandler {
      * 业务异常
      */
     @ExceptionHandler(ServiceException.class)
-    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) {
+    public AjaxResult handleServiceException(ServiceException e) {
         Integer code = e.getCode();
         return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
     }

+ 2 - 2
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/PermissionService.java

@@ -56,7 +56,7 @@ public class PermissionService {
      * @return 用户是否不具备某权限
      */
     public boolean lacksPermi(String permission) {
-        return hasPermi(permission) != true;
+        return !hasPermi(permission);
     }
 
     /**
@@ -113,7 +113,7 @@ public class PermissionService {
      * @return 用户是否不具备某角色
      */
     public boolean lacksRole(String role) {
-        return hasRole(role) != true;
+        return !hasRole(role);
     }
 
     /**

+ 4 - 2
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java

@@ -35,8 +35,6 @@ import javax.annotation.Resource;
  */
 @Component
 public class SysLoginService {
-    @Autowired
-    private TokenService tokenService;
 
     @Resource
     private AuthenticationManager authenticationManager;
@@ -45,6 +43,9 @@ public class SysLoginService {
     private RedisCache redisCache;
 
     @Autowired
+    private TokenService tokenService;
+
+    @Autowired
     private ISysUserService userService;
 
     @Autowired
@@ -170,4 +171,5 @@ public class SysLoginService {
         sysUser.setLoginDate(DateUtils.getNowDate());
         userService.updateUserProfile(sysUser);
     }
+
 }

+ 1 - 1
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java

@@ -60,7 +60,7 @@ public class SysPasswordService {
             retryCount = 0;
         }
 
-        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
+        if (retryCount >= maxRetryCount) {
             AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                     MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
             throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);

+ 3 - 2
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPermissionService.java

@@ -18,6 +18,7 @@ import java.util.Set;
  */
 @Component
 public class SysPermissionService {
+
     @Autowired
     private ISysRoleService roleService;
 
@@ -31,7 +32,7 @@ public class SysPermissionService {
      * @return 角色权限信息
      */
     public Set<String> getRolePermission(SysUser user) {
-        Set<String> roles = new HashSet<String>();
+        Set<String> roles = new HashSet<>();
         // 管理员拥有所有权限
         if (user.isAdmin()) {
             roles.add("admin");
@@ -48,7 +49,7 @@ public class SysPermissionService {
      * @return 菜单权限信息
      */
     public Set<String> getMenuPermission(SysUser user) {
-        Set<String> perms = new HashSet<String>();
+        Set<String> perms = new HashSet<>();
         // 管理员拥有所有权限
         if (user.isAdmin()) {
             perms.add("*:*:*");

+ 4 - 5
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java

@@ -45,7 +45,7 @@ public class SysRegisterService {
         // 验证码开关
         boolean captchaEnabled = configService.selectCaptchaEnabled();
         if (captchaEnabled) {
-            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
+            validateCaptcha(registerBody.getCode(), registerBody.getUuid());
         }
 
         if (StringUtils.isEmpty(username)) {
@@ -76,12 +76,11 @@ public class SysRegisterService {
     /**
      * 校验验证码
      *
-     * @param username 用户名
-     * @param code     验证码
-     * @param uuid     唯一标识
+     * @param code 验证码
+     * @param uuid 唯一标识
      * @return 结果
      */
-    public void validateCaptcha(String username, String code, String uuid) {
+    public void validateCaptcha(String code, String uuid) {
         String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
         String captcha = redisCache.getCacheObject(verifyKey);
         redisCache.deleteObject(verifyKey);

+ 2 - 53
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java

@@ -4,7 +4,6 @@ import com.ruoyi.common.constant.CacheConstants;
 import com.ruoyi.common.constant.Constants;
 import com.ruoyi.common.core.domain.model.LoginUser;
 import com.ruoyi.common.core.redis.RedisCache;
-import com.ruoyi.common.exception.ServiceException;
 import com.ruoyi.common.utils.ServletUtils;
 import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.common.utils.ip.AddressUtils;
@@ -19,10 +18,9 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
-import javax.crypto.Cipher;
-import javax.crypto.spec.SecretKeySpec;
 import javax.servlet.http.HttpServletRequest;
-import java.util.*;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -178,17 +176,6 @@ public class TokenService {
     }
 
     /**
-     * 从令牌中获取用户名
-     *
-     * @param token 令牌
-     * @return 用户名
-     */
-    public String getUsernameFromToken(String token) {
-        Claims claims = parseToken(token);
-        return claims.getSubject();
-    }
-
-    /**
      * 获取请求token
      *
      * @param request
@@ -196,11 +183,6 @@ public class TokenService {
      */
     private String getToken(HttpServletRequest request) {
         String token = request.getHeader(header);
-        // //token添加新的解码规则
-        // if (StringUtils.isNotEmpty(token)) {
-        //     String randomStr = request.getHeader("Randomnumber");
-        //     token = decodeToken(token, randomStr);
-        // }
         if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
             token = token.replace(Constants.TOKEN_PREFIX, "");
         }
@@ -211,37 +193,4 @@ public class TokenService {
         return CacheConstants.LOGIN_TOKEN_KEY + uuid;
     }
 
-    /**
-     * 解析解密后的token
-     *
-     * @param data      加密后的密文
-     * @param randomStr 20位随机字符
-     * @return 解密出的token
-     */
-    private String decodeToken(String data, String randomStr) {
-        try {
-            // 获取密钥
-            SecretKeySpec secretKey = new SecretKeySpec("N[9f%2gKyo7(GNv3".getBytes(), "AES");
-            // 解析密文
-            Cipher cipher = Cipher.getInstance("AES");
-            cipher.init(Cipher.DECRYPT_MODE, secretKey);
-            byte[] doFinal = cipher.doFinal(Base64.getDecoder().decode(data));
-            String decrypt = new String(doFinal, "UTF-8");
-            int decryptLength = decrypt.length();
-            // 解析token
-            String decodeRandomStr = decrypt.substring(decryptLength - 20);
-            String decodeTime = decrypt.substring(decryptLength - 33, decryptLength - 20);
-            String decodeToken = decrypt.substring(0, decryptLength - 33);
-            // 校验token
-            long newTime = new Date().getTime();
-            //时间戳有效时间5秒内
-            if (newTime - Long.parseLong(decodeTime) > 5000 || !Objects.equals(randomStr, decodeRandomStr)) {
-                throw new ServiceException("非法请求,无效用户令牌");
-            }
-            return decodeToken;
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-            throw new ServiceException("非法请求,用户令牌解析失败");
-        }
-    }
 }