diff --git a/awardBE/src/main/java/edu/ncst/award/config/security/CustomUserCache.java b/awardBE/src/main/java/edu/ncst/award/config/security/CustomUserCache.java new file mode 100644 index 0000000..247de6b --- /dev/null +++ b/awardBE/src/main/java/edu/ncst/award/config/security/CustomUserCache.java @@ -0,0 +1,82 @@ +package edu.ncst.award.config.security; + +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONUtil; +import edu.ncst.award.model.system.User; +import edu.ncst.award.utils.StringUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.security.core.userdetails.UserCache; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + + +@Slf4j +@Component +public class CustomUserCache implements UserCache { + private final RedisTemplate redisCacheTemplate; + + public CustomUserCache(RedisTemplate redisCacheTemplate) { + this.redisCacheTemplate = redisCacheTemplate; + } + + /** + * Obtains a {@link UserDetails} from the cache. + * + * @param username the {@link User#getUsername()} used to place the user in the cache + * @return the populated UserDetails or null if the user + * could not be found or if the cache entry has expired + */ + @Override + public UserDetails getUserFromCache(String username) { + UserDetails userDetails = null; + try { + String userJson = redisCacheTemplate.opsForValue().get(username); + if (!StrUtil.isEmpty(userJson)){ + userDetails = JSONUtil.toBean(userJson, User.class); + } + log.info("Cache read" + "username: " + username); + } catch (Exception e) { + e.printStackTrace(); + } + return userDetails; + } + + /** + * Places a {@link UserDetails} in the cache. The username is the key + * used to subsequently retrieve the UserDetails. + * + * @param user the fully populated UserDetails to place in the cache + */ + @Override + public void putUserInCache(UserDetails user) { + try { + redisCacheTemplate.opsForValue().set(user.getUsername(), JSONUtil.toJsonStr(user)); + log.info("Cache put" + "username: " + user.getUsername()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Removes the specified user from the cache. The username is the key + * used to remove the user. If the user is not found, the method should simply return + * (not thrown an exception). + *

+ * Some cache implementations may not support eviction from the cache, in which case + * they should provide appropriate behaviour to alter the user in either its + * documentation, via an exception, or through a log message. + * + * @param username to be evicted from the cache + */ + @Override + public void removeUserFromCache(String username) { + try { + redisCacheTemplate.delete(username); + log.info("Cache delete" + "username: " + username); + } catch (Exception e) { + e.printStackTrace(); + } + } +}