From 48c6db93631b1916f9bb0f70f82fda2b50ecdc43 Mon Sep 17 00:00:00 2001
From: huminmin <mac@MacBook-Pro.local>
Date: 星期六, 25 四月 2026 11:25:09 +0800
Subject: [PATCH] Merge branch 'dev_New_pro' of http://114.132.189.42:9002/r/product-inventory-management-after into dev_New_pro

---
 src/main/java/com/ruoyi/framework/security/service/TokenService.java |  137 +++++++++++++++++++++++++++++++++++++--------
 1 files changed, 113 insertions(+), 24 deletions(-)

diff --git a/src/main/java/com/ruoyi/framework/security/service/TokenService.java b/src/main/java/com/ruoyi/framework/security/service/TokenService.java
index e09ffe2..35802db 100644
--- a/src/main/java/com/ruoyi/framework/security/service/TokenService.java
+++ b/src/main/java/com/ruoyi/framework/security/service/TokenService.java
@@ -1,14 +1,6 @@
 package com.ruoyi.framework.security.service;
 
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-import javax.servlet.http.HttpServletRequest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.ruoyi.common.constant.CacheConstants;
 import com.ruoyi.common.constant.Constants;
 import com.ruoyi.common.utils.ServletUtils;
@@ -18,10 +10,27 @@
 import com.ruoyi.common.utils.uuid.IdUtils;
 import com.ruoyi.framework.redis.RedisCache;
 import com.ruoyi.framework.security.LoginUser;
+import com.ruoyi.project.system.domain.SysRole;
+import com.ruoyi.project.system.domain.SysUserDept;
+import com.ruoyi.project.system.mapper.SysUserDeptMapper;
 import eu.bitwalker.useragentutils.UserAgent;
 import io.jsonwebtoken.Claims;
 import io.jsonwebtoken.Jwts;
-import io.jsonwebtoken.SignatureAlgorithm;
+import io.jsonwebtoken.security.Keys;
+import jakarta.servlet.http.HttpServletRequest;
+import lombok.RequiredArgsConstructor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.util.CollectionUtils;
+
+import javax.crypto.SecretKey;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 /**
  * token楠岃瘉澶勭悊
@@ -29,6 +38,7 @@
  * @author ruoyi
  */
 @Component
