Kaynağa Gözat

调整 auth-service 的缓存 key 配置和 AccountInfo 中的字段

reghao 1 ay önce
ebeveyn
işleme
d16cae2868

+ 2 - 0
auth/auth-api/src/main/java/cn/reghao/tnb/auth/api/dto/AccountInfo.java

@@ -3,6 +3,7 @@ package cn.reghao.tnb.auth.api.dto;
 import lombok.*;
 
 import java.io.Serializable;
+import java.util.List;
 
 /**
  * @author reghao
@@ -22,4 +23,5 @@ public class AccountInfo implements Serializable {
     private String username;
     private String mobile;
     private String email;
+    private List<String> roles;
 }

+ 1 - 1
auth/auth-api/src/main/java/cn/reghao/tnb/auth/api/iface/AdminAccountService.java

@@ -13,6 +13,6 @@ public interface AdminAccountService {
     AccountRegistry getAccountRegistry();
     void setAccountRegistry(AccountRegistryStatus accountRegistryStatus);
     void setAccountCode(AccountRegistryStatus accountRegistryStatus);
-
     PageList<AccountInfo> getByScreenName(String screenName, int pageNumber, int pageSize);
+    void invalidCache(String key);
 }

+ 3 - 3
auth/auth-service/src/main/java/cn/reghao/tnb/auth/app/config/CacheConfig.java

@@ -24,12 +24,12 @@ import java.util.Objects;
 public class CacheConfig {
     @Bean
     public CacheManager cacheManager(RedisTemplate<String, Object> template) {
-        RedisCacheConfiguration config = RedisCacheConfiguration
-                .defaultCacheConfig()
+        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
+                .computePrefixWith(cacheName -> cacheName + ":")
                 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getStringSerializer()))
                 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getValueSerializer()))
                 .disableCachingNullValues()
-                .entryTtl(Duration.ofHours(1));
+                .entryTtl(Duration.ofMinutes(60));
 
         return RedisCacheManager.RedisCacheManagerBuilder
                         .fromConnectionFactory(Objects.requireNonNull(template.getConnectionFactory()))

+ 3 - 3
auth/auth-service/src/main/java/cn/reghao/tnb/auth/app/config/redis/RedisKeys.java

@@ -23,15 +23,15 @@ public class RedisKeys {
 
     public static String getPubkeyRKey() {
         String sessionId = ServletUtil.getSessionId();
-        return String.format("tnb:account:rsa:r:%s", sessionId);
+        return String.format("tnb:auth:rsa:r:%s", sessionId);
     }
 
     public static String getRsaPubkeyKey() {
-        return String.format("tnb:account:rsa:pubkey");
+        return String.format("tnb:auth:rsa:pubkey");
     }
 
     public static String getRsaPrikeyKey() {
-        return String.format("tnb:account:rsa:prikey");
+        return String.format("tnb:auth:rsa:prikey");
     }
 
     public static String getLoginFailedCountKey(long userId) {

+ 3 - 0
auth/auth-service/src/main/java/cn/reghao/tnb/auth/app/db/mapper/ApiKeyMapper.java

@@ -4,6 +4,8 @@ import cn.reghao.jutil.jdk.web.db.BaseMapper;
 import cn.reghao.tnb.auth.app.model.po.ApiKey;
 import org.apache.ibatis.annotations.Mapper;
 
+import java.util.List;
+
 /**
  * @author reghao
  * @date 2026-05-18 11:08:42
@@ -13,5 +15,6 @@ public interface ApiKeyMapper extends BaseMapper<ApiKey> {
     void deleteByAkAndUserId(String ak, Long userId);
     void updateById(ApiKey apiKey);
 
+    List<ApiKey> findByUserId(long userId);
     ApiKey findByAk(String ak);
 }

+ 11 - 2
auth/auth-service/src/main/java/cn/reghao/tnb/auth/app/db/repository/AccountRepository.java

@@ -1,5 +1,6 @@
 package cn.reghao.tnb.auth.app.db.repository;
 
+import cn.reghao.jutil.jdk.string.IDObfuscation;
 import cn.reghao.tnb.auth.api.dto.AccountInfo;
 import cn.reghao.tnb.auth.app.db.mapper.UserAccountMapper;
 import cn.reghao.tnb.auth.app.db.mapper.UserRoleMapper;
@@ -31,12 +32,14 @@ public class AccountRepository {
     private final UserAccountMapper userAccountMapper;
     private final UserRegistryMapper userRegistryMapper;
     private final UserRoleMapper userRoleMapper;
+    private final IDObfuscation userIdObfuscation;
 
     public AccountRepository(UserAccountMapper userAccountMapper, UserRegistryMapper userRegistryMapper,
-                             UserRoleMapper userRoleMapper) {
+                             UserRoleMapper userRoleMapper, IDObfuscation userIdObfuscation) {
         this.userAccountMapper = userAccountMapper;
         this.userRegistryMapper = userRegistryMapper;
         this.userRoleMapper = userRoleMapper;
+        this.userIdObfuscation = userIdObfuscation;
     }
 
     @Transactional(rollbackFor = Exception.class)
@@ -87,9 +90,12 @@ public class AccountRepository {
         return userId;
     }
 
+    // redis 中的 key 格式为 tnb:account:info:10002
     @Cacheable(cacheNames = "tnb:account:info", key = "#userId", unless = "#result == null")
     public AccountInfo getAccountInfo(long userId) {
         AccountInfo accountInfo = userAccountMapper.findAccountInfo(userId);
+        String userIdStr = userIdObfuscation.obfuscate(accountInfo.getUserId());
+        accountInfo.setUserIdStr(userIdStr);
         return accountInfo;
     }
 
@@ -172,7 +178,10 @@ public class AccountRepository {
 
     private UserAccount setAccountAuthorities(UserAccount userAccount) {
         Set<UserAuthority> set = userRoleMapper.findRolesByUserId(userAccount.getUserId()).stream()
-                .map(userRole -> new UserAuthority(userRole.getName()))
+                .map(userRole -> {
+                    String role = AccountRole.getByDesc(userRole.getName()).name();
+                    return new UserAuthority(role);
+                })
                 .collect(Collectors.toSet());
         userAccount.setAuthorities(set);
         return userAccount;

+ 17 - 1
auth/auth-service/src/main/java/cn/reghao/tnb/auth/app/rpc/AdminAccountServiceImpl.java

@@ -10,8 +10,11 @@ import cn.reghao.tnb.auth.app.model.po.UserRegistry;
 import cn.reghao.tnb.auth.app.service.AccountRegistryService;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.dubbo.config.annotation.DubboService;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Service;
 
+import java.util.Set;
+
 /**
  * @author reghao
  * @date 2024-07-31 07:00:22
@@ -22,10 +25,13 @@ import org.springframework.stereotype.Service;
 public class AdminAccountServiceImpl implements AdminAccountService {
     private final AccountRepository accountRepository;
     private final AccountRegistryService accountRegistryService;
+    private RedisTemplate<String, Object> redisTemplate;
 
-    public AdminAccountServiceImpl(AccountRepository accountRepository, AccountRegistryService accountRegistryService) {
+    public AdminAccountServiceImpl(AccountRepository accountRepository, AccountRegistryService accountRegistryService,
+                                   RedisTemplate<String, Object> redisTemplate) {
         this.accountRepository = accountRepository;
         this.accountRegistryService = accountRegistryService;
+        this.redisTemplate = redisTemplate;
     }
 
     @Override
@@ -48,7 +54,17 @@ public class AdminAccountServiceImpl implements AdminAccountService {
         accountRepository.updateUserRegistry(userRegistry);
     }
 
+    @Override
     public PageList<AccountInfo> getByScreenName(String screenName, int pageNumber, int pageSize) {
         return PageList.empty();
     }
+
+    @Override
+    public void invalidCache(String key) {
+        String pattern = key + "*";
+        Set<String> keys = redisTemplate.keys(pattern);
+        if (!keys.isEmpty()) {
+            redisTemplate.delete(keys);
+        }
+    }
 }

+ 1 - 1
auth/auth-service/src/main/java/cn/reghao/tnb/auth/app/service/AccountProfileService.java

@@ -48,7 +48,7 @@ public class AccountProfileService {
 
         AccountAuthToken authToken = accountTokenService.getAuthToken();
         long userId = authToken.getUserId();
-        accountRepository.addUserRole(userId, accountRole.getValue());
+        accountRepository.addUserRole(userId, accountRole.getDesc());
         return Result.success();
     }
 

+ 3 - 1
auth/auth-service/src/main/java/cn/reghao/tnb/auth/app/service/ApiKeyService.java

@@ -5,6 +5,7 @@ import cn.reghao.tnb.auth.app.model.dto.ApiKeyDto;
 import cn.reghao.tnb.auth.app.model.po.ApiKey;
 import cn.reghao.tnb.auth.app.model.vo.ApiKeyCacheDTO;
 import cn.reghao.tnb.auth.app.model.vo.ApiKeyCreateVO;
+import cn.reghao.tnb.common.auth.UserContext;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.springframework.data.redis.core.StringRedisTemplate;
@@ -116,6 +117,7 @@ public class ApiKeyService {
     }
 
     public List<ApiKey> getKey() {
-        return apiKeyMapper.findAll();
+        long loginUser = UserContext.getUserId();
+        return apiKeyMapper.findByUserId(loginUser);
     }
 }

+ 5 - 0
auth/auth-service/src/main/resources/mapper/ApiKeyMapper.xml

@@ -30,4 +30,9 @@
         from account_api_key
         where access_key=#{ak}
     </select>
+    <select id="findByUserId" resultType="cn.reghao.tnb.auth.app.model.po.ApiKey">
+        select *
+        from account_api_key
+        where user_id=#{userId}
+    </select>
 </mapper>

+ 17 - 1
auth/auth-service/src/main/resources/mapper/UserAccountMapper.xml

@@ -82,11 +82,27 @@
         from account_user_account
         where username=#{username}
     </select>
-    <select id="findAccountInfo" resultType="cn.reghao.tnb.auth.api.dto.AccountInfo">
+
+    <resultMap id="accountInfo" type="cn.reghao.tnb.auth.api.dto.AccountInfo">
+        <result property="userId" column="user_id"/>
+        <result property="screenName" column="screen_name"/>
+        <result property="avatarUrl" column="avatar_url"/>
+        <result property="username" column="username"/>
+        <result property="mobile" column="mobile"/>
+        <result property="email" column="email"/>
+        <collection property="roles" column="user_id" ofType="java.lang.String" select="findAccountRole"/>
+    </resultMap>
+    <select id="findAccountInfo" resultMap="accountInfo">
         select user_id,screen_name,avatar_url,username,mobile,email
         from account_user_account
         where user_id=#{userId}
     </select>
+    <select id="findAccountRole" resultType="java.lang.String">
+        select `name`
+        from account_user_role
+        where user_id=#{userId}
+    </select>
+
     <select id="findByUserId" resultType="cn.reghao.tnb.auth.app.model.po.UserAccount">
         select *
         from account_user_account