重构Salon后台单管理员与经营驾驶舱

This commit is contained in:
2026-10-26 01:19:23 +08:00
parent 17cf16db36
commit b8327146cb
35 changed files with 1087 additions and 4158 deletions
@@ -79,6 +79,15 @@ public class PermissionAspect {
return Result.error(404, "用户不存在");
}
// Salon 后台只有平台管理员,登录后台后的数据范围统一为全平台。
// 权限表继续保留给小程序和兼容接口使用,但不再阻断管理员后台请求。
String requestPath = request.getRequestURI();
boolean adminPath = requestPath != null
&& (requestPath.startsWith("/admin/") || requestPath.startsWith("/order/admin/"));
if (adminPath && Integer.valueOf(4).equals(userDO.getType())) {
return joinPoint.proceed();
}
String permissionCode = requirePermission.value();
Long currentShopId = parseShopId(request.getAttribute("currentShopId"));
if (Integer.valueOf(4).equals(userDO.getType())
@@ -117,10 +117,13 @@ public class AuthInterceptor implements HandlerInterceptor {
}
boolean adminPath = isAdminPath(path);
if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限");
if (adminPath && !Integer.valueOf(4).equals(currentUser.getType())) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "仅平台管理员可以访问后台管理系统");
return false;
}
if (adminPath && Integer.valueOf(4).equals(currentUser.getType())) {
currentShopId = null;
}
boolean canAccessShop = userShopBindingSupport.canUserAccessShop(
userId,
@@ -139,14 +142,6 @@ public class AuthInterceptor implements HandlerInterceptor {
return false;
}
if (adminPath
&& !Integer.valueOf(4).equals(currentUser.getType())
&& userShopBindingSupport.isShopAuthorizationExpired(currentShopId)
&& !isExpiredAdminAllowedPath(path)) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员");
return false;
}
if (requiresSignature(request)) {
try {
requestSignatureService.validateRequest(request, token, userId);
@@ -205,19 +200,6 @@ public class AuthInterceptor implements HandlerInterceptor {
return path.startsWith("/admin/") || path.startsWith("/order/admin/");
}
/**
* Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean isExpiredAdminAllowedPath(String path) {
return path.startsWith("/admin/auth/")
|| path.equals("/admin/user/info")
|| path.equals("/permission/list/user/current")
|| path.equals("/api/permission/list/user/current")
|| path.startsWith("/admin/planning/")
|| path.startsWith("/admin/shops/");
}
/**
* Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
@@ -73,7 +73,6 @@ public class WebMvcConfig implements WebMvcConfigurer {
"/tag/list/filter-options",
"/file/get-signed-url/**",
"/admin/auth/login",
"/admin/auth/login-shops/**",
"/admin/auth/refresh",
"/error",
"/health/**"
@@ -15,6 +15,7 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.salon.core.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
@@ -25,16 +26,35 @@ import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.DashboardStatsVO;
import com.xiaowang.jayucloud.salon.core.modules.product.vo.HotProductVO;
import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.OperationsAnalyticsVO;
import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.RecentActivityVO;
import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.SalonDashboardOverviewVO;
import com.xiaowang.jayucloud.salon.core.modules.analytics.mapper.SalonDashboardMapper;
import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO;
import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationStatus;
import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.AfterSaleDO;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistChangeRequestDO;
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.AfterSaleMapper;
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistChangeRequestMapper;
import com.xiaowang.jayucloud.salon.core.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.jayucloud.salon.core.modules.inventory.entity.InventoryItemDO;
import com.xiaowang.jayucloud.salon.core.modules.inventory.mapper.InventoryItemMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -44,6 +64,7 @@ import java.util.stream.Collectors;
@RestController
@RequestMapping("/admin/dashboard")
@RequiredArgsConstructor
@Slf4j
/**
* DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
@@ -90,6 +111,149 @@ public class DashboardController {
*/
private final AppCacheProperties appCacheProperties;
private final OperationsAnalyticsService operationsAnalyticsService;
private final WorkbenchRegistrationApplicationMapper registrationMapper;
private final ContentModerationRecordMapper contentModerationRecordMapper;
private final AfterSaleMapper afterSaleMapper;
private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
private final AppointmentReservationMapper appointmentReservationMapper;
private final InventoryItemMapper inventoryItemMapper;
private final SalonDashboardMapper salonDashboardMapper;
/**
* Salon 平台管理员专用驾驶舱。旧 stats/analytics 接口保留兼容,但首页只使用本接口。
*/
@GetMapping("/overview")
public Result<SalonDashboardOverviewVO> getOverview(
@RequestParam(required = false) String date,
@RequestParam(required = false, defaultValue = "7") Integer days) {
LocalDate targetDate = parseOverviewDate(date);
int rangeDays = days != null && days == 30 ? 30 : 7;
try {
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard();
String cacheKey = "cache:salon-dashboard:overview:" + targetDate + ":" + rangeDays;
return Result.success(multiLevelCacheService.getOrLoad(
cacheKey,
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<SalonDashboardOverviewVO>() { },
() -> buildSalonOverview(targetDate, rangeDays)
));
} catch (Exception exception) {
log.warn("Salon 驾驶舱统计失败,返回空数据: date={}, days={}", targetDate, rangeDays, exception);
SalonDashboardOverviewVO empty = emptySalonOverview(targetDate, rangeDays);
empty.setDegraded(true);
empty.setDegradedMessage("部分经营数据暂时不可用,刷新后重试");
return Result.success(empty);
}
}
private LocalDate parseOverviewDate(String value) {
if (value == null || value.isBlank()) return LocalDate.now();
try {
return LocalDate.parse(value);
} catch (DateTimeParseException exception) {
return LocalDate.now();
}
}
private SalonDashboardOverviewVO emptySalonOverview(LocalDate date, int days) {
SalonDashboardOverviewVO overview = new SalonDashboardOverviewVO();
overview.setDate(date.toString());
for (int index = days - 1; index >= 0; index--) {
SalonDashboardOverviewVO.TrendItem item = new SalonDashboardOverviewVO.TrendItem();
item.setDate(date.minusDays(index).toString());
overview.getTrend().add(item);
}
return overview;
}
private SalonDashboardOverviewVO buildSalonOverview(LocalDate date, int days) {
SalonDashboardOverviewVO overview = emptySalonOverview(date, days);
SalonDashboardOverviewVO.Platform platform = overview.getPlatform();
platform.setActiveShopCount(shopMapper.selectCount(new LambdaQueryWrapper<ShopDO>()
.eq(ShopDO::getStatus, 1).eq(ShopDO::getIsDelete, 0)));
platform.setActiveManagerCount(countUsersByType(2));
platform.setActiveStaffCount(countUsersByType(3));
platform.setCustomerCount(countUsersByType(0));
platform.setStyleCount(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>()
.eq(ProductDO::getIsDelete, 0)
.eq(ProductDO::getFrontVisible, 1)
.eq(ProductDO::getModerationStatus, "APPROVED")));
LocalDate rangeStart = date.minusDays(days - 1);
List<Map<String, Object>> trendRows = salonDashboardMapper.selectOrderTrend(rangeStart, date);
Map<String, SalonDashboardOverviewVO.TrendItem> trendByDate = overview.getTrend().stream()
.collect(Collectors.toMap(SalonDashboardOverviewVO.TrendItem::getDate, item -> item, (left, right) -> left, LinkedHashMap::new));
for (Map<String, Object> row : trendRows) {
String rowDate = stringValue(row, "date");
SalonDashboardOverviewVO.TrendItem item = trendByDate.get(rowDate);
if (item == null) continue;
item.setAppointmentCount(longValue(row, "appointmentCount"));
item.setCompletedCount(longValue(row, "completedCount"));
item.setAmount(decimalValue(row, "amount"));
if (date.equals(LocalDate.parse(rowDate))) {
overview.getToday().setServiceInProgressCount(longValue(row, "serviceInProgressCount"));
overview.getToday().setPendingOrderCount(longValue(row, "pendingOrderCount"));
overview.getToday().setCompletedServiceCount(longValue(row, "completedCount"));
overview.getToday().setOrderAmount(decimalValue(row, "amount"));
overview.getToday().setAppointmentCount(longValue(row, "appointmentCount"));
}
}
List<SalonDashboardOverviewVO.ShopRankingItem> ranking = new ArrayList<>();
for (Map<String, Object> row : salonDashboardMapper.selectShopRanking(rangeStart, date)) {
SalonDashboardOverviewVO.ShopRankingItem item = new SalonDashboardOverviewVO.ShopRankingItem();
item.setShopId(numberValue(row, "shopId"));
item.setShopName(stringValue(row, "shopName"));
item.setAppointmentCount(longValue(row, "appointmentCount"));
item.setCompletedCount(longValue(row, "completedCount"));
item.setAmount(decimalValue(row, "amount"));
ranking.add(item);
}
overview.setShopRanking(ranking);
overview.getAttention().setRegistrationReviewCount(registrationMapper.selectCount(new LambdaQueryWrapper<WorkbenchRegistrationApplicationDO>()
.eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0)
.in(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN, WorkbenchRegistrationStatus.PENDING_MANAGER)));
overview.getAttention().setContentReviewCount(contentModerationRecordMapper.selectCount(new LambdaQueryWrapper<ContentModerationRecordDO>()
.in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY")));
overview.getAttention().setAfterSaleCount(afterSaleMapper.selectCount(new LambdaQueryWrapper<AfterSaleDO>()
.eq(AfterSaleDO::getIsDelete, 0).eq(AfterSaleDO::getStatus, "PENDING")));
overview.getAttention().setArtistChangeCount(orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper<OrderArtistChangeRequestDO>()
.eq(OrderArtistChangeRequestDO::getIsDelete, 0).eq(OrderArtistChangeRequestDO::getStatus, "PENDING")));
overview.getAttention().setLowStockCount(inventoryItemMapper.selectCount(new LambdaQueryWrapper<InventoryItemDO>()
.eq(InventoryItemDO::getIsDelete, 0)
.apply("stock_quantity <= warning_threshold")));
return overview;
}
private String stringValue(Map<String, Object> row, String key) {
Object value = row.get(key);
return value == null ? "" : value.toString();
}
private long longValue(Map<String, Object> row, String key) {
Object value = row.get(key);
return value instanceof Number ? ((Number) value).longValue() : 0L;
}
private Long numberValue(Map<String, Object> row, String key) {
Object value = row.get(key);
return value instanceof Number ? ((Number) value).longValue() : null;
}
private BigDecimal decimalValue(Map<String, Object> row, String key) {
Object value = row.get(key);
if (value instanceof BigDecimal) return (BigDecimal) value;
if (value instanceof Number) return BigDecimal.valueOf(((Number) value).doubleValue());
return BigDecimal.ZERO;
}
private long countUsersByType(int type) {
return userMapper.selectCount(new LambdaQueryWrapper<UserDO>()
.eq(UserDO::getIsDelete, 0)
.eq(UserDO::getType, type)
.eq(UserDO::getStatus, 1));
}
@GetMapping("/stats")
@RequirePermission("dashboard:view")
@@ -0,0 +1,42 @@
package com.xiaowang.jayucloud.salon.core.modules.analytics.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
/** Salon 驾驶舱趋势和门店排行聚合查询。 */
@Mapper
public interface SalonDashboardMapper {
String BUSINESS_ORDERS = "(SELECT o.id, o.shop_id, o.status, o.order_source, "
+ "CASE WHEN o.order_source = 'HISTORICAL_BACKFILL' "
+ "THEN COALESCE(item.service_date, DATE(o.create_time)) "
+ "ELSE COALESCE(DATE(item.appointment_time), DATE(o.create_time)) END AS business_date, "
+ "item.appointment_time, COALESCE(o.actual_amount, o.total_amount, 0) AS amount "
+ "FROM t_order o LEFT JOIN (SELECT order_id, MIN(appointment_time) AS appointment_time, "
+ "MIN(service_date) AS service_date FROM t_order_item WHERE is_delete = 0 GROUP BY order_id) item "
+ "ON item.order_id = o.id WHERE o.is_delete = 0 AND o.status <> 3)";
@Select("SELECT DATE_FORMAT(business_date, '%Y-%m-%d') AS date, "
+ "SUM(CASE WHEN order_source <> 'HISTORICAL_BACKFILL' AND appointment_time IS NOT NULL AND status <> 3 THEN 1 ELSE 0 END) AS appointmentCount, "
+ "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS completedCount, "
+ "SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS serviceInProgressCount, "
+ "SUM(CASE WHEN status IN (0, 1) THEN 1 ELSE 0 END) AS pendingOrderCount, "
+ "SUM(amount) AS amount FROM " + BUSINESS_ORDERS + " business_orders"
+ " WHERE business_date BETWEEN #{startDate} AND #{endDate} GROUP BY business_date ORDER BY business_date")
List<Map<String, Object>> selectOrderTrend(@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
@Select("SELECT s.id AS shopId, s.shop_name AS shopName, "
+ "SUM(CASE WHEN o.order_source <> 'HISTORICAL_BACKFILL' AND o.appointment_time IS NOT NULL AND o.status <> 3 THEN 1 ELSE 0 END) AS appointmentCount, "
+ "SUM(CASE WHEN o.status = 2 THEN 1 ELSE 0 END) AS completedCount, SUM(o.amount) AS amount "
+ "FROM " + BUSINESS_ORDERS + " o JOIN t_shop s ON s.id = o.shop_id AND s.is_delete = 0 "
+ "WHERE o.business_date BETWEEN #{startDate} AND #{endDate} "
+ "GROUP BY s.id, s.shop_name ORDER BY amount DESC LIMIT 10")
List<Map<String, Object>> selectShopRanking(@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
}
@@ -0,0 +1,72 @@
package com.xiaowang.jayucloud.salon.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* Salon 平台管理员驾驶舱数据。
* 该 VO 只包含 Salon 经营口径,不复用 ArtList 的流量和电商指标。
*/
@Data
public class SalonDashboardOverviewVO {
private String date;
private boolean degraded;
private String degradedMessage;
private Platform platform = new Platform();
private Today today = new Today();
private Attention attention = new Attention();
private List<TrendItem> trend = new ArrayList<>();
private List<ShopRankingItem> shopRanking = new ArrayList<>();
@Data
public static class Platform {
private long activeShopCount;
private long activeManagerCount;
private long activeStaffCount;
private long customerCount;
private long styleCount;
}
@Data
public static class Today {
private long appointmentCount;
private long serviceInProgressCount;
private long completedServiceCount;
private BigDecimal orderAmount = BigDecimal.ZERO;
private long pendingOrderCount;
}
@Data
public static class Attention {
private long registrationReviewCount;
private long contentReviewCount;
private long afterSaleCount;
private long artistChangeCount;
private long lowStockCount;
public long total() {
return registrationReviewCount + contentReviewCount + afterSaleCount
+ artistChangeCount + lowStockCount;
}
}
@Data
public static class TrendItem {
private String date;
private long appointmentCount;
private long completedCount;
private BigDecimal amount = BigDecimal.ZERO;
}
@Data
public static class ShopRankingItem {
private Long shopId;
private String shopName;
private long appointmentCount;
private long completedCount;
private BigDecimal amount = BigDecimal.ZERO;
}
}
@@ -3,15 +3,13 @@ package com.xiaowang.jayucloud.salon.core.modules.auth.controller.admin;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.LoginRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningManagerRegisterDTO;
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.RefreshTokenRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.SwitchShopRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.AdminPasswordChangeRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.auth.service.admin.AdminAccountSecurityService;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService;
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils;
import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO;
import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@@ -40,6 +38,7 @@ public class AdminAuthController {
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final SecurityAuditLogService securityAuditLogService;
private final AdminAccountSecurityService adminAccountSecurityService;
@PostMapping("/login")
@OperationGuard(action = "admin-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
@@ -64,37 +63,6 @@ public class AdminAuthController {
}
}
@PostMapping("/register")
@OperationGuard(action = "admin-planning-register", ttlSeconds = 10, message = "注册处理中,请勿重复提交")
public Result<LoginResponseVO> register(@RequestBody PlanningManagerRegisterDTO registerDTO) {
return Result.success(userService.registerPlanningManager(registerDTO));
}
@GetMapping("/login-shops/{account}")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param account parameter `account` supplied by the caller
* @return Result<LoginShopSelectionVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginShopSelectionVO> getLoginShops(@PathVariable String account) {
return Result.success(userService.getAdminLoginShopSelection(AccountValidationUtils.requireValidAccount(account)));
}
@PostMapping("/switch-shop")
@OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作")
/**
* Run business method `switchShop`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller
* @return Result<LoginResponseVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId")));
}
@PostMapping("/logout")
@OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5)
/**
@@ -115,10 +83,9 @@ public class AdminAuthController {
* @return Result<LoginResponseVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginResponseVO> refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) {
LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken());
LoginResponseVO loginResponseVO = userService.adminRefreshToken(refreshTokenRequestDTO.getRefreshToken());
if (loginResponseVO.getUserInfo() == null
|| loginResponseVO.getUserInfo().getType() == null
|| loginResponseVO.getUserInfo().getType() < 2) {
|| !Integer.valueOf(4).equals(loginResponseVO.getUserInfo().getType())) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -128,4 +95,11 @@ public class AdminAuthController {
}
return Result.success(loginResponseVO);
}
@PostMapping("/password")
public Result<Boolean> changePassword(HttpServletRequest request,
@Valid @RequestBody AdminPasswordChangeRequestDTO passwordChangeRequest) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(adminAccountSecurityService.changePassword(userId, passwordChangeRequest));
}
}
@@ -0,0 +1,20 @@
package com.xiaowang.jayucloud.salon.core.modules.auth.dto;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Getter
@Setter
public class AdminPasswordChangeRequestDTO {
@NotBlank(message = "当前密码不能为空")
@Size(max = 128, message = "当前密码长度不能超过 128 位")
private String currentPassword;
@NotBlank(message = "新密码不能为空")
@Size(max = 128, message = "新密码长度不能超过 128 位")
private String newPassword;
}
@@ -0,0 +1,57 @@
package com.xiaowang.jayucloud.salon.core.modules.auth.service.admin;
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.AdminPasswordChangeRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.system.support.AdminDefaultPasswordSupport;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Service
@RequiredArgsConstructor
public class AdminAccountSecurityService {
private final UserMapper userMapper;
private final UserSessionService userSessionService;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@Transactional(rollbackFor = Exception.class)
public boolean changePassword(Long userId, AdminPasswordChangeRequestDTO request) {
if (userId == null || request == null) {
throw new RuntimeException("管理员账号信息无效");
}
UserDO admin = userMapper.selectById(userId);
if (admin == null || Integer.valueOf(1).equals(admin.getIsDelete())) {
throw new RuntimeException("管理员账号不存在或已失效");
}
if (!Integer.valueOf(4).equals(admin.getType())) {
throw new RuntimeException("仅平台管理员可以修改后台密码");
}
if (!Integer.valueOf(1).equals(admin.getStatus())) {
throw new RuntimeException("管理员账号已被禁用");
}
if (!StringUtils.hasText(request.getCurrentPassword())
|| !passwordEncoder.matches(request.getCurrentPassword(), admin.getPassword())) {
throw new RuntimeException("当前密码不正确");
}
String newPassword = request.getNewPassword();
AdminDefaultPasswordSupport.validatePasswordStrength(newPassword);
if (passwordEncoder.matches(newPassword, admin.getPassword())) {
throw new RuntimeException("新密码不能与当前密码相同");
}
admin.setPassword(passwordEncoder.encode(newPassword));
if (userMapper.updateById(admin) <= 0) {
throw new RuntimeException("密码保存失败,请重试");
}
userSessionService.revokeAllUserSessions(userId);
return true;
}
}
@@ -208,6 +208,15 @@ public interface UserService extends IService<UserDO> {
*/
LoginResponseVO refreshToken(String refreshToken);
/**
* Refresh a token for the platform administrator console.
*
* <p>This is deliberately separate from the user-facing refresh flow so
* the admin controller cannot accidentally change the rules used by the
* mini-program and front-end sessions.</p>
*/
LoginResponseVO adminRefreshToken(String refreshToken);
/**
* Run business method `logout`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -1365,6 +1365,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
assertLoginAccountAvailable(userDO);
if (!Integer.valueOf(4).equals(userDO.getType())) {
throw new RuntimeException("仅平台管理员可以登录后台管理系统");
}
if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) {
/**
* Run business method `handleLoginPasswordFailure`.
@@ -1375,17 +1379,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
handleLoginPasswordFailure(userDO);
}
Integer userType = userDO.getType();
if (userType == null || userType < 2) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("该账号不是后台管理账号");
}
Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId());
clearLoginFailureCount(userDO.getAccount());
/**
* Run business method `buildLoginResponse`.
@@ -1395,7 +1388,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @param false parameter `false` supplied by the caller
* @return return result consumed by the caller or returned to the frontend
*/
return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe()));
return buildLoginResponse(userDO, null, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe()));
}
@Override
@@ -1693,6 +1686,15 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return LoginResponseVO result consumed by the caller or returned to the frontend
*/
public LoginResponseVO refreshToken(String refreshToken) {
return refreshTokenInternal(refreshToken, false);
}
@Override
public LoginResponseVO adminRefreshToken(String refreshToken) {
return refreshTokenInternal(refreshToken, true);
}
private LoginResponseVO refreshTokenInternal(String refreshToken, boolean adminOnly) {
if (!jwtUtil.validateToken(refreshToken)) {
/**
* Run business method `RuntimeException`.
@@ -1715,7 +1717,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
Long userId = jwtUtil.getUserIdFromToken(refreshToken);
String account = jwtUtil.getAccountFromToken(refreshToken);
Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken));
Long currentShopId = adminOnly ? null : normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken));
String sessionId = jwtUtil.getSessionIdFromToken(refreshToken);
String refreshJti = jwtUtil.getJtiFromToken(refreshToken);
if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) {
@@ -1735,7 +1737,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return result consumed by the caller or returned to the frontend
*/
assertUserAvailable(userDO);
boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2;
if (adminOnly && !Integer.valueOf(4).equals(userDO.getType())) {
throw new RuntimeException("仅平台管理员可以刷新后台登录态");
}
boolean adminLogin = adminOnly || (userDO.getType() != null && userDO.getType() >= 2);
if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) {
/**
* Run business method `RuntimeException`.