+@RequiredArgsConstructor
 public class TokenService
 {
     private static final Logger log = LoggerFactory.getLogger(TokenService.class);
@@ -49,10 +59,9 @@
 
     protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
 
-    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
+    private static final Long MILLIS_MINUTE_TWENTY = 20 * 60 * 1000L;
 
-    @Autowired
-    private RedisCache redisCache;
+    private final RedisCache redisCache;
 
     /**
      * 鑾峰彇鐢ㄦ埛韬唤淇℃伅
@@ -127,18 +136,20 @@
     /**
      * 楠岃瘉浠ょ墝鏈夋晥鏈燂紝鐩稿樊涓嶈冻20鍒嗛挓锛岃嚜鍔ㄥ埛鏂扮紦瀛�
      * 
-     * @param token 浠ょ墝
+     * @param loginUser 鐧诲綍淇℃伅
      * @return 浠ょ墝
      */
     public void verifyToken(LoginUser loginUser)
     {
         long expireTime = loginUser.getExpireTime();
         long currentTime = System.currentTimeMillis();
-        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
+        if (expireTime - currentTime <= MILLIS_MINUTE_TWENTY)
         {
             refreshToken(loginUser);
         }
     }
+
+    private final SysUserDeptMapper sysUserDeptMapper;
 
     /**
      * 鍒锋柊浠ょ墝鏈夋晥鏈�
@@ -149,11 +160,83 @@
     {
         loginUser.setLoginTime(System.currentTimeMillis());
         loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
+        loginUser.setDeptIds(getDeptIdsByUserId(loginUser.getUserId()));
+        if (loginUser.getDeptIds() != null && loginUser.getDeptIds().length > 0)
+        {
+            loginUser.setCurrentDeptId(loginUser.getDeptIds()[0]);
+        }
+        loginUser.setDataScope(resolveDataScope(loginUser));
         // 鏍规嵁uuid灏唋oginUser缂撳瓨
         String userKey = getTokenKey(loginUser.getToken());
         redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
     }
-    
+
+    public String resolveDataScope(LoginUser loginUser)
+    {
+        if (loginUser == null || loginUser.getUser() == null || CollectionUtils.isEmpty(loginUser.getUser().getRoles()))
+        {
+            return null;
+        }
+        boolean hasCustom = false;
+        boolean hasDeptAndChild = false;
+        boolean hasDept = false;
+        boolean hasSelf = false;
+        for (SysRole role : loginUser.getUser().getRoles())
+        {
+            if (role == null || !"0".equals(role.getStatus()))
+            {
+                continue;
+            }
+            if ("1".equals(role.getDataScope()))
+            {
+                return "1";
+            }
+            if ("2".equals(role.getDataScope()))
+            {
+                hasCustom = true;
+            }
+            else if ("4".equals(role.getDataScope()))
+            {
+                hasDeptAndChild = true;
+            }
+            else if ("3".equals(role.getDataScope()))
+            {
+                hasDept = true;
+            }
+            else if ("5".equals(role.getDataScope()))
+            {
+                hasSelf = true;
+            }
+        }
+        if (hasCustom)
+        {
+            return "2";
+        }
+        if (hasDeptAndChild)
+        {
+            return "4";
+        }
+        if (hasDept)
+        {
+            return "3";
+        }
+        if (hasSelf)
+        {
+            return "5";
+        }
+        return null;
+    }
+
+    public Long[] getDeptIdsByUserId(Long userId){
+        LambdaQueryWrapper<SysUserDept> sysUserDeptLambdaQueryWrapper = new LambdaQueryWrapper<>();
+        sysUserDeptLambdaQueryWrapper.eq(SysUserDept::getUserId, userId);
+        List<SysUserDept> sysUserDept = sysUserDeptMapper.selectList(sysUserDeptLambdaQueryWrapper);
+        if(CollectionUtils.isEmpty(sysUserDept)){
+            return null;
+        }
+        return sysUserDept.stream().map(SysUserDept::getDeptId).toArray(Long[]::new);
+    }
+
     /**
      * 璁剧疆鐢ㄦ埛浠g悊淇℃伅
      * 
@@ -168,7 +251,12 @@
         loginUser.setBrowser(userAgent.getBrowser().getName());
         loginUser.setOs(userAgent.getOperatingSystem().getName());
     }
-    
+
+    private SecretKey getSigningKey() {
+        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
+        return Keys.hmacShaKeyFor(keyBytes);
+    }
+
     /**
      * 浠庢暟鎹0鏄庣敓鎴愪护鐗�
      *
@@ -177,10 +265,10 @@
      */
     private String createToken(Map<String, Object> claims)
     {
-        String token = Jwts.builder()
-                .setClaims(claims)
-                .signWith(SignatureAlgorithm.HS512, secret).compact();
-        return token;
+        return Jwts.builder()
+                .claims(claims) // 娉ㄦ剰锛氭柊鐗堟柟娉曞悕鍙樹簡锛屼笉鍐嶆槸 setClaims
+                .signWith(getSigningKey(), Jwts.SIG.HS512) // 浣跨敤鏂扮殑绛惧悕甯搁噺
+                .compact();
     }
 
     /**
@@ -192,9 +280,10 @@
     private Claims parseToken(String token)
     {
         return Jwts.parser()
-                .setSigningKey(secret)
-                .parseClaimsJws(token)
-                .getBody();
+                .verifyWith(getSigningKey()) // 鏂扮増浣跨敤 verifyWith
+                .build()
+                .parseSignedClaims(token)
+                .getPayload();
     }
 
     /**

--
Gitblit v1.9.3