功能:收口小程序前后台安全与防重复提交
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
package com.xiaowang.yuminailcore.annotation;
|
||||
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface OperationGuard {
|
||||
|
||||
String action();
|
||||
|
||||
OperationGuardStrategy strategy() default OperationGuardStrategy.REJECT_IF_RUNNING;
|
||||
|
||||
int ttlSeconds() default 10;
|
||||
|
||||
String message() default "操作进行中,请勿重复点击";
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.xiaowang.yuminailcore.aspect;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardService;
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.time.Duration;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@Order(100)
|
||||
@RequiredArgsConstructor
|
||||
public class OperationGuardAspect {
|
||||
|
||||
private final OperationGuardService operationGuardService;
|
||||
|
||||
@Around("@annotation(operationGuard)")
|
||||
public Object guardOperation(ProceedingJoinPoint joinPoint, OperationGuard operationGuard) throws Throwable {
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (attributes == null) {
|
||||
return Result.error(500, "无法获取请求信息");
|
||||
}
|
||||
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
OperationGuardService.GuardHandle handle = operationGuardService.tryAcquire(
|
||||
request,
|
||||
operationGuard.action(),
|
||||
Duration.ofSeconds(Math.max(1, operationGuard.ttlSeconds()))
|
||||
);
|
||||
if (!handle.acquired()) {
|
||||
if (operationGuard.strategy() == OperationGuardStrategy.NOOP_IF_DUPLICATE) {
|
||||
return Result.success();
|
||||
}
|
||||
return Result.error(operationGuard.message());
|
||||
}
|
||||
|
||||
try {
|
||||
return joinPoint.proceed();
|
||||
} finally {
|
||||
operationGuardService.release(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
@@ -23,6 +25,7 @@ import java.lang.reflect.Method;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
@RequiredArgsConstructor
|
||||
public class PermissionAspect {
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 多级缓存配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "yuminail.cache")
|
||||
public class AppCacheProperties {
|
||||
|
||||
private long localMaxSize = 2048;
|
||||
|
||||
private CacheSpec productDetail = new CacheSpec(120, 900);
|
||||
|
||||
private CacheSpec productList = new CacheSpec(60, 300);
|
||||
|
||||
private CacheSpec productSearch = new CacheSpec(60, 300);
|
||||
|
||||
private CacheSpec shop = new CacheSpec(180, 900);
|
||||
|
||||
private CacheSpec tag = new CacheSpec(300, 1200);
|
||||
|
||||
@Data
|
||||
public static class CacheSpec {
|
||||
private long localTtlSeconds;
|
||||
private long redisTtlSeconds;
|
||||
|
||||
public CacheSpec() {
|
||||
}
|
||||
|
||||
public CacheSpec(long localTtlSeconds, long redisTtlSeconds) {
|
||||
this.localTtlSeconds = localTtlSeconds;
|
||||
this.redisTtlSeconds = redisTtlSeconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,13 @@ import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.support.security.RequestSignatureService;
|
||||
import com.xiaowang.yuminailcore.support.security.RequestThrottleService;
|
||||
import com.xiaowang.yuminailcore.support.security.UserSessionService;
|
||||
import com.xiaowang.yuminailcore.utils.JwtUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -19,6 +23,9 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
private final JwtUtil jwtUtil;
|
||||
private final UserMapper userMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
private final UserSessionService userSessionService;
|
||||
private final RequestSignatureService requestSignatureService;
|
||||
private final RequestThrottleService requestThrottleService;
|
||||
|
||||
private static final String AUTHORIZATION_HEADER = "Authorization";
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
@@ -39,9 +46,7 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
String token = authHeader.substring(BEARER_PREFIX.length());
|
||||
|
||||
if (!jwtUtil.validateToken(token)) {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期\"}");
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -53,6 +58,13 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
Long userId = jwtUtil.getUserIdFromToken(token);
|
||||
String account = jwtUtil.getAccountFromToken(token);
|
||||
Long currentShopId = jwtUtil.getShopIdFromToken(token);
|
||||
String sessionId = jwtUtil.getSessionIdFromToken(token);
|
||||
String jti = jwtUtil.getJtiFromToken(token);
|
||||
if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "登录态已失效,请重新登录");
|
||||
return false;
|
||||
}
|
||||
|
||||
UserDO currentUser = userMapper.selectById(userId);
|
||||
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效");
|
||||
@@ -84,14 +96,48 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (requiresSignature(request)) {
|
||||
try {
|
||||
requestSignatureService.validateRequest(request, token, userId);
|
||||
} catch (RuntimeException exception) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (requiresWriteRateLimit(request)) {
|
||||
try {
|
||||
requestThrottleService.checkAuthenticatedWrite(request, userId);
|
||||
} catch (RuntimeException exception) {
|
||||
writeJsonResponse(response, 429, exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
request.setAttribute("userId", userId);
|
||||
request.setAttribute("account", account);
|
||||
request.setAttribute("userType", currentUser.getType());
|
||||
request.setAttribute("accessToken", token);
|
||||
request.setAttribute("sessionId", sessionId);
|
||||
request.setAttribute("tokenJti", jti);
|
||||
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean requiresSignature(HttpServletRequest request) {
|
||||
return requiresWriteRateLimit(request);
|
||||
}
|
||||
|
||||
private boolean requiresWriteRateLimit(HttpServletRequest request) {
|
||||
String method = request.getMethod();
|
||||
if (!StringUtils.hasText(method)) {
|
||||
return false;
|
||||
}
|
||||
String normalized = method.toUpperCase();
|
||||
return !("GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized));
|
||||
}
|
||||
|
||||
private boolean isAdminPath(String path) {
|
||||
return path.startsWith("/admin/") || path.startsWith("/order/admin/");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* JWT 配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "yuminail.security.jwt")
|
||||
public class JwtProperties {
|
||||
|
||||
/**
|
||||
* HS512 密钥,生产环境请通过 Nacos 覆盖。
|
||||
*/
|
||||
private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
|
||||
|
||||
/**
|
||||
* Token 发行者。
|
||||
*/
|
||||
private String issuer = "yuminail";
|
||||
|
||||
/**
|
||||
* AccessToken 有效期,单位秒。
|
||||
*/
|
||||
private long accessTokenExpirationSeconds = 2 * 60 * 60;
|
||||
|
||||
/**
|
||||
* RefreshToken 有效期,单位秒。
|
||||
*/
|
||||
private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60;
|
||||
|
||||
/**
|
||||
* 时钟偏移容忍,单位秒。
|
||||
*/
|
||||
private long clockSkewSeconds = 30;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 限流配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "yuminail.security.rate-limit")
|
||||
public class RateLimitProperties {
|
||||
|
||||
private LimitRule login = new LimitRule(10, 60);
|
||||
|
||||
private LimitRule sendCode = new LimitRule(5, 60);
|
||||
|
||||
private LimitRule resetPassword = new LimitRule(5, 600);
|
||||
|
||||
private LimitRule authenticatedWrite = new LimitRule(80, 60);
|
||||
|
||||
private LimitRule orderCreate = new LimitRule(10, 60);
|
||||
|
||||
@Data
|
||||
public static class LimitRule {
|
||||
private int limit;
|
||||
private long windowSeconds;
|
||||
|
||||
public LimitRule() {
|
||||
}
|
||||
|
||||
public LimitRule(int limit, long windowSeconds) {
|
||||
this.limit = limit;
|
||||
this.windowSeconds = windowSeconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 请求签名配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "yuminail.security.signature")
|
||||
public class RequestSignatureProperties {
|
||||
|
||||
/**
|
||||
* 是否启用签名校验。
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
|
||||
/**
|
||||
* 时间窗口,单位秒。
|
||||
*/
|
||||
private long windowSeconds = 300;
|
||||
|
||||
/**
|
||||
* nonce 额外保留时间,单位秒。
|
||||
*/
|
||||
private long nonceRetentionSeconds = 600;
|
||||
}
|
||||
+12
-4
@@ -1,10 +1,13 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.LoginRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.RefreshTokenRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.SwitchShopRequestDTO;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.support.security.RequestThrottleService;
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
|
||||
import com.xiaowang.yuminailcore.utils.AccountValidationUtils;
|
||||
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
|
||||
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
|
||||
@@ -20,9 +23,12 @@ import javax.servlet.http.HttpServletRequest;
|
||||
public class AdminAuthController {
|
||||
|
||||
private final UserService userService;
|
||||
private final RequestThrottleService requestThrottleService;
|
||||
|
||||
@PostMapping("/login")
|
||||
public Result<LoginResponseVO> login(@Valid @RequestBody LoginRequestDTO loginRequestDTO) {
|
||||
@OperationGuard(action = "admin-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
|
||||
public Result<LoginResponseVO> login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) {
|
||||
requestThrottleService.checkLogin(request, loginRequestDTO.getAccount());
|
||||
LoginResponseVO loginResponseVO = userService.adminLogin(loginRequestDTO);
|
||||
return Result.success(loginResponseVO);
|
||||
}
|
||||
@@ -33,14 +39,16 @@ public class AdminAuthController {
|
||||
}
|
||||
|
||||
@PostMapping("/switch-shop")
|
||||
@OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作")
|
||||
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId()));
|
||||
return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId")));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
public Result<Boolean> logout() {
|
||||
return Result.success(true);
|
||||
@OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5)
|
||||
public Result<Boolean> logout(HttpServletRequest request) {
|
||||
return Result.success(userService.logout((String) request.getAttribute("sessionId")));
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
|
||||
+6
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.CouponDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
@@ -34,6 +35,7 @@ public class AdminCouponController {
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("coupon:create")
|
||||
@OperationGuard(action = "admin-coupon-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId());
|
||||
@@ -46,6 +48,7 @@ public class AdminCouponController {
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("coupon:edit")
|
||||
@OperationGuard(action = "admin-coupon-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
@@ -64,6 +67,7 @@ public class AdminCouponController {
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("coupon:delete")
|
||||
@OperationGuard(action = "admin-coupon-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
@@ -125,6 +129,7 @@ public class AdminCouponController {
|
||||
*/
|
||||
@PostMapping("/assign")
|
||||
@RequirePermission("coupon:assign")
|
||||
@OperationGuard(action = "admin-coupon-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(couponId);
|
||||
@@ -147,6 +152,7 @@ public class AdminCouponController {
|
||||
*/
|
||||
@PostMapping("/distribute")
|
||||
@RequirePermission("coupon:assign")
|
||||
@OperationGuard(action = "admin-coupon-distribute", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(couponId);
|
||||
|
||||
+2
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
@@ -75,6 +76,7 @@ public class AdminNailArtistController {
|
||||
|
||||
@RequirePermission("nail_artist:edit")
|
||||
@PostMapping("/save")
|
||||
@OperationGuard(action = "admin-nail-artist-save", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<NailArtistInfoDTO> saveNailArtistInfo(@RequestBody NailArtistInfoDTO nailArtistInfoDTO, HttpServletRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
if (currentUser == null) {
|
||||
|
||||
+2
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.OrderService;
|
||||
@@ -81,6 +82,7 @@ public class AdminOrderController {
|
||||
*/
|
||||
@PutMapping("/update-status/{id}")
|
||||
@RequirePermission("order:process")
|
||||
@OperationGuard(action = "admin-order-update-status", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> updateOrderStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
if (Integer.valueOf(3).equals(currentUser.getType())) {
|
||||
|
||||
+5
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.PermissionDTO;
|
||||
import com.xiaowang.yuminailcore.dto.UserPermissionDTO;
|
||||
@@ -26,6 +27,7 @@ public class AdminPermissionController {
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("permission:create")
|
||||
@OperationGuard(action = "admin-permission-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||
@@ -35,6 +37,7 @@ public class AdminPermissionController {
|
||||
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("permission:edit")
|
||||
@OperationGuard(action = "admin-permission-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||
@@ -44,6 +47,7 @@ public class AdminPermissionController {
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("permission:delete")
|
||||
@OperationGuard(action = "admin-permission-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> deletePermission(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||
@@ -108,6 +112,7 @@ public class AdminPermissionController {
|
||||
|
||||
@PostMapping("/assign/{userId}")
|
||||
@RequirePermission("permission:assign")
|
||||
@OperationGuard(action = "admin-permission-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> assignPermissions(
|
||||
HttpServletRequest request,
|
||||
@PathVariable Long userId,
|
||||
|
||||
+4
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.ProductDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
@@ -39,6 +40,7 @@ public class AdminProductController {
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("product:create")
|
||||
@OperationGuard(action = "admin-product-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId()));
|
||||
@@ -48,6 +50,7 @@ public class AdminProductController {
|
||||
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("product:edit")
|
||||
@OperationGuard(action = "admin-product-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
ProductVO productVO = productService.getProductById(id);
|
||||
@@ -63,6 +66,7 @@ public class AdminProductController {
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("product:delete")
|
||||
@OperationGuard(action = "admin-product-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> deleteProduct(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
ProductVO productVO = productService.getProductById(id);
|
||||
|
||||
+5
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.ShopDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
@@ -40,6 +41,7 @@ public class AdminShopController {
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("shop:create")
|
||||
@OperationGuard(action = "admin-shop-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以创建店铺");
|
||||
@@ -49,6 +51,7 @@ public class AdminShopController {
|
||||
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("shop:edit")
|
||||
@OperationGuard(action = "admin-shop-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
ShopVO shopVO = shopService.getShopById(id);
|
||||
@@ -62,6 +65,7 @@ public class AdminShopController {
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("shop:delete")
|
||||
@OperationGuard(action = "admin-shop-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> deleteShop(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺");
|
||||
@@ -71,6 +75,7 @@ public class AdminShopController {
|
||||
|
||||
@PutMapping("/status/{id}")
|
||||
@RequirePermission("shop:edit")
|
||||
@OperationGuard(action = "admin-shop-status", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺");
|
||||
|
||||
+4
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.TagDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
@@ -29,6 +30,7 @@ public class AdminTagController {
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("tag:create")
|
||||
@OperationGuard(action = "admin-tag-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createTag(HttpServletRequest request, @RequestBody TagDTO tagDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, tagDTO.getShopId()));
|
||||
@@ -41,6 +43,7 @@ public class AdminTagController {
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("tag:edit")
|
||||
@OperationGuard(action = "admin-tag-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateTag(HttpServletRequest request, @PathVariable Long id, @RequestBody TagDTO tagDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
TagVO tagVO = tagService.getTagById(id);
|
||||
@@ -59,6 +62,7 @@ public class AdminTagController {
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("tag:delete")
|
||||
@OperationGuard(action = "admin-tag-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> deleteTag(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
TagVO tagVO = tagService.getTagById(id);
|
||||
|
||||
+10
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.AdminUserBalanceChangeDTO;
|
||||
import com.xiaowang.yuminailcore.dto.AdminUserVipOverrideDTO;
|
||||
@@ -49,6 +50,7 @@ public class AdminUserController {
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("user:create")
|
||||
@OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
|
||||
@@ -63,6 +65,7 @@ public class AdminUserController {
|
||||
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("user:edit")
|
||||
@OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = userService.getUserById(id);
|
||||
@@ -83,6 +86,7 @@ public class AdminUserController {
|
||||
|
||||
@PutMapping("/status/{id}")
|
||||
@RequirePermission("user:disable")
|
||||
@OperationGuard(action = "admin-user-status", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> updateUserStatus(HttpServletRequest httpRequest, @PathVariable Long id, @RequestBody StatusRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(httpRequest);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以停用用户");
|
||||
@@ -100,6 +104,7 @@ public class AdminUserController {
|
||||
|
||||
@PostMapping("/reset-password/{userId}")
|
||||
@RequirePermission("user:reset_password")
|
||||
@OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> resetPassword(HttpServletRequest request, @PathVariable Long userId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
@@ -114,6 +119,7 @@ public class AdminUserController {
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("user:delete")
|
||||
@OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> deleteUser(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户");
|
||||
@@ -130,6 +136,7 @@ public class AdminUserController {
|
||||
|
||||
@PutMapping("/unbind/{id}")
|
||||
@RequirePermission("user:unbind")
|
||||
@OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> unbindUser(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = userService.getUserById(id);
|
||||
@@ -165,6 +172,7 @@ public class AdminUserController {
|
||||
|
||||
@PostMapping("/{id}/balance/change")
|
||||
@RequirePermission("user:balance:manage")
|
||||
@OperationGuard(action = "admin-user-balance-change", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<UserAssetVO> changeUserBalance(
|
||||
HttpServletRequest request,
|
||||
@PathVariable Long id,
|
||||
@@ -178,6 +186,7 @@ public class AdminUserController {
|
||||
|
||||
@PostMapping("/{id}/vip/override")
|
||||
@RequirePermission("user:vip:manage")
|
||||
@OperationGuard(action = "admin-user-vip-override", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<UserAssetVO> overrideUserVip(
|
||||
HttpServletRequest request,
|
||||
@PathVariable Long id,
|
||||
@@ -191,6 +200,7 @@ public class AdminUserController {
|
||||
|
||||
@PostMapping("/{id}/vip/recalculate")
|
||||
@RequirePermission("user:vip:manage")
|
||||
@OperationGuard(action = "admin-user-vip-recalculate", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<UserAssetVO> recalculateUserVip(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP");
|
||||
|
||||
+8
-1
@@ -1,8 +1,10 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.CartDTO;
|
||||
import com.xiaowang.yuminailcore.service.CartService;
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
|
||||
import com.xiaowang.yuminailcore.vo.CartVO;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -18,6 +20,7 @@ public class CartController {
|
||||
private CartService cartService;
|
||||
|
||||
@PostMapping("/add")
|
||||
@OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作")
|
||||
public Result<Void> addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.addToCart(userId, cartDTO);
|
||||
@@ -25,6 +28,7 @@ public class CartController {
|
||||
}
|
||||
|
||||
@DeleteMapping("/remove/{productId}")
|
||||
@OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<Void> removeFromCart(@PathVariable Long productId, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.removeFromCart(userId, productId);
|
||||
@@ -32,6 +36,7 @@ public class CartController {
|
||||
}
|
||||
|
||||
@PostMapping("/batch-remove")
|
||||
@OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<Void> batchRemoveFromCart(@RequestBody List<Long> cartItemIds, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.batchRemoveFromCart(userId, cartItemIds);
|
||||
@@ -39,6 +44,7 @@ public class CartController {
|
||||
}
|
||||
|
||||
@PutMapping("/update")
|
||||
@OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作")
|
||||
public Result<Void> updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.updateCartQuantity(userId, cartDTO);
|
||||
@@ -53,9 +59,10 @@ public class CartController {
|
||||
}
|
||||
|
||||
@DeleteMapping("/clear")
|
||||
@OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<Void> clearCart(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.clearCart(userId);
|
||||
return Result.success();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+7
-7
@@ -52,7 +52,7 @@ public class CouponController {
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券");
|
||||
Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId());
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId);
|
||||
boolean success = couponService.updateCoupon(id, couponDTO, shopId);
|
||||
@@ -70,7 +70,7 @@ public class CouponController {
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.deleteCoupon(id, shopId);
|
||||
return Result.success(success);
|
||||
@@ -85,7 +85,7 @@ public class CouponController {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO != null) {
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券");
|
||||
}
|
||||
return Result.success(couponVO);
|
||||
}
|
||||
@@ -113,12 +113,12 @@ public class CouponController {
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍙戞斁鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰彂鏀句紭鎯犲埜");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
|
||||
return Result.success(success);
|
||||
@@ -167,13 +167,13 @@ public class CouponController {
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍙戞斁鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
|
||||
for (Long userId : userIds) {
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰彂鏀句紭鎯犲埜");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
|
||||
}
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
|
||||
|
||||
+19
-17
@@ -3,13 +3,17 @@ package com.xiaowang.yuminailcore.controller;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 前台文件控制器
|
||||
* 提供前台用户可以访问的文件相关接口
|
||||
* 前台文件控制器,提供前台用户可访问的文件相关接口。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/file")
|
||||
@@ -18,31 +22,29 @@ public class FrontendFileController {
|
||||
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final MinioService minioService;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
/**
|
||||
* 获取带签名的图片链接(前台用户可访问)
|
||||
* 获取带签名的图片链接。
|
||||
*
|
||||
* @param fileId 文件ID
|
||||
* @param expiryTimeInMinutes 有效期(分钟),默认60分钟
|
||||
* @return 带签名的临时访问链接
|
||||
* @param fileId 文件 ID
|
||||
* @param expiryTimeInMinutes 有效期,默认 60 分钟
|
||||
* @return 临时可访问的签名地址
|
||||
*/
|
||||
@GetMapping("/get-signed-url/{fileId}")
|
||||
public Result<String> getSignedUrl(@PathVariable Long fileId, @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) {
|
||||
public Result<String> getSignedUrl(@PathVariable Long fileId,
|
||||
@RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) {
|
||||
try {
|
||||
ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId);
|
||||
if (fileVO == null) {
|
||||
return Result.error("文件不存在");
|
||||
}
|
||||
|
||||
// 从fileUrl中提取objectName
|
||||
String fileUrl = fileVO.getFileUrl();
|
||||
// 提取最后一个/后面的部分作为objectName
|
||||
int lastSlashIndex = fileUrl.lastIndexOf("/");
|
||||
if (lastSlashIndex == -1) {
|
||||
return Result.error("文件URL格式错误");
|
||||
|
||||
String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl());
|
||||
if (objectName == null || objectName.isEmpty()) {
|
||||
return Result.error("文件 URL 格式错误");
|
||||
}
|
||||
String objectName = fileUrl.substring(lastSlashIndex + 1);
|
||||
|
||||
|
||||
String signedUrl = minioService.getPresignedUrl(objectName, expiryTimeInMinutes);
|
||||
return Result.success(signedUrl);
|
||||
} catch (Exception e) {
|
||||
|
||||
+49
-72
@@ -1,5 +1,6 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.ChunkUploadCompleteRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.ChunkUploadInitRequestDTO;
|
||||
@@ -7,24 +8,31 @@ import com.xiaowang.yuminailcore.dto.ObjectStorageFileDTO;
|
||||
import com.xiaowang.yuminailcore.service.ChunkUploadService;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
|
||||
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 对象存储文件信息表 Controller
|
||||
* 对应数据库表 t_object_storage_file
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-13
|
||||
* 对象存储文件控制器,对应表 t_object_storage_file。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/admin/object-storage-file")
|
||||
@@ -35,15 +43,19 @@ public class ObjectStorageFileController {
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final MinioService minioService;
|
||||
private final ChunkUploadService chunkUploadService;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@PostMapping("/upload/init")
|
||||
public Result<ChunkUploadSessionVO> initChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
|
||||
@OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作")
|
||||
public Result<ChunkUploadSessionVO> initChunkUpload(HttpServletRequest request,
|
||||
@Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/upload/chunk")
|
||||
@OperationGuard(action = "admin-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20)
|
||||
public Result<Boolean> uploadChunk(HttpServletRequest request,
|
||||
@RequestParam("uploadId") String uploadId,
|
||||
@RequestParam("chunkIndex") Integer chunkIndex,
|
||||
@@ -55,16 +67,23 @@ public class ObjectStorageFileController {
|
||||
}
|
||||
|
||||
@PostMapping("/upload/complete")
|
||||
public Result<ObjectStorageFileVO> completeChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
|
||||
@OperationGuard(action = "admin-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
|
||||
public Result<ObjectStorageFileVO> completeChunkUpload(HttpServletRequest request,
|
||||
@Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
|
||||
chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId());
|
||||
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
|
||||
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
|
||||
String originalFilename = preparedUploadFile.getFileName();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
|
||||
|
||||
String fileUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
|
||||
String fileUrl = minioService.uploadStream(
|
||||
inputStream,
|
||||
preparedUploadFile.getFileSize(),
|
||||
preparedUploadFile.getContentType(),
|
||||
objectName
|
||||
);
|
||||
|
||||
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
|
||||
dto.setFileName(originalFilename);
|
||||
@@ -81,6 +100,7 @@ public class ObjectStorageFileController {
|
||||
}
|
||||
|
||||
@DeleteMapping("/upload/{uploadId}")
|
||||
@OperationGuard(action = "admin-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
|
||||
public Result<Boolean> cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId);
|
||||
@@ -88,29 +108,25 @@ public class ObjectStorageFileController {
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*
|
||||
* @param file 文件
|
||||
* @return 文件ID和URL
|
||||
* 上传文件。
|
||||
*/
|
||||
@PostMapping("/upload")
|
||||
@OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
|
||||
public Result<ObjectStorageFileVO> uploadFile(@RequestParam("file") MultipartFile file) {
|
||||
try {
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
|
||||
|
||||
|
||||
String fileUrl = minioService.uploadFile(file, objectName);
|
||||
|
||||
|
||||
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
|
||||
dto.setFileName(originalFilename);
|
||||
dto.setFileUrl(fileUrl);
|
||||
dto.setStatus(1);
|
||||
|
||||
|
||||
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
|
||||
ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId);
|
||||
|
||||
return Result.success(fileVO);
|
||||
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return Result.error("文件上传失败: " + e.getMessage());
|
||||
@@ -118,29 +134,22 @@ public class ObjectStorageFileController {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取带签名的图片链接
|
||||
*
|
||||
* @param fileId 文件ID
|
||||
* @param expiryTimeInMinutes 有效期(分钟),默认60分钟
|
||||
* @return 带签名的临时访问链接
|
||||
* 获取带签名的图片链接。
|
||||
*/
|
||||
@GetMapping("/get-signed-url/{fileId}")
|
||||
public Result<String> getSignedUrl(@PathVariable Long fileId, @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) {
|
||||
public Result<String> getSignedUrl(@PathVariable Long fileId,
|
||||
@RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) {
|
||||
try {
|
||||
ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId);
|
||||
if (fileVO == null) {
|
||||
return Result.error("文件不存在");
|
||||
}
|
||||
|
||||
// 从fileUrl中提取objectName
|
||||
String fileUrl = fileVO.getFileUrl();
|
||||
// 提取最后一个/后面的部分作为objectName
|
||||
int lastSlashIndex = fileUrl.lastIndexOf("/");
|
||||
if (lastSlashIndex == -1) {
|
||||
return Result.error("文件URL格式错误");
|
||||
|
||||
String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl());
|
||||
if (objectName == null || objectName.isEmpty()) {
|
||||
return Result.error("文件 URL 格式错误");
|
||||
}
|
||||
String objectName = fileUrl.substring(lastSlashIndex + 1);
|
||||
|
||||
|
||||
String signedUrl = minioService.getPresignedUrl(objectName, expiryTimeInMinutes);
|
||||
return Result.success(signedUrl);
|
||||
} catch (Exception e) {
|
||||
@@ -149,72 +158,40 @@ public class ObjectStorageFileController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建文件
|
||||
*
|
||||
* @param objectStorageFileDTO 文件DTO
|
||||
* @return 文件ID
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@OperationGuard(action = "admin-file-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createObjectStorageFile(@RequestBody ObjectStorageFileDTO objectStorageFileDTO) {
|
||||
Long id = objectStorageFileService.createObjectStorageFile(objectStorageFileDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新文件
|
||||
*
|
||||
* @param id 文件ID
|
||||
* @param objectStorageFileDTO 文件DTO
|
||||
* @return 是否更新成功
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
public Result<Boolean> updateObjectStorageFile(@PathVariable Long id, @RequestBody ObjectStorageFileDTO objectStorageFileDTO) {
|
||||
@OperationGuard(action = "admin-file-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateObjectStorageFile(@PathVariable Long id,
|
||||
@RequestBody ObjectStorageFileDTO objectStorageFileDTO) {
|
||||
boolean success = objectStorageFileService.updateObjectStorageFile(id, objectStorageFileDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件
|
||||
*
|
||||
* @param id 文件ID
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@OperationGuard(action = "admin-file-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> deleteObjectStorageFile(@PathVariable Long id) {
|
||||
boolean success = objectStorageFileService.deleteObjectStorageFile(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID查询文件
|
||||
*
|
||||
* @param id 文件ID
|
||||
* @return 文件VO
|
||||
*/
|
||||
@GetMapping("/get/{id}")
|
||||
public Result<ObjectStorageFileVO> getObjectStorageFileById(@PathVariable Long id) {
|
||||
ObjectStorageFileVO objectStorageFileVO = objectStorageFileService.getObjectStorageFileById(id);
|
||||
return Result.success(objectStorageFileVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有文件
|
||||
*
|
||||
* @return 文件VO列表
|
||||
*/
|
||||
@GetMapping("/list/all")
|
||||
public Result<List<ObjectStorageFileVO>> listAllObjectStorageFiles() {
|
||||
List<ObjectStorageFileVO> objectStorageFileVOs = objectStorageFileService.listAllObjectStorageFiles();
|
||||
return Result.success(objectStorageFileVOs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据状态查询文件
|
||||
*
|
||||
* @param status 文件状态
|
||||
* @return 文件VO列表
|
||||
*/
|
||||
@GetMapping("/list/status/{status}")
|
||||
public Result<List<ObjectStorageFileVO>> listObjectStorageFilesByStatus(@PathVariable Integer status) {
|
||||
List<ObjectStorageFileVO> objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
||||
@@ -24,6 +25,7 @@ public class OrderController {
|
||||
private UserService userService;
|
||||
|
||||
@PostMapping("/create")
|
||||
@OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击")
|
||||
public Result<OrderVO> createOrder(@RequestBody OrderDTO orderDTO, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
OrderVO orderVO = orderService.createOrder(userId, orderDTO);
|
||||
@@ -45,6 +47,7 @@ public class OrderController {
|
||||
}
|
||||
|
||||
@PutMapping("/cancel/{orderId}")
|
||||
@OperationGuard(action = "order-cancel", ttlSeconds = 15, message = "操作进行中,请勿重复点击")
|
||||
public Result<Void> cancelOrder(@PathVariable Long orderId, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
orderService.cancelOrder(orderId, userId);
|
||||
@@ -77,6 +80,7 @@ public class OrderController {
|
||||
|
||||
@RequirePermission("order:process")
|
||||
@PutMapping("/admin/process/{orderId}")
|
||||
@OperationGuard(action = "admin-order-process", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<Void> processOrder(@PathVariable Long orderId, @RequestParam Integer status, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Integer userType = (Integer) request.getAttribute("userType");
|
||||
@@ -119,6 +123,7 @@ public class OrderController {
|
||||
|
||||
@RequirePermission("order:process")
|
||||
@PutMapping("/artist/complete/{orderId}")
|
||||
@OperationGuard(action = "artist-order-complete", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<Void> completeArtistOrder(@PathVariable Long orderId, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Integer userType = (Integer) request.getAttribute("userType");
|
||||
|
||||
+4
-4
@@ -128,9 +128,9 @@ public class PermissionController {
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
UserDO targetUser = userService.getById(userId);
|
||||
if (targetUser == null) {
|
||||
throw new RuntimeException("鐩爣鐢ㄦ埛涓嶅瓨鍦?");
|
||||
throw new RuntimeException("目标用户不存在");
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛鏉冮檺");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限");
|
||||
}
|
||||
List<PermissionVO> permissionVOs = permissionService.listUserPermissions(userId);
|
||||
return Result.success(permissionVOs);
|
||||
@@ -149,9 +149,9 @@ public class PermissionController {
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
UserDO targetUser = userService.getById(userPermissionDTO.getUserId());
|
||||
if (targetUser == null) {
|
||||
throw new RuntimeException("鐩爣鐢ㄦ埛涓嶅瓨鍦?");
|
||||
throw new RuntimeException("目标用户不存在");
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰垎閰嶆潈闄?");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "无权给其他店铺用户分配权限");
|
||||
}
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
boolean success = permissionService.assignPermissions(userPermissionDTO, userId);
|
||||
|
||||
+12
-5
@@ -39,7 +39,7 @@ public class ProductController {
|
||||
if (productVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵鍟嗗搧");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权编辑其他店铺商品");
|
||||
Long targetShopId = productDTO.getShopId() != null ? productDTO.getShopId() : productVO.getShopId();
|
||||
productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId));
|
||||
boolean success = productService.updateProduct(id, productDTO);
|
||||
@@ -54,7 +54,7 @@ public class ProductController {
|
||||
if (productVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鍟嗗搧");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权删除其他店铺商品");
|
||||
boolean success = productService.deleteProduct(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -85,8 +85,15 @@ public class ProductController {
|
||||
|
||||
@GetMapping("/list/search")
|
||||
public Result<List<ProductVO>> searchProducts(@RequestParam("keyword") String keyword) {
|
||||
// 调用pageProducts方法,设置默认分页参数,只返回列表
|
||||
PageResultVO<ProductVO> pageResult = productService.pageProducts(1, 100, keyword, null);
|
||||
return Result.success(pageResult.getList());
|
||||
List<ProductVO> productVOs = productService.searchProducts(keyword);
|
||||
return Result.success(productVOs);
|
||||
}
|
||||
|
||||
@GetMapping("/list/page")
|
||||
public Result<PageResultVO<ProductVO>> pagePublicProducts(@RequestParam(defaultValue = "1") Integer page,
|
||||
@RequestParam(defaultValue = "10") Integer size,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) String tag) {
|
||||
return Result.success(productService.pagePublicProducts(page, size, keyword, tag));
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -1,7 +1,9 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.service.ProductLikeService;
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -26,6 +28,7 @@ public class ProductLikeController {
|
||||
* @return 是否成功
|
||||
*/
|
||||
@PostMapping("/like/{productId}")
|
||||
@OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<Boolean> likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) {
|
||||
productLikeService.addLike(userId, productId);
|
||||
return Result.success(true);
|
||||
@@ -39,6 +42,7 @@ public class ProductLikeController {
|
||||
* @return 是否成功
|
||||
*/
|
||||
@PostMapping("/unlike/{productId}")
|
||||
@OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<Boolean> unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) {
|
||||
productLikeService.removeLike(userId, productId);
|
||||
return Result.success(true);
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ public class ShopController {
|
||||
if (shopVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵淇℃伅");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "无权编辑其他店铺信息");
|
||||
boolean success = shopService.updateShop(id, shopDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ public class TagController {
|
||||
if (tagVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵鏍囩");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权编辑其他店铺标签");
|
||||
Long targetShopId = tagDTO.getShopId() != null ? tagDTO.getShopId() : tagVO.getShopId();
|
||||
tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId));
|
||||
boolean success = tagService.updateTag(id, tagDTO);
|
||||
@@ -79,7 +79,7 @@ public class TagController {
|
||||
if (tagVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鏍囩");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权删除其他店铺标签");
|
||||
boolean success = tagService.deleteTag(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -96,7 +96,7 @@ public class TagController {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
TagVO tagVO = tagService.getTagById(id);
|
||||
if (tagVO != null) {
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鏍囩");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签");
|
||||
}
|
||||
return Result.success(tagVO);
|
||||
}
|
||||
@@ -139,7 +139,7 @@ public class TagController {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
TagVO tagVO = tagService.getTagByTagName(tagName);
|
||||
if (tagVO != null) {
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鏍囩");
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签");
|
||||
}
|
||||
return Result.success(tagVO);
|
||||
}
|
||||
|
||||
+49
-13
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.*;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
@@ -17,7 +18,10 @@ import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.service.VerificationCodeService;
|
||||
import com.xiaowang.yuminailcore.service.WechatMiniAuthService;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.support.security.RequestThrottleService;
|
||||
import com.xiaowang.yuminailcore.utils.AccountValidationUtils;
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -49,6 +53,8 @@ public class UserController {
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final WechatMiniAuthService wechatMiniAuthService;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private final RequestThrottleService requestThrottleService;
|
||||
|
||||
/**
|
||||
* 创建用户
|
||||
@@ -58,6 +64,7 @@ public class UserController {
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("user:create")
|
||||
@OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
|
||||
@@ -79,9 +86,10 @@ public class UserController {
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("user:edit")
|
||||
@OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "鏃犳潈缂栬緫鍏朵粬搴楅摵鐢ㄦ埛");
|
||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权编辑其他店铺用户");
|
||||
if (userDTO.getType() != null) {
|
||||
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
|
||||
}
|
||||
@@ -101,6 +109,7 @@ public class UserController {
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("user:delete")
|
||||
@OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作进行中,请勿重复点击")
|
||||
public Result<Boolean> deleteUser(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户");
|
||||
@@ -114,6 +123,7 @@ public class UserController {
|
||||
|
||||
@PutMapping("/unbind/{id}")
|
||||
@RequirePermission("user:unbind")
|
||||
@OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作进行中,请勿重复点击")
|
||||
public Result<Boolean> unbindUser(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权解绑其他店铺用户");
|
||||
@@ -135,7 +145,7 @@ public class UserController {
|
||||
@RequirePermission("user:view")
|
||||
public Result<UserVO> getUserById(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO userVO = requireAccessibleUser(currentUser, id, "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛");
|
||||
UserVO userVO = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户");
|
||||
return Result.success(userVO);
|
||||
}
|
||||
|
||||
@@ -199,7 +209,7 @@ public class UserController {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO userVO = userService.getUserByAccount(AccountValidationUtils.requireValidAccount(account));
|
||||
if (userVO != null) {
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "无权查看其他店铺用户");
|
||||
}
|
||||
return Result.success(userVO);
|
||||
}
|
||||
@@ -262,7 +272,9 @@ public class UserController {
|
||||
* @return 登录响应VO
|
||||
*/
|
||||
@PostMapping("/login")
|
||||
public Result<LoginResponseVO> login(@Valid @RequestBody LoginRequestDTO loginRequestDTO) {
|
||||
@OperationGuard(action = "user-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
|
||||
public Result<LoginResponseVO> login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) {
|
||||
requestThrottleService.checkLogin(request, loginRequestDTO.getAccount());
|
||||
LoginResponseVO loginResponseVO = userService.login(loginRequestDTO);
|
||||
return Result.success(loginResponseVO);
|
||||
}
|
||||
@@ -274,30 +286,36 @@ public class UserController {
|
||||
* @return 登录响应VO
|
||||
*/
|
||||
@PostMapping("/phone-login")
|
||||
public Result<LoginResponseVO> phoneLogin(@RequestBody PhoneLoginRequestDTO phoneLoginRequestDTO) {
|
||||
@OperationGuard(action = "user-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
|
||||
public Result<LoginResponseVO> phoneLogin(HttpServletRequest request, @RequestBody PhoneLoginRequestDTO phoneLoginRequestDTO) {
|
||||
requestThrottleService.checkLogin(request, phoneLoginRequestDTO.getPhone());
|
||||
LoginResponseVO loginResponseVO = userService.phoneLogin(phoneLoginRequestDTO);
|
||||
return Result.success(loginResponseVO);
|
||||
}
|
||||
|
||||
@PostMapping("/wechat-mini/auto-login")
|
||||
@OperationGuard(action = "wechat-mini-auto-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
|
||||
public Result<WechatMiniLoginResultVO> wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
|
||||
return Result.success(wechatMiniAuthService.autoLogin(requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/wechat-mini/phone-login")
|
||||
@OperationGuard(action = "wechat-mini-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
|
||||
public Result<WechatMiniLoginResultVO> wechatMiniPhoneLogin(@Valid @RequestBody WechatMiniPhoneLoginRequestDTO requestDTO) {
|
||||
return Result.success(wechatMiniAuthService.phoneLogin(requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/wechat-mini/confirm-login")
|
||||
@OperationGuard(action = "wechat-mini-confirm-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
|
||||
public Result<WechatMiniLoginResultVO> confirmWechatMiniLogin(@Valid @RequestBody WechatMiniConfirmLoginRequestDTO requestDTO) {
|
||||
return Result.success(wechatMiniAuthService.confirmLogin(requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/switch-shop")
|
||||
@OperationGuard(action = "user-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作")
|
||||
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId()));
|
||||
return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId")));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -307,6 +325,7 @@ public class UserController {
|
||||
* @return 是否注册成功
|
||||
*/
|
||||
@PostMapping("/register")
|
||||
@OperationGuard(action = "user-register", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
|
||||
public Result<Boolean> register(@Valid @RequestBody RegisterRequestDTO registerRequestDTO) {
|
||||
boolean success = userService.register(registerRequestDTO);
|
||||
return Result.success(success);
|
||||
@@ -319,7 +338,9 @@ public class UserController {
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
@PostMapping("/send-verification-code")
|
||||
public Result<Boolean> sendVerificationCode(@RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) {
|
||||
@OperationGuard(action = "send-verification-code", ttlSeconds = 8, message = "验证码发送处理中,请稍后再试")
|
||||
public Result<Boolean> sendVerificationCode(HttpServletRequest request, @RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) {
|
||||
requestThrottleService.checkSendCode(request, sendVerificationCodeRequestDTO.getPhone());
|
||||
if (!verificationCodeService.canResend(sendVerificationCodeRequestDTO.getPhone())) {
|
||||
throw new RuntimeException("验证码发送过于频繁,请1分钟后再试");
|
||||
}
|
||||
@@ -334,7 +355,9 @@ public class UserController {
|
||||
* @return 是否重置成功
|
||||
*/
|
||||
@PostMapping("/reset-password-by-phone")
|
||||
public Result<Boolean> resetPasswordByPhone(@RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) {
|
||||
@OperationGuard(action = "reset-password-by-phone", ttlSeconds = 8, message = "操作进行中,请勿重复点击")
|
||||
public Result<Boolean> resetPasswordByPhone(HttpServletRequest request, @RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) {
|
||||
requestThrottleService.checkResetPassword(request, resetPasswordRequestDTO.getPhone());
|
||||
boolean success = userService.resetPasswordByPhone(resetPasswordRequestDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -357,8 +380,9 @@ public class UserController {
|
||||
* @return 是否登出成功
|
||||
*/
|
||||
@PostMapping("/logout")
|
||||
public Result<Boolean> logout() {
|
||||
boolean success = userService.logout();
|
||||
@OperationGuard(action = "user-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5)
|
||||
public Result<Boolean> logout(HttpServletRequest request) {
|
||||
boolean success = userService.logout((String) request.getAttribute("sessionId"));
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@@ -381,6 +405,7 @@ public class UserController {
|
||||
* @return 是否更新成功
|
||||
*/
|
||||
@PutMapping({"/update", "/info"})
|
||||
@OperationGuard(action = "user-update-info", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateCurrentUserInfo(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.updateCurrentUserInfo(userId, userDTO);
|
||||
@@ -394,6 +419,7 @@ public class UserController {
|
||||
* @return 是否绑定成功
|
||||
*/
|
||||
@PostMapping("/bind-phone")
|
||||
@OperationGuard(action = "user-bind-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> bindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO bindPhoneRequestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.bindPhone(userId, bindPhoneRequestDTO);
|
||||
@@ -407,6 +433,7 @@ public class UserController {
|
||||
* @return 是否绑定成功
|
||||
*/
|
||||
@PostMapping("/bind-email")
|
||||
@OperationGuard(action = "user-bind-email", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> bindEmail(HttpServletRequest request, @RequestBody BindEmailRequestDTO bindEmailRequestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.bindEmail(userId, bindEmailRequestDTO);
|
||||
@@ -420,12 +447,14 @@ public class UserController {
|
||||
* @return 头像URL
|
||||
*/
|
||||
@PostMapping("/upload-avatar/init")
|
||||
@OperationGuard(action = "user-avatar-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作")
|
||||
public Result<ChunkUploadSessionVO> initAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(chunkUploadService.initUserAvatarUpload(userId, requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/upload-avatar/chunk")
|
||||
@OperationGuard(action = "user-avatar-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20)
|
||||
public Result<Boolean> uploadAvatarChunk(HttpServletRequest request,
|
||||
@RequestParam("uploadId") String uploadId,
|
||||
@RequestParam("chunkIndex") Integer chunkIndex,
|
||||
@@ -437,6 +466,7 @@ public class UserController {
|
||||
}
|
||||
|
||||
@PostMapping("/upload-avatar/complete")
|
||||
@OperationGuard(action = "user-avatar-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
|
||||
public Result<String> completeAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
|
||||
@@ -449,7 +479,7 @@ public class UserController {
|
||||
String avatarUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
|
||||
userService.updateUserAvatar(userId, avatarUrl);
|
||||
chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId());
|
||||
return Result.success(avatarUrl);
|
||||
return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return Result.error("头像上传失败: " + e.getMessage());
|
||||
@@ -457,6 +487,7 @@ public class UserController {
|
||||
}
|
||||
|
||||
@DeleteMapping("/upload-avatar/{uploadId}")
|
||||
@OperationGuard(action = "user-avatar-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
|
||||
public Result<Boolean> cancelAvatarUpload(HttpServletRequest request, @PathVariable String uploadId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
chunkUploadService.clearUserAvatarUpload(userId, uploadId);
|
||||
@@ -464,6 +495,7 @@ public class UserController {
|
||||
}
|
||||
|
||||
@PostMapping("/upload-avatar")
|
||||
@OperationGuard(action = "user-avatar-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
|
||||
public Result<String> uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
|
||||
try {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
@@ -474,7 +506,7 @@ public class UserController {
|
||||
String avatarUrl = minioService.uploadFile(file, objectName);
|
||||
userService.updateUserAvatar(userId, avatarUrl);
|
||||
|
||||
return Result.success(avatarUrl);
|
||||
return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return Result.error("头像上传失败: " + e.getMessage());
|
||||
@@ -489,9 +521,10 @@ public class UserController {
|
||||
*/
|
||||
@PostMapping("/reset-password/{userId}")
|
||||
@RequirePermission("user:reset_password")
|
||||
@OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作进行中,请勿重复点击")
|
||||
public Result<Boolean> resetPassword(HttpServletRequest request, @PathVariable Long userId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
requireAccessibleUser(currentUser, userId, "鏃犳潈閲嶇疆鍏朵粬搴楅摵鐢ㄦ埛瀵嗙爜");
|
||||
requireAccessibleUser(currentUser, userId, "无权重置其他店铺用户密码");
|
||||
Long currentUserId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.resetPassword(userId, currentUserId);
|
||||
return Result.success(success);
|
||||
@@ -505,6 +538,7 @@ public class UserController {
|
||||
* @return 是否更新成功
|
||||
*/
|
||||
@PutMapping("/password")
|
||||
@OperationGuard(action = "user-update-password", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updatePassword(HttpServletRequest request, @RequestBody PasswordDTO passwordDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.updatePassword(userId, passwordDTO.getPassword(), passwordDTO.getVerificationCode());
|
||||
@@ -519,6 +553,7 @@ public class UserController {
|
||||
* @return 是否修改成功
|
||||
*/
|
||||
@PutMapping("/phone")
|
||||
@OperationGuard(action = "user-update-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updatePhone(HttpServletRequest request, @RequestBody UpdatePhoneRequestDTO updatePhoneDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.updatePhone(userId, updatePhoneDTO);
|
||||
@@ -532,6 +567,7 @@ public class UserController {
|
||||
* @return 是否注销成功
|
||||
*/
|
||||
@DeleteMapping("/deactivate")
|
||||
@OperationGuard(action = "user-deactivate", ttlSeconds = 10, message = "操作进行中,请勿重复点击")
|
||||
public Result<Boolean> deactivateAccount(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
|
||||
|
||||
+4
@@ -1,8 +1,10 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.WishlistDTO;
|
||||
import com.xiaowang.yuminailcore.service.WishlistService;
|
||||
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -17,6 +19,7 @@ public class WishlistController {
|
||||
private WishlistService wishlistService;
|
||||
|
||||
@PostMapping("/add")
|
||||
@OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<?> addToWishlist(@RequestBody Map<String, Long> request, @RequestAttribute("userId") Long userId) {
|
||||
Long productId = request.get("productId");
|
||||
wishlistService.addToWishlist(userId, productId);
|
||||
@@ -24,6 +27,7 @@ public class WishlistController {
|
||||
}
|
||||
|
||||
@PostMapping("/remove")
|
||||
@OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<?> removeFromWishlist(@RequestBody Map<String, Long> request, @RequestAttribute("userId") Long userId) {
|
||||
Long productId = request.get("productId");
|
||||
wishlistService.removeFromWishlist(userId, productId);
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.xiaowang.yuminailcore.filter;
|
||||
|
||||
import com.xiaowang.yuminailcore.support.security.CachedBodyHttpServletRequest;
|
||||
import com.xiaowang.yuminailcore.support.security.RequestSignatureService;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 缓存 JSON 请求体,供签名校验复用。
|
||||
*/
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RequestBodyCacheFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
if (!shouldWrap(request)) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] body = StreamUtils.copyToByteArray(request.getInputStream());
|
||||
CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request, body);
|
||||
wrappedRequest.setAttribute(RequestSignatureService.REQUEST_BODY_ATTRIBUTE, body);
|
||||
filterChain.doFilter(wrappedRequest, response);
|
||||
}
|
||||
|
||||
private boolean shouldWrap(HttpServletRequest request) {
|
||||
String method = request.getMethod();
|
||||
if (!StringUtils.hasText(method)) {
|
||||
return false;
|
||||
}
|
||||
String normalizedMethod = method.toUpperCase();
|
||||
if (!("POST".equals(normalizedMethod) || "PUT".equals(normalizedMethod) || "PATCH".equals(normalizedMethod) || "DELETE".equals(normalizedMethod))) {
|
||||
return false;
|
||||
}
|
||||
String contentType = request.getContentType();
|
||||
if (!StringUtils.hasText(contentType)) {
|
||||
return false;
|
||||
}
|
||||
String normalizedType = contentType.toLowerCase();
|
||||
return normalizedType.contains("application/json");
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,14 @@ public interface ProductService extends IService<ProductDO> {
|
||||
* @return 商品VO列表
|
||||
*/
|
||||
List<ProductVO> listProductsByTag(String tag);
|
||||
|
||||
/**
|
||||
* 前台按标题、描述、标签名搜索商品
|
||||
*
|
||||
* @param keyword 搜索关键词
|
||||
* @return 商品列表
|
||||
*/
|
||||
List<ProductVO> searchProducts(String keyword);
|
||||
|
||||
/**
|
||||
* 分页查询商品
|
||||
@@ -98,4 +106,6 @@ public interface ProductService extends IService<ProductDO> {
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageResultVO<ProductVO> pageProducts(Integer page, Integer size, String keyword, Long shopId);
|
||||
|
||||
PageResultVO<ProductVO> pagePublicProducts(Integer page, Integer size, String keyword, String tag);
|
||||
}
|
||||
|
||||
@@ -51,9 +51,9 @@ public interface UserService extends IService<UserDO> {
|
||||
|
||||
LoginShopSelectionVO getAdminLoginShopSelection(String account);
|
||||
|
||||
LoginResponseVO switchShop(Long userId, Long shopId);
|
||||
LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId);
|
||||
|
||||
LoginResponseVO switchAdminShop(Long userId, Long shopId);
|
||||
LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId);
|
||||
|
||||
void syncManagedPermissions(Long userId);
|
||||
|
||||
@@ -61,7 +61,7 @@ public interface UserService extends IService<UserDO> {
|
||||
|
||||
LoginResponseVO refreshToken(String refreshToken);
|
||||
|
||||
boolean logout();
|
||||
boolean logout(String sessionId);
|
||||
|
||||
UserVO getCurrentUserInfo();
|
||||
|
||||
|
||||
+5
-1
@@ -11,6 +11,7 @@ import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.service.CartService;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.CartArtistVO;
|
||||
import com.xiaowang.yuminailcore.vo.CartVO;
|
||||
@@ -49,6 +50,9 @@ public class CartServiceImpl implements CartService {
|
||||
@Resource
|
||||
private BookableArtistSupport bookableArtistSupport;
|
||||
|
||||
@Resource
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void addToCart(Long userId, CartDTO cartDTO) {
|
||||
@@ -239,7 +243,7 @@ public class CartServiceImpl implements CartService {
|
||||
CartArtistVO cartArtistVO = new CartArtistVO();
|
||||
cartArtistVO.setId(artist.getId());
|
||||
cartArtistVO.setName(artist.getNickname());
|
||||
cartArtistVO.setAvatar(artist.getAvatar());
|
||||
cartArtistVO.setAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar()));
|
||||
return cartArtistVO;
|
||||
}
|
||||
}
|
||||
|
||||
+5
-1
@@ -22,6 +22,7 @@ import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.service.OrderService;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.OrderItemVO;
|
||||
@@ -144,6 +145,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
@Resource
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@Resource
|
||||
private TransactionTemplate transactionTemplate;
|
||||
|
||||
@@ -536,7 +540,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
UserDO artist = getUserFromCache(item.getArtistId(), userCache);
|
||||
if (artist != null) {
|
||||
itemVO.setArtistName(artist.getNickname());
|
||||
itemVO.setArtistAvatar(artist.getAvatar());
|
||||
itemVO.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+245
-33
@@ -4,6 +4,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.xiaowang.yuminailcore.config.AppCacheProperties;
|
||||
import com.xiaowang.yuminailcore.dto.ProductDTO;
|
||||
import com.xiaowang.yuminailcore.entity.CouponDO;
|
||||
import com.xiaowang.yuminailcore.entity.ProductDO;
|
||||
@@ -17,6 +19,7 @@ import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.service.ProductService;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ProductVO;
|
||||
@@ -26,9 +29,11 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -42,6 +47,11 @@ import java.util.stream.Collectors;
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> implements ProductService {
|
||||
private static final String PRODUCT_DETAIL_CACHE_PREFIX = "cache:product:detail:";
|
||||
private static final String PRODUCT_LIST_CACHE_PREFIX = "cache:product:list:";
|
||||
private static final String PRODUCT_SEARCH_CACHE_PREFIX = "cache:product:search:";
|
||||
private static final int DEFAULT_PUBLIC_PAGE_SIZE = 10;
|
||||
private static final int MAX_PUBLIC_PAGE_SIZE = 30;
|
||||
|
||||
private final ProductMapper productMapper;
|
||||
private final TagService tagService;
|
||||
@@ -50,6 +60,8 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
private final ShopMapper shopMapper;
|
||||
private final TagMapper tagMapper;
|
||||
private final BookableArtistSupport bookableArtistSupport;
|
||||
private final MultiLevelCacheService multiLevelCacheService;
|
||||
private final AppCacheProperties appCacheProperties;
|
||||
|
||||
@Override
|
||||
public Long createProduct(ProductDTO productDTO) {
|
||||
@@ -69,6 +81,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
productDO.setAvailableCoupons(productDTO.getAvailableCoupons());
|
||||
productDO.setIsDelete(0);
|
||||
productMapper.insert(productDO);
|
||||
evictPublicProductCaches(productDO.getId());
|
||||
return productDO.getId();
|
||||
}
|
||||
|
||||
@@ -95,7 +108,11 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
productDO.setApproximateDuration(productDTO.getApproximateDuration());
|
||||
productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()));
|
||||
productDO.setAvailableCoupons(productDTO.getAvailableCoupons());
|
||||
return productMapper.updateById(productDO) > 0;
|
||||
boolean updated = productMapper.updateById(productDO) > 0;
|
||||
if (updated) {
|
||||
evictPublicProductCaches(id);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -105,37 +122,67 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
return false;
|
||||
}
|
||||
productDO.setIsDelete(1);
|
||||
return productMapper.updateById(productDO) > 0;
|
||||
boolean deleted = productMapper.updateById(productDO) > 0;
|
||||
if (deleted) {
|
||||
evictPublicProductCaches(id);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int incrementLikeCount(Long productId) {
|
||||
return productMapper.incrementLikeCount(productId);
|
||||
int updated = productMapper.incrementLikeCount(productId);
|
||||
if (updated > 0) {
|
||||
evictPublicProductCaches(productId);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int decrementLikeCount(Long productId) {
|
||||
return productMapper.decrementLikeCount(productId);
|
||||
int updated = productMapper.decrementLikeCount(productId);
|
||||
if (updated > 0) {
|
||||
evictPublicProductCaches(productId);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProductVO getProductById(Long id) {
|
||||
ProductDO productDO = productMapper.selectById(id);
|
||||
if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(productDO);
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail();
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
PRODUCT_DETAIL_CACHE_PREFIX + id,
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<ProductVO>() {
|
||||
},
|
||||
() -> {
|
||||
ProductDO productDO = productMapper.selectById(id);
|
||||
if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(productDO);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ProductVO> listAllProducts() {
|
||||
List<ProductDO> productDOs = productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList();
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
PRODUCT_LIST_CACHE_PREFIX + "all",
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<List<ProductVO>>() {
|
||||
},
|
||||
() -> productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.orderByDesc(ProductDO::getCreateTime)
|
||||
).stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
return productDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -152,27 +199,33 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
|
||||
@Override
|
||||
public List<ProductVO> listProductsByTag(String tag) {
|
||||
List<TagDO> matchedTags = tagMapper.selectList(
|
||||
Wrappers.lambdaQuery(TagDO.class)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
.eq(TagDO::getTagName, tag)
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList();
|
||||
String normalizedTag = normalizeOptionalKeyword(tag);
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
PRODUCT_LIST_CACHE_PREFIX + "tag:" + normalizedTag,
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<List<ProductVO>>() {
|
||||
},
|
||||
() -> loadProductsByTag(normalizedTag)
|
||||
);
|
||||
if (matchedTags.isEmpty()) {
|
||||
return new java.util.ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> matchedTagIds = matchedTags.stream()
|
||||
.map(TagDO::getId)
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
List<ProductDO> productDOs = productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
@Override
|
||||
public List<ProductVO> searchProducts(String keyword) {
|
||||
if (!StringUtils.hasText(keyword)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductSearch();
|
||||
String trimmedKeyword = keyword.trim();
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
PRODUCT_SEARCH_CACHE_PREFIX + trimmedKeyword.toLowerCase(Locale.ROOT),
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<List<ProductVO>>() {
|
||||
},
|
||||
() -> searchFrontProducts(trimmedKeyword)
|
||||
);
|
||||
return productDOs.stream()
|
||||
.filter(productDO -> containsAnyTagId(productDO.getTags(), matchedTagIds))
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -277,6 +330,29 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResultVO<ProductVO> pagePublicProducts(Integer page, Integer size, String keyword, String tag) {
|
||||
int normalizedPage = normalizePage(page);
|
||||
int normalizedSize = normalizePageSize(size);
|
||||
String normalizedKeyword = normalizeOptionalKeyword(keyword);
|
||||
String normalizedTag = normalizeOptionalKeyword(tag);
|
||||
AppCacheProperties.CacheSpec cacheSpec = StringUtils.hasText(normalizedKeyword)
|
||||
? appCacheProperties.getProductSearch()
|
||||
: appCacheProperties.getProductList();
|
||||
String cacheKey = PRODUCT_LIST_CACHE_PREFIX + "page:" + normalizedPage
|
||||
+ ":" + normalizedSize
|
||||
+ ":" + normalizedKeyword.toLowerCase(Locale.ROOT)
|
||||
+ ":" + normalizedTag.toLowerCase(Locale.ROOT);
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
cacheKey,
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<PageResultVO<ProductVO>>() {
|
||||
},
|
||||
() -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag)
|
||||
);
|
||||
}
|
||||
|
||||
private void validateBookableArtists(Long shopId, String bookableArtists) {
|
||||
if (!StringUtils.hasText(bookableArtists)) {
|
||||
return;
|
||||
@@ -363,6 +439,25 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
return count;
|
||||
}
|
||||
|
||||
private boolean matchesFrontSearch(ProductDO productDO, String normalizedKeyword, Set<String> matchedTagIds) {
|
||||
if (containsKeyword(productDO.getTitle(), normalizedKeyword)
|
||||
|| containsKeyword(productDO.getDescription(), normalizedKeyword)) {
|
||||
return true;
|
||||
}
|
||||
return containsAnyTagId(productDO.getTags(), matchedTagIds);
|
||||
}
|
||||
|
||||
private String normalizeSearchKeyword(String keyword) {
|
||||
return keyword.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private boolean containsKeyword(String source, String normalizedKeyword) {
|
||||
if (!StringUtils.hasText(source) || !StringUtils.hasText(normalizedKeyword)) {
|
||||
return false;
|
||||
}
|
||||
return source.toLowerCase(Locale.ROOT).contains(normalizedKeyword);
|
||||
}
|
||||
|
||||
private boolean containsAnyTagId(String tags, Set<String> targetTagIds) {
|
||||
if (!StringUtils.hasText(tags) || targetTagIds == null || targetTagIds.isEmpty()) {
|
||||
return false;
|
||||
@@ -374,4 +469,121 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private List<ProductVO> loadProductsByTag(String tag) {
|
||||
if (!StringUtils.hasText(tag)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
Set<String> matchedTagIds = findExactTagIds(tag);
|
||||
if (matchedTagIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return listFrontProductDOs().stream()
|
||||
.filter(productDO -> containsAnyTagId(productDO.getTags(), matchedTagIds))
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<ProductVO> searchFrontProducts(String keyword) {
|
||||
String normalizedKeyword = normalizeSearchKeyword(keyword);
|
||||
Set<String> matchedTagIds = findLikeTagIds(keyword);
|
||||
return listFrontProductDOs().stream()
|
||||
.filter(productDO -> matchesFrontSearch(productDO, normalizedKeyword, matchedTagIds))
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private PageResultVO<ProductVO> buildPublicProductPage(int page, int size, String keyword, String tag) {
|
||||
if (!StringUtils.hasText(keyword) && !StringUtils.hasText(tag)) {
|
||||
Page<ProductDO> pageParam = new Page<>(page, size);
|
||||
Page<ProductDO> productPage = productMapper.selectPage(pageParam,
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.orderByDesc(ProductDO::getCreateTime));
|
||||
PageResultVO<ProductVO> result = new PageResultVO<>();
|
||||
result.setList(productPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList()));
|
||||
result.setTotal(productPage.getTotal());
|
||||
result.setPage(page);
|
||||
result.setSize(size);
|
||||
return result;
|
||||
}
|
||||
|
||||
List<ProductVO> source = StringUtils.hasText(keyword)
|
||||
? searchFrontProducts(keyword)
|
||||
: loadProductsByTag(tag);
|
||||
if (StringUtils.hasText(keyword) && StringUtils.hasText(tag)) {
|
||||
Set<String> exactTagIds = findExactTagIds(tag);
|
||||
source = source.stream()
|
||||
.filter(productVO -> containsAnyTagId(productVO.getTags(), exactTagIds))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
int fromIndex = Math.max((page - 1) * size, 0);
|
||||
int toIndex = Math.min(fromIndex + size, source.size());
|
||||
PageResultVO<ProductVO> result = new PageResultVO<>();
|
||||
result.setList(fromIndex >= source.size() ? List.of() : new ArrayList<>(source.subList(fromIndex, toIndex)));
|
||||
result.setTotal((long) source.size());
|
||||
result.setPage(page);
|
||||
result.setSize(size);
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<ProductDO> listFrontProductDOs() {
|
||||
return productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.orderByDesc(ProductDO::getCreateTime)
|
||||
);
|
||||
}
|
||||
|
||||
private Set<String> findExactTagIds(String tag) {
|
||||
if (!StringUtils.hasText(tag)) {
|
||||
return Set.of();
|
||||
}
|
||||
return tagMapper.selectList(
|
||||
Wrappers.lambdaQuery(TagDO.class)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
.eq(TagDO::getTagName, tag)
|
||||
).stream()
|
||||
.map(TagDO::getId)
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
}
|
||||
|
||||
private Set<String> findLikeTagIds(String keyword) {
|
||||
if (!StringUtils.hasText(keyword)) {
|
||||
return Set.of();
|
||||
}
|
||||
return tagMapper.selectList(
|
||||
Wrappers.lambdaQuery(TagDO.class)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
.like(TagDO::getTagName, keyword)
|
||||
).stream()
|
||||
.map(TagDO::getId)
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
}
|
||||
|
||||
private int normalizePage(Integer page) {
|
||||
return page == null || page < 1 ? 1 : page;
|
||||
}
|
||||
|
||||
private int normalizePageSize(Integer size) {
|
||||
if (size == null || size < 1) {
|
||||
return DEFAULT_PUBLIC_PAGE_SIZE;
|
||||
}
|
||||
return Math.min(size, MAX_PUBLIC_PAGE_SIZE);
|
||||
}
|
||||
|
||||
private String normalizeOptionalKeyword(String value) {
|
||||
return StringUtils.hasText(value) ? value.trim() : "";
|
||||
}
|
||||
|
||||
private void evictPublicProductCaches(Long productId) {
|
||||
if (productId != null) {
|
||||
multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + productId);
|
||||
}
|
||||
multiLevelCacheService.evictByPrefix(PRODUCT_LIST_CACHE_PREFIX);
|
||||
multiLevelCacheService.evictByPrefix(PRODUCT_SEARCH_CACHE_PREFIX);
|
||||
}
|
||||
}
|
||||
|
||||
+61
-15
@@ -4,6 +4,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.xiaowang.yuminailcore.config.AppCacheProperties;
|
||||
import com.xiaowang.yuminailcore.dto.ShopDTO;
|
||||
import com.xiaowang.yuminailcore.entity.CouponDO;
|
||||
import com.xiaowang.yuminailcore.entity.CommentDO;
|
||||
@@ -20,6 +22,7 @@ import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.service.ShopService;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ShopVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -27,6 +30,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -40,6 +44,8 @@ import java.util.stream.Collectors;
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements ShopService {
|
||||
private static final String SHOP_DETAIL_CACHE_PREFIX = "cache:shop:detail:";
|
||||
private static final String SHOP_LIST_CACHE_PREFIX = "cache:shop:list:";
|
||||
|
||||
private final ShopMapper shopMapper;
|
||||
private final CouponService couponService;
|
||||
@@ -49,6 +55,8 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
private final CommentMapper commentMapper;
|
||||
private final UserCouponMapper userCouponMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
private final MultiLevelCacheService multiLevelCacheService;
|
||||
private final AppCacheProperties appCacheProperties;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -64,6 +72,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
shopDO.setIsDelete(0);
|
||||
shopMapper.insert(shopDO);
|
||||
couponService.initializeDefaultVipAutoCoupons(shopDO.getId());
|
||||
evictShopCaches(shopDO.getId());
|
||||
return shopDO.getId();
|
||||
}
|
||||
|
||||
@@ -82,7 +91,11 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
if (shopDTO.getStatus() != null) {
|
||||
shopDO.setStatus(normalizeStatus(shopDTO.getStatus()));
|
||||
}
|
||||
return shopMapper.updateById(shopDO) > 0;
|
||||
boolean updated = shopMapper.updateById(shopDO) > 0;
|
||||
if (updated) {
|
||||
evictShopCaches(id);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -124,7 +137,11 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
userShopBindingSupport.deleteBindingsByShopId(id);
|
||||
shopDO.setStatus(0);
|
||||
shopDO.setIsDelete(1);
|
||||
return shopMapper.updateById(shopDO) > 0;
|
||||
boolean deleted = shopMapper.updateById(shopDO) > 0;
|
||||
if (deleted) {
|
||||
evictShopCaches(id);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -134,28 +151,50 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
return false;
|
||||
}
|
||||
shopDO.setStatus(normalizeStatus(status));
|
||||
return shopMapper.updateById(shopDO) > 0;
|
||||
boolean updated = shopMapper.updateById(shopDO) > 0;
|
||||
if (updated) {
|
||||
evictShopCaches(id);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ShopVO getShopById(Long id) {
|
||||
ShopDO shopDO = shopMapper.selectById(id);
|
||||
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(shopDO);
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop();
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
SHOP_DETAIL_CACHE_PREFIX + id,
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<ShopVO>() {
|
||||
},
|
||||
() -> {
|
||||
ShopDO shopDO = shopMapper.selectById(id);
|
||||
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(shopDO);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ShopVO> listAllShops() {
|
||||
List<ShopDO> shopDOs = shopMapper.selectList(
|
||||
Wrappers.lambdaQuery(ShopDO.class)
|
||||
.eq(ShopDO::getIsDelete, 0)
|
||||
.eq(ShopDO::getStatus, 1)
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop();
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
SHOP_LIST_CACHE_PREFIX + "active",
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<List<ShopVO>>() {
|
||||
},
|
||||
() -> shopMapper.selectList(
|
||||
Wrappers.lambdaQuery(ShopDO.class)
|
||||
.eq(ShopDO::getIsDelete, 0)
|
||||
.eq(ShopDO::getStatus, 1)
|
||||
.orderByDesc(ShopDO::getCreateTime)
|
||||
).stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
return shopDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -236,4 +275,11 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
private Integer normalizeStatus(Integer status) {
|
||||
return Integer.valueOf(0).equals(status) ? 0 : 1;
|
||||
}
|
||||
|
||||
private void evictShopCaches(Long shopId) {
|
||||
if (shopId != null) {
|
||||
multiLevelCacheService.evict(SHOP_DETAIL_CACHE_PREFIX + shopId);
|
||||
}
|
||||
multiLevelCacheService.evictByPrefix(SHOP_LIST_CACHE_PREFIX);
|
||||
}
|
||||
}
|
||||
|
||||
+73
-20
@@ -2,18 +2,22 @@ package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.xiaowang.yuminailcore.config.AppCacheProperties;
|
||||
import com.xiaowang.yuminailcore.dto.TagDTO;
|
||||
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||
import com.xiaowang.yuminailcore.entity.TagDO;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.TagMapper;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.yuminailcore.vo.TagVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -27,9 +31,13 @@ import java.util.stream.Collectors;
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements TagService {
|
||||
private static final String TAG_DETAIL_CACHE_PREFIX = "cache:tag:detail:";
|
||||
private static final String TAG_LIST_CACHE_PREFIX = "cache:tag:list:";
|
||||
|
||||
private final TagMapper tagMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final MultiLevelCacheService multiLevelCacheService;
|
||||
private final AppCacheProperties appCacheProperties;
|
||||
|
||||
@Override
|
||||
public Long createTag(TagDTO tagDTO) {
|
||||
@@ -49,6 +57,7 @@ public class TagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements Tag
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw buildDuplicateTagException(tagName, shopId, null);
|
||||
}
|
||||
evictTagCaches(tagDO.getId(), shopId);
|
||||
return tagDO.getId();
|
||||
}
|
||||
|
||||
@@ -68,7 +77,11 @@ public class TagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements Tag
|
||||
tagDO.setBorderColor(tagDTO.getBorderColor());
|
||||
tagDO.setShopId(shopId);
|
||||
try {
|
||||
return tagMapper.updateById(tagDO) > 0;
|
||||
boolean updated = tagMapper.updateById(tagDO) > 0;
|
||||
if (updated) {
|
||||
evictTagCaches(id, shopId);
|
||||
}
|
||||
return updated;
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw buildDuplicateTagException(tagName, shopId, id);
|
||||
}
|
||||
@@ -81,39 +94,69 @@ public class TagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements Tag
|
||||
return false;
|
||||
}
|
||||
tagDO.setIsDelete(1);
|
||||
return tagMapper.updateById(tagDO) > 0;
|
||||
boolean deleted = tagMapper.updateById(tagDO) > 0;
|
||||
if (deleted) {
|
||||
evictTagCaches(id, tagDO.getShopId());
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TagVO getTagById(Long id) {
|
||||
TagDO tagDO = tagMapper.selectById(id);
|
||||
if (tagDO == null) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(tagDO);
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag();
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
TAG_DETAIL_CACHE_PREFIX + id,
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<TagVO>() {
|
||||
},
|
||||
() -> {
|
||||
TagDO tagDO = tagMapper.selectById(id);
|
||||
if (tagDO == null || Integer.valueOf(1).equals(tagDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(tagDO);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TagVO> listAllTags() {
|
||||
List<TagDO> tagDOs = tagMapper.selectList(
|
||||
Wrappers.lambdaQuery(TagDO.class)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag();
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
TAG_LIST_CACHE_PREFIX + "all",
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<List<TagVO>>() {
|
||||
},
|
||||
() -> tagMapper.selectList(
|
||||
Wrappers.lambdaQuery(TagDO.class)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
.orderByDesc(TagDO::getCreateTime)
|
||||
).stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
return tagDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TagVO> listTagsByShopId(Long shopId) {
|
||||
List<TagDO> tagDOs = tagMapper.selectList(
|
||||
Wrappers.lambdaQuery(TagDO.class)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
.eq(TagDO::getShopId, shopId)
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag();
|
||||
return multiLevelCacheService.getOrLoad(
|
||||
TAG_LIST_CACHE_PREFIX + "shop:" + shopId,
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<List<TagVO>>() {
|
||||
},
|
||||
() -> tagMapper.selectList(
|
||||
Wrappers.lambdaQuery(TagDO.class)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
.eq(TagDO::getShopId, shopId)
|
||||
.orderByDesc(TagDO::getCreateTime)
|
||||
).stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
return tagDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -194,4 +237,14 @@ public class TagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements Tag
|
||||
ShopDO shopDO = shopMapper.selectById(shopId);
|
||||
return shopDO == null ? null : shopDO.getShopName();
|
||||
}
|
||||
|
||||
private void evictTagCaches(Long tagId, Long shopId) {
|
||||
if (tagId != null) {
|
||||
multiLevelCacheService.evict(TAG_DETAIL_CACHE_PREFIX + tagId);
|
||||
}
|
||||
if (shopId != null) {
|
||||
multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "shop:" + shopId);
|
||||
}
|
||||
multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "all");
|
||||
}
|
||||
}
|
||||
|
||||
+79
-19
@@ -19,6 +19,8 @@ import com.xiaowang.yuminailcore.service.NailArtistInfoService;
|
||||
import com.xiaowang.yuminailcore.service.ShopService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.service.VerificationCodeService;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.support.security.UserSessionService;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.support.PermissionPolicy;
|
||||
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||
@@ -62,6 +64,7 @@ import java.util.stream.Collectors;
|
||||
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
|
||||
private static final String VIP_LEVEL_NORMAL = "普通";
|
||||
private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
|
||||
private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
|
||||
private static final String DELETED_PHONE_MARKER = "_deleted_";
|
||||
private static final String LOGIN_FAIL_KEY_PREFIX = "user:login:failed:";
|
||||
private static final int MAX_LOGIN_FAILURES = 5;
|
||||
@@ -79,9 +82,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
private final VerificationCodeService verificationCodeService;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final WechatMiniBindingMapper wechatMiniBindingMapper;
|
||||
private final UserSessionService userSessionService;
|
||||
|
||||
private static Map<String, PermissionSeed> buildDefaultPermissionSeeds() {
|
||||
Map<String, PermissionSeed> seeds = new HashMap<>();
|
||||
@@ -266,8 +271,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
userDO.setIsDelete(0);
|
||||
userDO.setStatus(1);
|
||||
// 设置默认头像
|
||||
String defaultAvatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
|
||||
userDO.setAvatar(defaultAvatar);
|
||||
userDO.setAvatar(DEFAULT_AVATAR_URL);
|
||||
|
||||
if (Integer.valueOf(0).equals(userDO.getType())) {
|
||||
if (!StringUtils.hasText(userDO.getLevel())) {
|
||||
@@ -382,7 +386,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
if (userDTO.getAvatar().isEmpty()) {
|
||||
userDO.setAvatar(null);
|
||||
} else {
|
||||
userDO.setAvatar(userDTO.getAvatar());
|
||||
userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar()));
|
||||
}
|
||||
}
|
||||
if (userDTO.getSignature() != null) {
|
||||
@@ -411,6 +415,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
if (shopBindingChanged) {
|
||||
userShopBindingSupport.syncUserShopBindings(id, validatedShopIds);
|
||||
}
|
||||
if (userDTO.getPassword() != null) {
|
||||
userSessionService.revokeAllUserSessions(id);
|
||||
}
|
||||
syncDefaultPermissions(id, targetUserType);
|
||||
}
|
||||
return updated;
|
||||
@@ -429,6 +436,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
|
||||
clearLoginFailureCount(userDO.getAccount());
|
||||
userSessionService.revokeAllUserSessions(id);
|
||||
userShopBindingSupport.deleteBindingsByUserId(id);
|
||||
wechatMiniBindingMapper.update(
|
||||
null,
|
||||
@@ -566,8 +574,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
userVO.setNickname(userDO.getNickname());
|
||||
userVO.setAccount(userDO.getAccount());
|
||||
userVO.setPhone(userDO.getPhone());
|
||||
String defaultAvatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
|
||||
userVO.setAvatar(userDO.getAvatar() != null && !userDO.getAvatar().isEmpty() ? userDO.getAvatar() : defaultAvatar);
|
||||
userVO.setAvatar(resolveAccessibleAvatar(userDO.getAvatar()));
|
||||
userVO.setSignature(userDO.getSignature());
|
||||
userVO.setLevel(userDO.getLevel());
|
||||
userVO.setType(userDO.getType());
|
||||
@@ -578,6 +585,20 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
return userVO;
|
||||
}
|
||||
|
||||
private String resolveAccessibleAvatar(String avatarUrl) {
|
||||
if (!StringUtils.hasText(avatarUrl)) {
|
||||
return DEFAULT_AVATAR_URL;
|
||||
}
|
||||
return objectStorageUrlSupport.toAccessibleUrl(avatarUrl);
|
||||
}
|
||||
|
||||
private String normalizeStoredAvatar(String avatarUrl) {
|
||||
if (!StringUtils.hasText(avatarUrl)) {
|
||||
return avatarUrl;
|
||||
}
|
||||
return objectStorageUrlSupport.toStoredUrl(avatarUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginShopSelectionVO getLoginShopSelectionByAccount(String account) {
|
||||
String normalizedAccount = account == null ? "" : account.trim();
|
||||
@@ -835,18 +856,18 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginResponseVO switchShop(Long userId, Long shopId) {
|
||||
public LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
if (userDO.getType() != null && userDO.getType() >= 2) {
|
||||
throw new RuntimeException("当前账号请使用后台切换店铺");
|
||||
}
|
||||
Long resolvedShopId = resolveUserLoginShopId(userDO, shopId);
|
||||
return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
|
||||
return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), previousSessionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginResponseVO switchAdminShop(Long userId, Long shopId) {
|
||||
public LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
Integer userType = userDO.getType();
|
||||
@@ -854,7 +875,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
throw new RuntimeException("您没有后台管理权限");
|
||||
}
|
||||
Long resolvedShopId = resolveAdminLoginShopId(userDO, shopId);
|
||||
return buildLoginResponse(userDO, resolvedShopId, false);
|
||||
return buildLoginResponse(userDO, resolvedShopId, false, previousSessionId);
|
||||
}
|
||||
|
||||
private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) {
|
||||
@@ -966,6 +987,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
Long userId = jwtUtil.getUserIdFromToken(refreshToken);
|
||||
String account = jwtUtil.getAccountFromToken(refreshToken);
|
||||
Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken));
|
||||
String sessionId = jwtUtil.getSessionIdFromToken(refreshToken);
|
||||
String refreshJti = jwtUtil.getJtiFromToken(refreshToken);
|
||||
if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) {
|
||||
throw new RuntimeException("登录态已失效,请重新登录");
|
||||
}
|
||||
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
@@ -974,11 +1000,12 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
throw new RuntimeException("当前登录店铺已失效,请重新登录");
|
||||
}
|
||||
|
||||
return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
|
||||
return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), sessionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean logout() {
|
||||
public boolean logout(String sessionId) {
|
||||
userSessionService.revokeSession(sessionId);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -999,7 +1026,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
if (userDTO.getAvatar().isEmpty()) {
|
||||
userDO.setAvatar(null);
|
||||
} else {
|
||||
userDO.setAvatar(userDTO.getAvatar());
|
||||
userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar()));
|
||||
}
|
||||
}
|
||||
if (userDTO.getSignature() != null) {
|
||||
@@ -1067,8 +1094,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
targetUser.setPassword(passwordEncoder.encode("888888"));
|
||||
targetUser.setUpdateTime(LocalDateTime.now());
|
||||
|
||||
return userMapper.updateById(targetUser) > 0;
|
||||
boolean updated = userMapper.updateById(targetUser) > 0;
|
||||
if (updated) {
|
||||
userSessionService.revokeAllUserSessions(targetUserId);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1131,6 +1161,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
if (latestUser != null) {
|
||||
clearLoginFailureCount(latestUser.getAccount());
|
||||
}
|
||||
} else if (updated) {
|
||||
userSessionService.revokeAllUserSessions(id);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
@@ -1197,7 +1229,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
validateVerificationCode(userDO.getPhone(), verificationCode);
|
||||
userDO.setPassword(passwordEncoder.encode(password));
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
boolean updated = userMapper.updateById(userDO) > 0;
|
||||
if (updated) {
|
||||
userSessionService.revokeAllUserSessions(userId);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1248,7 +1284,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
// 更新密码
|
||||
userDO.setPassword(passwordEncoder.encode(newPassword));
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
boolean updated = userMapper.updateById(userDO) > 0;
|
||||
if (updated) {
|
||||
userSessionService.revokeAllUserSessions(userDO.getId());
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
private String buildDeletedAccount(UserDO userDO) {
|
||||
@@ -1317,6 +1357,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.set(UserDO::getStatus, 0)
|
||||
.set(UserDO::getUpdateTime, LocalDateTime.now())
|
||||
);
|
||||
userSessionService.revokeAllUserSessions(userId);
|
||||
}
|
||||
|
||||
private void clearLoginFailureCount(String account) {
|
||||
@@ -1432,8 +1473,27 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
|
||||
private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword) {
|
||||
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount(), currentShopId);
|
||||
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount(), currentShopId);
|
||||
return buildLoginResponse(userDO, currentShopId, needSetPassword, null);
|
||||
}
|
||||
|
||||
private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, String previousSessionId) {
|
||||
UserSessionService.SessionIssueResult sessionIssueResult = StringUtils.hasText(previousSessionId)
|
||||
? userSessionService.rotateSession(previousSessionId, userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType())
|
||||
: userSessionService.issueSession(userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType());
|
||||
String accessToken = jwtUtil.generateAccessToken(
|
||||
userDO.getId(),
|
||||
userDO.getAccount(),
|
||||
currentShopId,
|
||||
sessionIssueResult.sessionId(),
|
||||
sessionIssueResult.accessJti()
|
||||
);
|
||||
String refreshToken = jwtUtil.generateRefreshToken(
|
||||
userDO.getId(),
|
||||
userDO.getAccount(),
|
||||
currentShopId,
|
||||
sessionIssueResult.sessionId(),
|
||||
sessionIssueResult.refreshJti()
|
||||
);
|
||||
|
||||
LoginResponseVO responseVO = new LoginResponseVO();
|
||||
responseVO.setAccessToken(accessToken);
|
||||
@@ -1462,7 +1522,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
userInfo.setId(userDO.getId());
|
||||
userInfo.setAccount(userDO.getAccount());
|
||||
userInfo.setNickname(userDO.getNickname());
|
||||
userInfo.setAvatar(userDO.getAvatar());
|
||||
userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar()));
|
||||
userInfo.setType(userDO.getType());
|
||||
userInfo.setShopId(normalizedCurrentShopId);
|
||||
userInfo.setShopName(currentShopName);
|
||||
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
import com.xiaowang.yuminailcore.config.MinioConfig;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* 统一处理对象存储文件地址的提取、签名与归一化,避免把私有桶原始地址直接暴露给前端。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ObjectStorageUrlSupport {
|
||||
|
||||
private static final int DEFAULT_SIGNED_URL_EXPIRE_MINUTES = 60;
|
||||
|
||||
private final MinioService minioService;
|
||||
private final MinioConfig minioConfig;
|
||||
|
||||
public String toAccessibleUrl(String fileUrl) {
|
||||
if (!StringUtils.hasText(fileUrl)) {
|
||||
return fileUrl;
|
||||
}
|
||||
String objectName = extractObjectName(fileUrl);
|
||||
if (!StringUtils.hasText(objectName)) {
|
||||
return fileUrl;
|
||||
}
|
||||
try {
|
||||
return minioService.getPresignedUrl(objectName, DEFAULT_SIGNED_URL_EXPIRE_MINUTES);
|
||||
} catch (Exception e) {
|
||||
log.warn("生成对象存储签名地址失败,回退原地址: {}", fileUrl, e);
|
||||
return fileUrl;
|
||||
}
|
||||
}
|
||||
|
||||
public String toStoredUrl(String fileUrl) {
|
||||
if (!StringUtils.hasText(fileUrl)) {
|
||||
return fileUrl;
|
||||
}
|
||||
String objectName = extractObjectName(fileUrl);
|
||||
if (!StringUtils.hasText(objectName)) {
|
||||
return fileUrl;
|
||||
}
|
||||
return minioService.getFileUrl(objectName);
|
||||
}
|
||||
|
||||
public String extractObjectName(String fileUrl) {
|
||||
if (!StringUtils.hasText(fileUrl)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
String normalizedUrl = fileUrl.trim();
|
||||
if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) {
|
||||
return trimBucketPrefix(stripQuery(normalizedUrl));
|
||||
}
|
||||
|
||||
try {
|
||||
URI fileUri = URI.create(normalizedUrl);
|
||||
String path = fileUri.getPath();
|
||||
if (!StringUtils.hasText(path)) {
|
||||
return "";
|
||||
}
|
||||
return extractObjectNameFromPath(path);
|
||||
} catch (Exception e) {
|
||||
log.warn("解析对象存储文件地址失败: {}", fileUrl, e);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private String extractObjectNameFromPath(String path) {
|
||||
String bucketPrefix = "/" + minioConfig.getBucketName() + "/";
|
||||
if (path.startsWith(bucketPrefix)) {
|
||||
return path.substring(bucketPrefix.length());
|
||||
}
|
||||
|
||||
String endpointPath = "";
|
||||
try {
|
||||
endpointPath = URI.create(minioConfig.getEndpoint()).getPath();
|
||||
} catch (Exception e) {
|
||||
log.warn("解析 MinIO endpoint 失败: {}", minioConfig.getEndpoint(), e);
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(endpointPath) && !"/".equals(endpointPath)) {
|
||||
String normalizedEndpointPath = endpointPath.endsWith("/")
|
||||
? endpointPath.substring(0, endpointPath.length() - 1)
|
||||
: endpointPath;
|
||||
String prefixedBucketPath = normalizedEndpointPath + bucketPrefix;
|
||||
if (path.startsWith(prefixedBucketPath)) {
|
||||
return path.substring(prefixedBucketPath.length());
|
||||
}
|
||||
}
|
||||
|
||||
int bucketIndex = path.indexOf(bucketPrefix);
|
||||
if (bucketIndex >= 0) {
|
||||
return path.substring(bucketIndex + bucketPrefix.length());
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
private String trimBucketPrefix(String rawValue) {
|
||||
String normalized = stripLeadingSlash(rawValue);
|
||||
String bucketPrefix = minioConfig.getBucketName() + "/";
|
||||
if (normalized.startsWith(bucketPrefix)) {
|
||||
return normalized.substring(bucketPrefix.length());
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private String stripLeadingSlash(String rawValue) {
|
||||
String normalized = rawValue;
|
||||
while (normalized.startsWith("/")) {
|
||||
normalized = normalized.substring(1);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private String stripQuery(String rawValue) {
|
||||
int queryIndex = rawValue.indexOf('?');
|
||||
return queryIndex >= 0 ? rawValue.substring(0, queryIndex) : rawValue;
|
||||
}
|
||||
}
|
||||
Vendored
+165
@@ -0,0 +1,165 @@
|
||||
package com.xiaowang.yuminailcore.support.cache;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.xiaowang.yuminailcore.config.AppCacheProperties;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* 本地 + Redis 多级缓存。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class MultiLevelCacheService {
|
||||
|
||||
private static final String NULL_SENTINEL = "__CACHE_NULL__";
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AppCacheProperties cacheProperties;
|
||||
|
||||
private Cache<String, LocalCacheEntry> localCache;
|
||||
|
||||
private Cache<String, LocalCacheEntry> getLocalCache() {
|
||||
if (localCache == null) {
|
||||
localCache = Caffeine.newBuilder()
|
||||
.maximumSize(Math.max(128, cacheProperties.getLocalMaxSize()))
|
||||
.build();
|
||||
}
|
||||
return localCache;
|
||||
}
|
||||
|
||||
public <T> T getOrLoad(String key,
|
||||
Duration localTtl,
|
||||
Duration redisTtl,
|
||||
TypeReference<T> typeReference,
|
||||
Supplier<T> loader) {
|
||||
CacheLookup<T> lookup = get(key, localTtl, typeReference);
|
||||
if (lookup.isHit()) {
|
||||
return lookup.getValue();
|
||||
}
|
||||
|
||||
T loaded = loader.get();
|
||||
put(key, loaded, localTtl, redisTtl);
|
||||
return loaded;
|
||||
}
|
||||
|
||||
public <T> CacheLookup<T> get(String key, Duration localTtl, TypeReference<T> typeReference) {
|
||||
if (!StringUtils.hasText(key)) {
|
||||
return CacheLookup.miss();
|
||||
}
|
||||
|
||||
LocalCacheEntry localEntry = getLocalCache().getIfPresent(key);
|
||||
if (localEntry != null) {
|
||||
if (!localEntry.isExpired()) {
|
||||
return CacheLookup.hit(readValue(localEntry.getJson(), typeReference));
|
||||
}
|
||||
getLocalCache().invalidate(key);
|
||||
}
|
||||
|
||||
String json = stringRedisTemplate.opsForValue().get(key);
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return CacheLookup.miss();
|
||||
}
|
||||
|
||||
putLocal(key, json, localTtl);
|
||||
return CacheLookup.hit(readValue(json, typeReference));
|
||||
}
|
||||
|
||||
public void put(String key, Object value, Duration localTtl, Duration redisTtl) {
|
||||
if (!StringUtils.hasText(key)) {
|
||||
return;
|
||||
}
|
||||
String json = writeValue(value);
|
||||
putLocal(key, json, localTtl);
|
||||
stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public void evict(String... keys) {
|
||||
if (keys == null || keys.length == 0) {
|
||||
return;
|
||||
}
|
||||
for (String key : keys) {
|
||||
getLocalCache().invalidate(key);
|
||||
}
|
||||
stringRedisTemplate.delete(Set.of(keys));
|
||||
}
|
||||
|
||||
public void evictByPrefix(String prefix) {
|
||||
if (!StringUtils.hasText(prefix)) {
|
||||
return;
|
||||
}
|
||||
getLocalCache().asMap().keySet().removeIf(key -> key.startsWith(prefix));
|
||||
Set<String> redisKeys = stringRedisTemplate.keys(prefix + "*");
|
||||
if (!CollectionUtils.isEmpty(redisKeys)) {
|
||||
stringRedisTemplate.delete(redisKeys);
|
||||
}
|
||||
}
|
||||
|
||||
private void putLocal(String key, String json, Duration localTtl) {
|
||||
getLocalCache().put(key, new LocalCacheEntry(json, System.currentTimeMillis() + Math.max(1L, localTtl.toMillis())));
|
||||
}
|
||||
|
||||
private String writeValue(Object value) {
|
||||
try {
|
||||
return value == null ? NULL_SENTINEL : objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new RuntimeException("缓存序列化失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T readValue(String json, TypeReference<T> typeReference) {
|
||||
if (NULL_SENTINEL.equals(json)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, typeReference);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new RuntimeException("缓存反序列化失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
public static final class CacheLookup<T> {
|
||||
private final boolean hit;
|
||||
private final T value;
|
||||
|
||||
private CacheLookup(boolean hit, T value) {
|
||||
this.hit = hit;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public static <T> CacheLookup<T> hit(T value) {
|
||||
return new CacheLookup<>(true, value);
|
||||
}
|
||||
|
||||
public static <T> CacheLookup<T> miss() {
|
||||
return new CacheLookup<>(false, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
private static final class LocalCacheEntry {
|
||||
private final String json;
|
||||
private final long expireAt;
|
||||
|
||||
private boolean isExpired() {
|
||||
return System.currentTimeMillis() >= expireAt;
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.xiaowang.yuminailcore.support.security;
|
||||
|
||||
import javax.servlet.ReadListener;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 可重复读取 body 的请求包装。
|
||||
*/
|
||||
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
|
||||
|
||||
private final byte[] cachedBody;
|
||||
|
||||
public CachedBodyHttpServletRequest(HttpServletRequest request, byte[] cachedBody) {
|
||||
super(request);
|
||||
this.cachedBody = cachedBody == null ? new byte[0] : cachedBody;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServletInputStream getInputStream() {
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(cachedBody);
|
||||
return new ServletInputStream() {
|
||||
@Override
|
||||
public boolean isFinished() {
|
||||
return inputStream.available() == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReadListener(ReadListener readListener) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() {
|
||||
return inputStream.read();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedReader getReader() throws IOException {
|
||||
Charset charset = getCharacterEncoding() == null
|
||||
? StandardCharsets.UTF_8
|
||||
: Charset.forName(getCharacterEncoding());
|
||||
return new BufferedReader(new InputStreamReader(getInputStream(), charset));
|
||||
}
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
package com.xiaowang.yuminailcore.support.security;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.DigestUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.xiaowang.yuminailcore.support.security.RequestSignatureService.REQUEST_BODY_ATTRIBUTE;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OperationGuardService {
|
||||
|
||||
private static final DefaultRedisScript<Long> RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>();
|
||||
|
||||
static {
|
||||
RELEASE_LOCK_SCRIPT.setScriptText(
|
||||
"if redis.call('get', KEYS[1]) == ARGV[1] then "
|
||||
+ "return redis.call('del', KEYS[1]) "
|
||||
+ "else return 0 end"
|
||||
);
|
||||
RELEASE_LOCK_SCRIPT.setResultType(Long.class);
|
||||
}
|
||||
|
||||
private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<>() {
|
||||
};
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public GuardHandle tryAcquire(HttpServletRequest request, String action, Duration ttl) {
|
||||
String key = buildKey(request, action);
|
||||
String token = UUID.randomUUID().toString();
|
||||
Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(
|
||||
key,
|
||||
token,
|
||||
Math.max(1L, ttl == null ? 10L : ttl.getSeconds()),
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
return new GuardHandle(key, token, Boolean.TRUE.equals(success));
|
||||
}
|
||||
|
||||
public void release(GuardHandle handle) {
|
||||
if (handle == null || !handle.acquired()) {
|
||||
return;
|
||||
}
|
||||
stringRedisTemplate.execute(
|
||||
RELEASE_LOCK_SCRIPT,
|
||||
Collections.singletonList(handle.key()),
|
||||
handle.token()
|
||||
);
|
||||
}
|
||||
|
||||
public String buildKey(HttpServletRequest request, String action) {
|
||||
String safeAction = sanitize(action);
|
||||
String path = request == null ? "-" : sanitize(request.getRequestURI());
|
||||
Long userId = request == null ? null : parseLong(request.getAttribute("userId"));
|
||||
Integer userType = request == null ? null : parseInteger(request.getAttribute("userType"));
|
||||
Long shopId = request == null ? null : RequestShopContext.getCurrentShopId(request);
|
||||
|
||||
if (isUploadPath(path)) {
|
||||
return buildUploadKey(request, safeAction, userId);
|
||||
}
|
||||
|
||||
String fingerprint = buildRequestFingerprint(request, path);
|
||||
if (userId != null) {
|
||||
if (isAdminRequest(path, userType)) {
|
||||
return String.join(":",
|
||||
"op",
|
||||
"admin",
|
||||
String.valueOf(userId),
|
||||
safeAction,
|
||||
sanitize(shopId),
|
||||
fingerprint
|
||||
);
|
||||
}
|
||||
return String.join(":",
|
||||
"op",
|
||||
"user",
|
||||
String.valueOf(userId),
|
||||
safeAction,
|
||||
fingerprint
|
||||
);
|
||||
}
|
||||
|
||||
String subject = resolvePublicSubject(request);
|
||||
return String.join(":",
|
||||
"op",
|
||||
"public",
|
||||
safeAction,
|
||||
subject,
|
||||
sanitize(resolveClientIp(request)),
|
||||
sanitize(resolveDeviceId(request))
|
||||
);
|
||||
}
|
||||
|
||||
private String buildUploadKey(HttpServletRequest request, String action, Long userId) {
|
||||
String uploadId = firstNonBlank(
|
||||
request == null ? null : request.getParameter("uploadId"),
|
||||
readBodyField(request, "uploadId")
|
||||
);
|
||||
String chunkIndex = firstNonBlank(
|
||||
request == null ? null : request.getParameter("chunkIndex"),
|
||||
readBodyField(request, "chunkIndex")
|
||||
);
|
||||
String suffix = StringUtils.hasText(chunkIndex)
|
||||
? sanitize(chunkIndex)
|
||||
: buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI());
|
||||
return String.join(":",
|
||||
"op",
|
||||
"upload",
|
||||
sanitize(userId),
|
||||
action,
|
||||
sanitize(uploadId),
|
||||
suffix
|
||||
);
|
||||
}
|
||||
|
||||
private String buildRequestFingerprint(HttpServletRequest request, String path) {
|
||||
String canonicalParams = buildCanonicalParams(request == null ? null : request.getParameterMap());
|
||||
String bodyHash = buildBodyHash(request);
|
||||
String raw = String.join("|",
|
||||
sanitize(path),
|
||||
sanitize(canonicalParams),
|
||||
sanitize(bodyHash)
|
||||
);
|
||||
return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private String resolvePublicSubject(HttpServletRequest request) {
|
||||
for (String key : new String[]{"account", "phone", "shopId", "productId", "couponId", "userId", "uploadId", "ticket"}) {
|
||||
String value = firstNonBlank(
|
||||
request == null ? null : request.getParameter(key),
|
||||
readBodyField(request, key)
|
||||
);
|
||||
if (StringUtils.hasText(value)) {
|
||||
return sanitize(value);
|
||||
}
|
||||
}
|
||||
return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI());
|
||||
}
|
||||
|
||||
private String buildBodyHash(HttpServletRequest request) {
|
||||
if (request == null) {
|
||||
return "-";
|
||||
}
|
||||
Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE);
|
||||
if (cachedBody instanceof byte[] bytes && bytes.length > 0) {
|
||||
return DigestUtils.md5DigestAsHex(bytes);
|
||||
}
|
||||
return DigestUtils.md5DigestAsHex(
|
||||
buildCanonicalParams(request.getParameterMap()).getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
}
|
||||
|
||||
private String readBodyField(HttpServletRequest request, String fieldName) {
|
||||
if (request == null || !StringUtils.hasText(fieldName)) {
|
||||
return null;
|
||||
}
|
||||
Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE);
|
||||
if (!(cachedBody instanceof byte[] bytes) || bytes.length == 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Map<String, Object> payload = objectMapper.readValue(bytes, MAP_TYPE);
|
||||
Object value = payload.get(fieldName);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String buildCanonicalParams(Map<String, String[]> parameterMap) {
|
||||
if (parameterMap == null || parameterMap.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
Map<String, String[]> sorted = new LinkedHashMap<>();
|
||||
parameterMap.entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.forEach(entry -> sorted.put(entry.getKey(), entry.getValue()));
|
||||
StringBuilder builder = new StringBuilder();
|
||||
sorted.forEach((key, values) -> {
|
||||
if (builder.length() > 0) {
|
||||
builder.append('&');
|
||||
}
|
||||
builder.append(key)
|
||||
.append('=')
|
||||
.append(String.join(",", sortValues(values)));
|
||||
});
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private String[] sortValues(String[] values) {
|
||||
String[] copy = values == null ? new String[0] : values.clone();
|
||||
Arrays.sort(copy, Comparator.nullsLast(String::compareTo));
|
||||
return copy;
|
||||
}
|
||||
|
||||
private boolean isUploadPath(String path) {
|
||||
return StringUtils.hasText(path) && path.contains("/upload/");
|
||||
}
|
||||
|
||||
private boolean isAdminRequest(String path, Integer userType) {
|
||||
return (StringUtils.hasText(path) && (path.startsWith("/admin/") || path.startsWith("/order/admin/")))
|
||||
|| (userType != null && userType >= 2);
|
||||
}
|
||||
|
||||
private String resolveClientIp(HttpServletRequest request) {
|
||||
if (request == null) {
|
||||
return "-";
|
||||
}
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.hasText(forwarded)) {
|
||||
return forwarded.split(",")[0].trim();
|
||||
}
|
||||
String realIp = request.getHeader("X-Real-IP");
|
||||
if (StringUtils.hasText(realIp)) {
|
||||
return realIp.trim();
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
|
||||
private String resolveDeviceId(HttpServletRequest request) {
|
||||
if (request == null) {
|
||||
return "-";
|
||||
}
|
||||
return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER);
|
||||
}
|
||||
|
||||
private String sanitize(Object value) {
|
||||
if (value == null) {
|
||||
return "-";
|
||||
}
|
||||
String text = String.valueOf(value).trim();
|
||||
return text.isEmpty() ? "-" : text.replace(":", "_");
|
||||
}
|
||||
|
||||
private String firstNonBlank(String... values) {
|
||||
if (values == null) {
|
||||
return null;
|
||||
}
|
||||
for (String value : values) {
|
||||
if (StringUtils.hasText(value)) {
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Long parseLong(Object value) {
|
||||
if (value instanceof Number number) {
|
||||
return number.longValue();
|
||||
}
|
||||
if (value instanceof String text && StringUtils.hasText(text)) {
|
||||
try {
|
||||
return Long.parseLong(text.trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Integer parseInteger(Object value) {
|
||||
if (value instanceof Number number) {
|
||||
return number.intValue();
|
||||
}
|
||||
if (value instanceof String text && StringUtils.hasText(text)) {
|
||||
try {
|
||||
return Integer.parseInt(text.trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public record GuardHandle(String key, String token, boolean acquired) {
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.xiaowang.yuminailcore.support.security;
|
||||
|
||||
public enum OperationGuardStrategy {
|
||||
REJECT_IF_RUNNING,
|
||||
NOOP_IF_DUPLICATE
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package com.xiaowang.yuminailcore.support.security;
|
||||
|
||||
import com.xiaowang.yuminailcore.config.RequestSignatureProperties;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 已登录写接口签名校验。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RequestSignatureService {
|
||||
|
||||
public static final String REQUEST_BODY_ATTRIBUTE = "cachedRequestBody";
|
||||
public static final String HEADER_TIMESTAMP = "X-Timestamp";
|
||||
public static final String HEADER_NONCE = "X-Nonce";
|
||||
public static final String HEADER_SIGNATURE = "X-Signature";
|
||||
public static final String HEADER_SIGNATURE_VERSION = "X-Sign-Version";
|
||||
|
||||
private static final String SIGNATURE_VERSION = "v1";
|
||||
private static final String HMAC_ALGORITHM = "HmacSHA256";
|
||||
|
||||
private final RequestSignatureProperties properties;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public void validateRequest(HttpServletRequest request, String accessToken, Long userId) {
|
||||
if (!properties.isEnabled() || isSafeMethod(request.getMethod())) {
|
||||
return;
|
||||
}
|
||||
if (!StringUtils.hasText(accessToken)) {
|
||||
throw new RuntimeException("请求签名缺少登录态");
|
||||
}
|
||||
|
||||
String version = request.getHeader(HEADER_SIGNATURE_VERSION);
|
||||
String timestamp = request.getHeader(HEADER_TIMESTAMP);
|
||||
String nonce = request.getHeader(HEADER_NONCE);
|
||||
String signature = request.getHeader(HEADER_SIGNATURE);
|
||||
|
||||
if (!SIGNATURE_VERSION.equals(version)) {
|
||||
throw new RuntimeException("请求签名版本不正确");
|
||||
}
|
||||
if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) {
|
||||
throw new RuntimeException("请求签名缺失");
|
||||
}
|
||||
|
||||
validateTimestamp(timestamp);
|
||||
registerNonce(userId, nonce);
|
||||
|
||||
String bodyHash = sha256Hex(resolvePayloadBytes(request));
|
||||
String canonical = request.getMethod().toUpperCase()
|
||||
+ "\n" + request.getRequestURI()
|
||||
+ "\n" + timestamp
|
||||
+ "\n" + nonce
|
||||
+ "\n" + bodyHash;
|
||||
String expected = hmacSha256Hex(accessToken, canonical);
|
||||
if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8))) {
|
||||
throw new RuntimeException("请求签名无效");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateTimestamp(String timestamp) {
|
||||
long requestTimestamp;
|
||||
try {
|
||||
requestTimestamp = Long.parseLong(timestamp);
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new RuntimeException("请求时间戳不合法");
|
||||
}
|
||||
long now = Instant.now().toEpochMilli();
|
||||
long delta = Math.abs(now - requestTimestamp);
|
||||
if (delta > properties.getWindowSeconds() * 1000L) {
|
||||
throw new RuntimeException("请求已过期,请重试");
|
||||
}
|
||||
}
|
||||
|
||||
private void registerNonce(Long userId, String nonce) {
|
||||
String nonceKey = "request:nonce:" + (userId == null ? "anon" : userId) + ":" + nonce;
|
||||
Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(
|
||||
nonceKey,
|
||||
"1",
|
||||
properties.getNonceRetentionSeconds(),
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
if (Boolean.FALSE.equals(success)) {
|
||||
throw new RuntimeException("请求已失效,请勿重复提交");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSafeMethod(String method) {
|
||||
if (!StringUtils.hasText(method)) {
|
||||
return true;
|
||||
}
|
||||
String normalized = method.toUpperCase();
|
||||
return "GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized);
|
||||
}
|
||||
|
||||
private byte[] resolvePayloadBytes(HttpServletRequest request) {
|
||||
Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE);
|
||||
if (cachedBody instanceof byte[] bytes && bytes.length > 0) {
|
||||
return bytes;
|
||||
}
|
||||
String canonicalParams = buildCanonicalParams(request.getParameterMap());
|
||||
return canonicalParams.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String buildCanonicalParams(Map<String, String[]> parameterMap) {
|
||||
if (parameterMap == null || parameterMap.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return parameterMap.entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.map(entry -> entry.getKey() + "=" + String.join(",", sorted(entry.getValue())))
|
||||
.reduce((left, right) -> left + "&" + right)
|
||||
.orElse("");
|
||||
}
|
||||
|
||||
private String[] sorted(String[] values) {
|
||||
String[] result = values == null ? new String[0] : values.clone();
|
||||
Arrays.sort(result, Comparator.nullsLast(String::compareTo));
|
||||
return result;
|
||||
}
|
||||
|
||||
private String sha256Hex(byte[] payload) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] bytes = digest.digest(payload == null ? new byte[0] : payload);
|
||||
return toHex(bytes);
|
||||
} catch (Exception exception) {
|
||||
throw new RuntimeException("计算请求摘要失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String hmacSha256Hex(String secret, String text) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
|
||||
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM));
|
||||
return toHex(mac.doFinal(text.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception exception) {
|
||||
throw new RuntimeException("计算请求签名失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String toHex(byte[] bytes) {
|
||||
StringBuilder builder = new StringBuilder(bytes.length * 2);
|
||||
for (byte value : bytes) {
|
||||
builder.append(String.format("%02x", value));
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.xiaowang.yuminailcore.support.security;
|
||||
|
||||
import com.xiaowang.yuminailcore.config.RateLimitProperties;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.DigestUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 请求限流服务。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RequestThrottleService {
|
||||
|
||||
public static final String DEVICE_ID_HEADER = "X-Device-Id";
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final RateLimitProperties rateLimitProperties;
|
||||
|
||||
public void checkLogin(HttpServletRequest request, String account) {
|
||||
RateLimitProperties.LimitRule rule = rateLimitProperties.getLogin();
|
||||
assertAllowed("login", request, sanitize(account), rule, "登录过于频繁,请稍后再试");
|
||||
}
|
||||
|
||||
public void checkSendCode(HttpServletRequest request, String phone) {
|
||||
RateLimitProperties.LimitRule rule = rateLimitProperties.getSendCode();
|
||||
assertAllowed("send-code", request, sanitize(phone), rule, "验证码发送过于频繁,请稍后再试");
|
||||
}
|
||||
|
||||
public void checkResetPassword(HttpServletRequest request, String phone) {
|
||||
RateLimitProperties.LimitRule rule = rateLimitProperties.getResetPassword();
|
||||
assertAllowed("reset-password", request, sanitize(phone), rule, "密码重置请求过于频繁,请稍后再试");
|
||||
}
|
||||
|
||||
public void checkAuthenticatedWrite(HttpServletRequest request, Long userId) {
|
||||
String path = request.getRequestURI();
|
||||
RateLimitProperties.LimitRule rule = rateLimitProperties.getAuthenticatedWrite();
|
||||
String message = "操作过于频繁,请稍后再试";
|
||||
String category = "write:" + path;
|
||||
if ("/order/create".equals(path)) {
|
||||
rule = rateLimitProperties.getOrderCreate();
|
||||
message = "下单过于频繁,请稍后再试";
|
||||
}
|
||||
assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message);
|
||||
}
|
||||
|
||||
private void assertAllowed(String category,
|
||||
HttpServletRequest request,
|
||||
String subject,
|
||||
RateLimitProperties.LimitRule rule,
|
||||
String message) {
|
||||
if (rule == null || rule.getLimit() <= 0 || rule.getWindowSeconds() <= 0) {
|
||||
return;
|
||||
}
|
||||
String raw = String.join("|",
|
||||
category,
|
||||
sanitize(resolveClientIp(request)),
|
||||
sanitize(resolveDeviceId(request)),
|
||||
sanitize(subject)
|
||||
);
|
||||
String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8));
|
||||
Long count = stringRedisTemplate.opsForValue().increment(key);
|
||||
if (count != null && count == 1L) {
|
||||
stringRedisTemplate.expire(key, rule.getWindowSeconds(), TimeUnit.SECONDS);
|
||||
}
|
||||
if (count != null && count > rule.getLimit()) {
|
||||
throw new RuntimeException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveClientIp(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.hasText(forwarded)) {
|
||||
return forwarded.split(",")[0].trim();
|
||||
}
|
||||
String realIp = request.getHeader("X-Real-IP");
|
||||
if (StringUtils.hasText(realIp)) {
|
||||
return realIp.trim();
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
|
||||
private String resolveDeviceId(HttpServletRequest request) {
|
||||
return request.getHeader(DEVICE_ID_HEADER);
|
||||
}
|
||||
|
||||
private String sanitize(String value) {
|
||||
return StringUtils.hasText(value) ? value.trim() : "-";
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package com.xiaowang.yuminailcore.support.security;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.yuminailcore.config.JwtProperties;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 基于 Redis 的登录会话状态。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class UserSessionService {
|
||||
|
||||
private static final String SESSION_KEY_PREFIX = "auth:session:";
|
||||
private static final String USER_SESSION_SET_PREFIX = "auth:user:sessions:";
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final JwtProperties jwtProperties;
|
||||
private final TimeOrderedSnowflakeIdGenerator idGenerator;
|
||||
|
||||
public SessionIssueResult issueSession(Long userId, String account, Long shopId, Integer userType) {
|
||||
String sessionId = idGenerator.nextIdString();
|
||||
String accessJti = idGenerator.nextIdString();
|
||||
String refreshJti = idGenerator.nextIdString();
|
||||
SessionState state = SessionState.builder()
|
||||
.sessionId(sessionId)
|
||||
.userId(userId)
|
||||
.account(account)
|
||||
.shopId(shopId)
|
||||
.userType(userType)
|
||||
.accessJti(accessJti)
|
||||
.refreshJti(refreshJti)
|
||||
.build();
|
||||
save(state);
|
||||
return new SessionIssueResult(sessionId, accessJti, refreshJti);
|
||||
}
|
||||
|
||||
public SessionIssueResult rotateSession(String previousSessionId, Long userId, String account, Long shopId, Integer userType) {
|
||||
revokeSession(previousSessionId);
|
||||
return issueSession(userId, account, shopId, userType);
|
||||
}
|
||||
|
||||
public boolean isAccessSessionActive(Long userId, String sessionId, String accessJti) {
|
||||
SessionState state = getSessionState(sessionId);
|
||||
return matches(state, userId) && StringUtils.hasText(accessJti) && accessJti.equals(state.getAccessJti());
|
||||
}
|
||||
|
||||
public boolean isRefreshSessionActive(Long userId, String sessionId, String refreshJti) {
|
||||
SessionState state = getSessionState(sessionId);
|
||||
return matches(state, userId) && StringUtils.hasText(refreshJti) && refreshJti.equals(state.getRefreshJti());
|
||||
}
|
||||
|
||||
public void revokeSession(String sessionId) {
|
||||
if (!StringUtils.hasText(sessionId)) {
|
||||
return;
|
||||
}
|
||||
SessionState state = getSessionState(sessionId);
|
||||
stringRedisTemplate.delete(buildSessionKey(sessionId));
|
||||
if (state != null && state.getUserId() != null) {
|
||||
stringRedisTemplate.opsForSet().remove(buildUserSessionSetKey(state.getUserId()), sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
public void revokeAllUserSessions(Long userId) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
String setKey = buildUserSessionSetKey(userId);
|
||||
Set<String> sessionIds = stringRedisTemplate.opsForSet().members(setKey);
|
||||
if (sessionIds != null) {
|
||||
for (String sessionId : sessionIds) {
|
||||
stringRedisTemplate.delete(buildSessionKey(sessionId));
|
||||
}
|
||||
}
|
||||
stringRedisTemplate.delete(setKey);
|
||||
}
|
||||
|
||||
private boolean matches(SessionState state, Long userId) {
|
||||
return state != null && state.getUserId() != null && state.getUserId().equals(userId);
|
||||
}
|
||||
|
||||
private void save(SessionState state) {
|
||||
try {
|
||||
String sessionKey = buildSessionKey(state.getSessionId());
|
||||
String setKey = buildUserSessionSetKey(state.getUserId());
|
||||
Duration ttl = Duration.ofSeconds(jwtProperties.getRefreshTokenExpirationSeconds());
|
||||
String json = objectMapper.writeValueAsString(state);
|
||||
stringRedisTemplate.opsForValue().set(sessionKey, json, ttl.getSeconds(), TimeUnit.SECONDS);
|
||||
stringRedisTemplate.opsForSet().add(setKey, state.getSessionId());
|
||||
stringRedisTemplate.expire(setKey, ttl.getSeconds(), TimeUnit.SECONDS);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new RuntimeException("写入登录会话失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private SessionState getSessionState(String sessionId) {
|
||||
if (!StringUtils.hasText(sessionId)) {
|
||||
return null;
|
||||
}
|
||||
String json = stringRedisTemplate.opsForValue().get(buildSessionKey(sessionId));
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, SessionState.class);
|
||||
} catch (JsonProcessingException exception) {
|
||||
stringRedisTemplate.delete(buildSessionKey(sessionId));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String buildSessionKey(String sessionId) {
|
||||
return SESSION_KEY_PREFIX + sessionId;
|
||||
}
|
||||
|
||||
private String buildUserSessionSetKey(Long userId) {
|
||||
return USER_SESSION_SET_PREFIX + userId;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class SessionState {
|
||||
private String sessionId;
|
||||
private Long userId;
|
||||
private String account;
|
||||
private Long shopId;
|
||||
private Integer userType;
|
||||
private String accessJti;
|
||||
private String refreshJti;
|
||||
}
|
||||
|
||||
public record SessionIssueResult(String sessionId, String accessJti, String refreshJti) {
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.xiaowang.yuminailcore.utils;
|
||||
|
||||
import com.xiaowang.yuminailcore.config.JwtProperties;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
@@ -13,38 +15,39 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class JwtUtil {
|
||||
|
||||
private static final String SECRET = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
|
||||
private static final long ACCESS_TOKEN_EXPIRATION = 2 * 60 * 60 * 1000;
|
||||
private static final long REFRESH_TOKEN_EXPIRATION = 7 * 24 * 60 * 60 * 1000;
|
||||
private final JwtProperties jwtProperties;
|
||||
|
||||
private final SecretKey key;
|
||||
|
||||
public JwtUtil() {
|
||||
this.key = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));
|
||||
private SecretKey getKey() {
|
||||
return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public String generateAccessToken(Long userId, String account, Long currentShopId) {
|
||||
public String generateAccessToken(Long userId, String account, Long currentShopId, String sessionId, String jti) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("userId", userId);
|
||||
claims.put("account", account);
|
||||
claims.put("type", "access");
|
||||
claims.put("sessionId", sessionId);
|
||||
claims.put("jti", jti);
|
||||
if (currentShopId != null && currentShopId > 0) {
|
||||
claims.put("shopId", currentShopId);
|
||||
}
|
||||
return createToken(claims, userId.toString(), ACCESS_TOKEN_EXPIRATION);
|
||||
return createToken(claims, userId.toString(), jwtProperties.getAccessTokenExpirationSeconds() * 1000);
|
||||
}
|
||||
|
||||
public String generateRefreshToken(Long userId, String account, Long currentShopId) {
|
||||
public String generateRefreshToken(Long userId, String account, Long currentShopId, String sessionId, String jti) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("userId", userId);
|
||||
claims.put("account", account);
|
||||
claims.put("type", "refresh");
|
||||
claims.put("sessionId", sessionId);
|
||||
claims.put("jti", jti);
|
||||
if (currentShopId != null && currentShopId > 0) {
|
||||
claims.put("shopId", currentShopId);
|
||||
}
|
||||
return createToken(claims, userId.toString(), REFRESH_TOKEN_EXPIRATION);
|
||||
return createToken(claims, userId.toString(), jwtProperties.getRefreshTokenExpirationSeconds() * 1000);
|
||||
}
|
||||
|
||||
private String createToken(Map<String, Object> claims, String subject, long expiration) {
|
||||
@@ -54,15 +57,18 @@ public class JwtUtil {
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setSubject(subject)
|
||||
.setIssuer(jwtProperties.getIssuer())
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiryDate)
|
||||
.signWith(key, SignatureAlgorithm.HS512)
|
||||
.signWith(getKey(), SignatureAlgorithm.HS512)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims parseToken(String token) {
|
||||
return Jwts.parserBuilder()
|
||||
.setSigningKey(key)
|
||||
.setSigningKey(getKey())
|
||||
.setAllowedClockSkewSeconds(jwtProperties.getClockSkewSeconds())
|
||||
.requireIssuer(jwtProperties.getIssuer())
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
@@ -83,6 +89,21 @@ public class JwtUtil {
|
||||
return claims.get("type", String.class);
|
||||
}
|
||||
|
||||
public String getSessionIdFromToken(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
return claims.get("sessionId", String.class);
|
||||
}
|
||||
|
||||
public String getJtiFromToken(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
return claims.get("jti", String.class);
|
||||
}
|
||||
|
||||
public String getIssuerFromToken(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
return claims.getIssuer();
|
||||
}
|
||||
|
||||
public Long getShopIdFromToken(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
Object value = claims.get("shopId");
|
||||
|
||||
@@ -24,3 +24,48 @@ server:
|
||||
mybatis:
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
|
||||
yuminail:
|
||||
security:
|
||||
jwt:
|
||||
issuer: yuminail
|
||||
access-token-expiration-seconds: 7200
|
||||
refresh-token-expiration-seconds: 604800
|
||||
clock-skew-seconds: 30
|
||||
signature:
|
||||
enabled: true
|
||||
window-seconds: 300
|
||||
nonce-retention-seconds: 600
|
||||
rate-limit:
|
||||
login:
|
||||
limit: 10
|
||||
window-seconds: 60
|
||||
send-code:
|
||||
limit: 5
|
||||
window-seconds: 60
|
||||
reset-password:
|
||||
limit: 5
|
||||
window-seconds: 600
|
||||
authenticated-write:
|
||||
limit: 80
|
||||
window-seconds: 60
|
||||
order-create:
|
||||
limit: 10
|
||||
window-seconds: 60
|
||||
cache:
|
||||
local-max-size: 2048
|
||||
product-detail:
|
||||
local-ttl-seconds: 120
|
||||
redis-ttl-seconds: 900
|
||||
product-list:
|
||||
local-ttl-seconds: 60
|
||||
redis-ttl-seconds: 300
|
||||
product-search:
|
||||
local-ttl-seconds: 60
|
||||
redis-ttl-seconds: 300
|
||||
shop:
|
||||
local-ttl-seconds: 180
|
||||
redis-ttl-seconds: 900
|
||||
tag:
|
||||
local-ttl-seconds: 300
|
||||
redis-ttl-seconds: 1200
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
|
||||
<PatternLayout pattern="${LOG_PATTERN}"/>
|
||||
</Console>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user