Dev #100
+19
@@ -0,0 +1,19 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 拨号取号配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jayucloud-artlist.dial")
|
||||
public class DialProperties {
|
||||
|
||||
/**
|
||||
* 拨号提供方:direct(直拨真实号码)或 privacy-number(隐私号,未对接时明确报错)。
|
||||
*/
|
||||
private String provider = "direct";
|
||||
}
|
||||
+28
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.config;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -27,6 +28,7 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
log.info("start insert fill ....");
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
|
||||
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
fillPhoneHashes(metaObject);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -37,5 +39,31 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
log.info("start update fill ....");
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
fillPhoneHashes(metaObject);
|
||||
}
|
||||
|
||||
/**
|
||||
* 实体写入时按明文手机号刷新哈希列。
|
||||
* 注意:QueryWrapper/UpdateWrapper 的 set 不会经过这里,删除等场景需显式置空哈希。
|
||||
*/
|
||||
private void fillPhoneHashes(MetaObject metaObject) {
|
||||
if (metaObject.hasSetter("accountHash")) {
|
||||
Object account = getFieldValByName("account", metaObject);
|
||||
if (account != null) {
|
||||
setFieldValByName("accountHash", PhoneCrypto.current().index(String.valueOf(account)), metaObject);
|
||||
}
|
||||
}
|
||||
if (metaObject.hasSetter("phoneHash")) {
|
||||
Object phone = getFieldValByName("phone", metaObject);
|
||||
if (phone != null) {
|
||||
setFieldValByName("phoneHash", PhoneCrypto.current().index(String.valueOf(phone)), metaObject);
|
||||
}
|
||||
}
|
||||
if (metaObject.hasSetter("contactPhoneHash")) {
|
||||
Object contactPhone = getFieldValByName("contactPhone", metaObject);
|
||||
if (contactPhone != null) {
|
||||
setFieldValByName("contactPhoneHash", PhoneCrypto.current().index(String.valueOf(contactPhone)), metaObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 手机号加密配置。密钥口径与 JC-Salon-Core 完全一致,保证两条业务线的 phone_hash 可比对。
|
||||
* 配置位置:Nacos jayucloud-artlist / DEFAULT_GROUP / secret.yaml。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jayucloud-artlist.privacy.phone-crypto")
|
||||
public class PhoneCryptoProperties {
|
||||
private String encryptionKey;
|
||||
private String indexKey;
|
||||
}
|
||||
+10
@@ -28,6 +28,16 @@ public class RateLimitProperties {
|
||||
|
||||
private LimitRule orderCreate = new LimitRule(10, 60);
|
||||
|
||||
/**
|
||||
* 联系方式查询:按登录用户维度。
|
||||
*/
|
||||
private LimitRule contactInfoRead = new LimitRule(30, 60);
|
||||
|
||||
/**
|
||||
* 单次拨号取号:按登录用户维度。
|
||||
*/
|
||||
private LimitRule contactDial = new LimitRule(10, 60);
|
||||
|
||||
@Data
|
||||
/**
|
||||
* Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role.
|
||||
|
||||
+11
-8
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.artlist.core.modules.auth.service.impl;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
@@ -51,6 +52,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
* Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final MessageHubClientService messageHubClientService;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Override
|
||||
/**
|
||||
@@ -94,15 +96,16 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
public void sendVerificationCode(String phone, String sceneCode) {
|
||||
String code = generateVerificationCode();
|
||||
|
||||
String codeKey = CODE_PREFIX + phone;
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phone;
|
||||
String phoneKey = phoneCrypto.index(phone);
|
||||
String codeKey = CODE_PREFIX + phoneKey;
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phoneKey;
|
||||
|
||||
redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES));
|
||||
redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()),
|
||||
Duration.ofSeconds(RESEND_INTERVAL_SECONDS));
|
||||
|
||||
messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code);
|
||||
log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode);
|
||||
log.info("验证码已发送,手机号: {}, sceneCode: {}", phoneCrypto.mask(phone), sceneCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -114,21 +117,21 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
* @return boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public boolean verifyCode(String phone, String code) {
|
||||
String codeKey = CODE_PREFIX + phone;
|
||||
String codeKey = CODE_PREFIX + phoneCrypto.index(phone);
|
||||
String storedCode = redisTemplate.opsForValue().get(codeKey);
|
||||
|
||||
if (storedCode == null) {
|
||||
log.warn("验证码不存在或已过期,手机号: {}", phone);
|
||||
log.warn("验证码不存在或已过期,手机号: {}", phoneCrypto.mask(phone));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!storedCode.equals(code)) {
|
||||
log.warn("验证码错误,手机号: {}", phone);
|
||||
log.warn("验证码错误,手机号: {}", phoneCrypto.mask(phone));
|
||||
return false;
|
||||
}
|
||||
|
||||
redisTemplate.delete(codeKey);
|
||||
log.info("验证码验证成功,手机号: {}", phone);
|
||||
log.info("验证码验证成功,手机号: {}", phoneCrypto.mask(phone));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -140,7 +143,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
* @return boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public boolean canResend(String phone) {
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phone;
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phoneCrypto.index(phone);
|
||||
String sendTime = redisTemplate.opsForValue().get(sendTimeKey);
|
||||
return sendTime == null;
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,4 +1,4 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.content.service.impl;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
@@ -489,7 +489,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) {
|
||||
UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId());
|
||||
if (user != null) {
|
||||
commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount());
|
||||
commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname()
|
||||
: SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY));
|
||||
}
|
||||
ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId());
|
||||
if (shop != null) {
|
||||
|
||||
+3
-1
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.MessageHub
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubPushConfigService;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
@@ -51,6 +52,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
* 平台品牌文案配置。
|
||||
*/
|
||||
private final BrandProperties brandProperties;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Value("${messagehub.client.sms-queue:smsQueue}")
|
||||
/**
|
||||
@@ -123,7 +125,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
String queueName = config == null ? smsQueue : config.getQueueName();
|
||||
rabbitTemplate.convertAndSend(queueName, message);
|
||||
log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}",
|
||||
sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
|
||||
sceneCode, phoneCrypto.mask(phone), queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
|
||||
} catch (Exception exception) {
|
||||
log.error("发送短信验证码失败", exception);
|
||||
throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception);
|
||||
|
||||
+3
-1
@@ -24,6 +24,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.WechatMiniLogi
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -87,6 +88,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
* Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Override
|
||||
/**
|
||||
@@ -350,7 +352,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
}
|
||||
return userMapper.selectOne(
|
||||
new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getPhone, phone)
|
||||
.eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.message.service.impl;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
@@ -212,7 +212,7 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO();
|
||||
vo.setId(user.getId());
|
||||
vo.setNickname(user.getNickname());
|
||||
vo.setAccount(user.getAccount());
|
||||
vo.setAccount(SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.ADMIN_LIST));
|
||||
vo.setShopId(user.getShopId());
|
||||
vo.setShopName(shopNameMap.get(user.getShopId()));
|
||||
vo.setType(user.getType());
|
||||
@@ -498,6 +498,8 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
* @return private String result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private String resolvePublisherName(UserDO currentUser) {
|
||||
return StringUtils.hasText(currentUser.getNickname()) ? currentUser.getNickname() : currentUser.getAccount();
|
||||
return StringUtils.hasText(currentUser.getNickname())
|
||||
? currentUser.getNickname()
|
||||
: SensitiveFieldPolicy.account(currentUser.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.message.service.impl;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
@@ -267,7 +267,7 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO();
|
||||
vo.setId(user.getId());
|
||||
vo.setNickname(user.getNickname());
|
||||
vo.setAccount(user.getAccount());
|
||||
vo.setAccount(SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.ADMIN_LIST));
|
||||
vo.setShopId(user.getShopId());
|
||||
vo.setShopName(shopNameMap.get(user.getShopId()));
|
||||
vo.setType(user.getType());
|
||||
@@ -881,6 +881,6 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
if (StringUtils.hasText(currentUser.getNickname())) {
|
||||
return currentUser.getNickname();
|
||||
}
|
||||
return currentUser.getAccount();
|
||||
return SensitiveFieldPolicy.account(currentUser.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -48,6 +48,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.artist.support.BookableArtist
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStateMachine;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistCalendarAppointmentVO;
|
||||
@@ -3733,7 +3734,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
return customer.getNickname();
|
||||
}
|
||||
if (StringUtils.hasText(customer.getAccount())) {
|
||||
return customer.getAccount();
|
||||
return SensitiveFieldPolicy.account(customer.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY);
|
||||
}
|
||||
return "用户";
|
||||
}
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.security.entity.SecurityAudit
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.SecurityAuditLogMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
|
||||
import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.vo.SecurityAuditLogVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -38,7 +39,7 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
|
||||
try {
|
||||
SecurityAuditLogDO log = new SecurityAuditLogDO();
|
||||
log.setUserId(userId);
|
||||
log.setAccount(limit(account, 80));
|
||||
log.setAccount(limit(SensitiveFieldPolicy.account(account, SensitiveFieldPolicy.Scenario.LOG), 80));
|
||||
log.setAction(limit(action, 80));
|
||||
log.setResult(limit(result, 20));
|
||||
log.setReason(limit(reason, 500));
|
||||
|
||||
+67
-4
@@ -1,8 +1,15 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.artlist.core.common.Result;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactDialService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialScene;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -20,6 +27,18 @@ public class ContactInfoController {
|
||||
* Variable `contactInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ContactInfoService contactInfoService;
|
||||
/**
|
||||
* Variable `contactDialService`: resolves a one-time dial number after scene authorization.
|
||||
*/
|
||||
private final ContactDialService contactDialService;
|
||||
/**
|
||||
* Variable `requestThrottleService`: per-user throttling for all contact endpoints.
|
||||
*/
|
||||
private final RequestThrottleService requestThrottleService;
|
||||
/**
|
||||
* Variable `securityAuditLogService`: records who dialed which scene and the result, without the number.
|
||||
*/
|
||||
private final SecurityAuditLogService securityAuditLogService;
|
||||
|
||||
@GetMapping("/shop/{shopId}/manager")
|
||||
/**
|
||||
@@ -30,7 +49,8 @@ public class ContactInfoController {
|
||||
* @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<ContactInfoVO> shopManager(HttpServletRequest request, @PathVariable Long shopId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Long userId = requireLogin(request);
|
||||
requestThrottleService.checkContactInfoRead(request, userId);
|
||||
return Result.success(contactInfoService.getShopManagerContact(userId, shopId));
|
||||
}
|
||||
|
||||
@@ -44,7 +64,8 @@ public class ContactInfoController {
|
||||
* @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<ContactInfoVO> productArtist(HttpServletRequest request, @PathVariable Long productId, @PathVariable Long artistId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Long userId = requireLogin(request);
|
||||
requestThrottleService.checkContactInfoRead(request, userId);
|
||||
return Result.success(contactInfoService.getProductArtistContact(userId, productId, artistId));
|
||||
}
|
||||
|
||||
@@ -54,7 +75,8 @@ public class ContactInfoController {
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<ContactInfoVO> orderArtist(HttpServletRequest request, @PathVariable Long orderId, @RequestParam(required = false) Long artistId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Long userId = requireLogin(request);
|
||||
requestThrottleService.checkContactInfoRead(request, userId);
|
||||
return Result.success(contactInfoService.getOrderArtistContact(userId, orderId, artistId));
|
||||
}
|
||||
|
||||
@@ -62,9 +84,50 @@ public class ContactInfoController {
|
||||
/**
|
||||
* Run business method `platform`.
|
||||
* 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
|
||||
* @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<ContactInfoVO> platform() {
|
||||
public Result<ContactInfoVO> platform(HttpServletRequest request) {
|
||||
Long userId = requireLogin(request);
|
||||
requestThrottleService.checkContactInfoRead(request, userId);
|
||||
return Result.success(contactInfoService.getPlatformContact());
|
||||
}
|
||||
|
||||
@PostMapping("/dial")
|
||||
/**
|
||||
* 单次拨号取号:按场景校验可见范围后返回一次可用号码,号码不落库、不进日志、不进缓存。
|
||||
*/
|
||||
public Result<DialResponseVO> dial(HttpServletRequest request, @RequestBody DialRequestDTO dialRequestDTO) {
|
||||
Long userId = requireLogin(request);
|
||||
String account = (String) request.getAttribute("account");
|
||||
requestThrottleService.checkContactDial(request, userId);
|
||||
String action = "CONTACT_DIAL_" + safeSceneCode(dialRequestDTO);
|
||||
try {
|
||||
DialResponseVO response = contactDialService.dial(userId, dialRequestDTO);
|
||||
securityAuditLogService.record(userId, account, action, "SUCCESS", null, request);
|
||||
return Result.success(response);
|
||||
} catch (BusinessException exception) {
|
||||
securityAuditLogService.record(userId, account, action, "FAIL", "code=" + exception.getCode(), request);
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
private Long requireLogin(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
if (userId == null) {
|
||||
throw new BusinessException(403, "请先登录后再获取联系方式");
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
|
||||
private String safeSceneCode(DialRequestDTO dialRequestDTO) {
|
||||
if (dialRequestDTO == null || dialRequestDTO.getScene() == null) {
|
||||
return "UNKNOWN";
|
||||
}
|
||||
try {
|
||||
return DialScene.fromCode(dialRequestDTO.getScene()).name();
|
||||
} catch (BusinessException exception) {
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 单次拨号取号请求。
|
||||
*/
|
||||
@Data
|
||||
public class DialRequestDTO {
|
||||
|
||||
/**
|
||||
* 拨号场景:SHOP_MANAGER / ORDER_ARTIST / PRODUCT_ARTIST / PLATFORM。
|
||||
*/
|
||||
private String scene;
|
||||
|
||||
/**
|
||||
* 目标标识:SHOP_MANAGER=店铺ID,ORDER_ARTIST=订单ID,PRODUCT_ARTIST=作品ID,PLATFORM 忽略。
|
||||
*/
|
||||
private Long targetId;
|
||||
|
||||
/**
|
||||
* 可选的美甲师ID,仅 PRODUCT_ARTIST 场景使用;不传时取作品可预约美甲师的第一位。
|
||||
*/
|
||||
private Long artistId;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.service;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
|
||||
|
||||
/**
|
||||
* 单次拨号取号服务:按场景校验可见范围后返回一次可用的拨号号码。
|
||||
*/
|
||||
public interface ContactDialService {
|
||||
|
||||
/**
|
||||
* 按场景解析并返回拨号号码;号码不落库、不进日志、不进缓存。
|
||||
*/
|
||||
DialResponseVO dial(Long userId, DialRequestDTO request);
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.artlist.core.config.DialProperties;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactDialService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialScene;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialTargetProvider;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
/**
|
||||
* 单次拨号取号实现:先按场景校验可见范围,再由配置的提供方生成拨号号码。
|
||||
*/
|
||||
public class ContactDialServiceImpl implements ContactDialService {
|
||||
|
||||
private static final int FORBIDDEN = 403;
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
private final DialProperties dialProperties;
|
||||
private final List<DialTargetProvider> dialTargetProviders;
|
||||
|
||||
@Override
|
||||
public DialResponseVO dial(Long userId, DialRequestDTO request) {
|
||||
if (userId == null) {
|
||||
throw new BusinessException(FORBIDDEN, "请先登录后再获取联系方式");
|
||||
}
|
||||
DialScene scene = DialScene.fromCode(request == null ? null : request.getScene());
|
||||
UserDO caller = userMapper.selectById(userId);
|
||||
if (caller == null || Integer.valueOf(1).equals(caller.getIsDelete())) {
|
||||
throw new BusinessException(FORBIDDEN, "用户不存在或已失效");
|
||||
}
|
||||
|
||||
String rawPhone = switch (scene) {
|
||||
case SHOP_MANAGER -> resolveShopManagerPhone(caller, request.getTargetId());
|
||||
case ORDER_ARTIST -> resolveOrderArtistPhone(caller, request.getTargetId());
|
||||
case PRODUCT_ARTIST -> resolveProductArtistPhone(request.getTargetId(), request.getArtistId());
|
||||
case PLATFORM -> resolvePlatformPhone();
|
||||
};
|
||||
if (!StringUtils.hasText(rawPhone)) {
|
||||
throw new BusinessException(404, "该联系人暂未配置可拨打电话");
|
||||
}
|
||||
|
||||
DialTargetProvider provider = selectProvider();
|
||||
return provider.resolve(rawPhone);
|
||||
}
|
||||
|
||||
private String resolveShopManagerPhone(UserDO caller, Long shopId) {
|
||||
if (shopId == null || shopId <= 0) {
|
||||
throw new BusinessException(400, "店铺ID不能为空");
|
||||
}
|
||||
ensureShopVisible(caller, shopId);
|
||||
UserDO manager = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getType, 2)
|
||||
.eq(UserDO::getShopId, shopId)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.eq(UserDO::getStatus, 1)
|
||||
.last("LIMIT 1"));
|
||||
return resolveContactPhone(manager);
|
||||
}
|
||||
|
||||
private String resolveOrderArtistPhone(UserDO caller, Long orderId) {
|
||||
if (orderId == null || orderId <= 0) {
|
||||
throw new BusinessException(400, "订单ID不能为空");
|
||||
}
|
||||
OrderDO order = orderMapper.selectById(orderId);
|
||||
if (order == null
|
||||
|| Integer.valueOf(1).equals(order.getIsDelete())
|
||||
|| !caller.getId().equals(order.getUserId())) {
|
||||
throw new BusinessException(FORBIDDEN, "订单不存在或无权查看");
|
||||
}
|
||||
OrderItemDO item = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
|
||||
.eq(OrderItemDO::getOrderId, orderId)
|
||||
.eq(OrderItemDO::getIsDelete, 0)
|
||||
.isNotNull(OrderItemDO::getArtistId)
|
||||
.last("LIMIT 1"))
|
||||
.stream()
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new BusinessException(404, "订单暂无可联系美甲师"));
|
||||
return resolveContactPhone(userMapper.selectById(item.getArtistId()));
|
||||
}
|
||||
|
||||
private String resolveProductArtistPhone(Long productId, Long artistId) {
|
||||
if (productId == null || productId <= 0) {
|
||||
throw new BusinessException(400, "作品ID不能为空");
|
||||
}
|
||||
ProductDO product = productMapper.selectById(productId);
|
||||
if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) {
|
||||
throw new BusinessException(FORBIDDEN, "作品不存在或不可见");
|
||||
}
|
||||
Long targetArtistId = artistId;
|
||||
if (targetArtistId == null || targetArtistId <= 0) {
|
||||
targetArtistId = firstBookableArtistId(product.getBookableArtists());
|
||||
}
|
||||
if (targetArtistId == null) {
|
||||
throw new BusinessException(404, "该作品暂未配置可联系美甲师");
|
||||
}
|
||||
ensureArtistAllowed(product.getBookableArtists(), targetArtistId);
|
||||
return resolveContactPhone(userMapper.selectById(targetArtistId));
|
||||
}
|
||||
|
||||
private String resolvePlatformPhone() {
|
||||
UserDO admin = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getType, 4)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.eq(UserDO::getStatus, 1)
|
||||
.isNotNull(UserDO::getPhone)
|
||||
.last("LIMIT 1"));
|
||||
return resolveContactPhone(admin);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验当前用户是否可拨打该店铺店长:平台管理员、本店用户、有绑定关系或门店公开可见。
|
||||
*/
|
||||
private void ensureShopVisible(UserDO caller, Long shopId) {
|
||||
if (Integer.valueOf(4).equals(caller.getType())) {
|
||||
return;
|
||||
}
|
||||
if (shopId.equals(caller.getShopId()) || userShopBindingSupport.hasActiveBinding(caller.getId(), shopId)) {
|
||||
return;
|
||||
}
|
||||
ShopDO shop = shopMapper.selectById(shopId);
|
||||
if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) {
|
||||
throw new BusinessException(FORBIDDEN, "店铺不存在或不可见");
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureArtistAllowed(String rawBookableArtists, Long artistId) {
|
||||
if (!StringUtils.hasText(rawBookableArtists)) {
|
||||
return;
|
||||
}
|
||||
boolean allowed = Arrays.stream(rawBookableArtists.split(","))
|
||||
.map(String::trim)
|
||||
.filter(StringUtils::hasText)
|
||||
.anyMatch(id -> id.equals(String.valueOf(artistId)));
|
||||
if (!allowed) {
|
||||
throw new BusinessException(FORBIDDEN, "该美甲师不可联系当前作品");
|
||||
}
|
||||
}
|
||||
|
||||
private Long firstBookableArtistId(String rawBookableArtists) {
|
||||
if (!StringUtils.hasText(rawBookableArtists)) {
|
||||
return null;
|
||||
}
|
||||
return Arrays.stream(rawBookableArtists.split(","))
|
||||
.map(String::trim)
|
||||
.filter(StringUtils::hasText)
|
||||
.map(value -> {
|
||||
try {
|
||||
return Long.valueOf(value);
|
||||
} catch (NumberFormatException exception) {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private String resolveContactPhone(UserDO contact) {
|
||||
if (contact == null || Integer.valueOf(1).equals(contact.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return StringUtils.hasText(contact.getContactPhone()) ? contact.getContactPhone() : contact.getPhone();
|
||||
}
|
||||
|
||||
private DialTargetProvider selectProvider() {
|
||||
String configured = StringUtils.hasText(dialProperties.getProvider())
|
||||
? dialProperties.getProvider().trim()
|
||||
: "direct";
|
||||
return dialTargetProviders.stream()
|
||||
.filter(provider -> provider.name().equalsIgnoreCase(configured))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new BusinessException(9002, "拨号号码提供方配置无效"));
|
||||
}
|
||||
}
|
||||
+27
-6
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
|
||||
@@ -8,11 +9,13 @@ import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -40,6 +43,10 @@ public class ContactInfoServiceImpl implements ContactInfoService {
|
||||
* Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
/**
|
||||
* Variable `shopMapper`: used to verify the target shop is visible before exposing contact actions.
|
||||
*/
|
||||
private final com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper shopMapper;
|
||||
/**
|
||||
* Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
@@ -160,11 +167,23 @@ public class ContactInfoServiceImpl implements ContactInfoService {
|
||||
* @return private void result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private void ensureUserCanSeeShop(Long userId, Long shopId) {
|
||||
if (userId == null) return;
|
||||
if (userId == null) {
|
||||
throw new BusinessException(403, "请先登录后再获取联系方式");
|
||||
}
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
if (user != null && shopId.equals(user.getShopId())) return;
|
||||
if (!userShopBindingSupport.hasActiveBinding(userId, shopId)) {
|
||||
// 店铺详情是公开入口,未绑定用户仍允许看联系方式。
|
||||
if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) {
|
||||
throw new BusinessException(403, "用户不存在或已失效");
|
||||
}
|
||||
if (Integer.valueOf(4).equals(user.getType())) {
|
||||
return;
|
||||
}
|
||||
if (shopId.equals(user.getShopId()) || userShopBindingSupport.hasActiveBinding(userId, shopId)) {
|
||||
return;
|
||||
}
|
||||
// 普通用户仅可查看未删除的门店,与公开店铺详情可见范围一致。
|
||||
ShopDO shop = shopMapper.selectById(shopId);
|
||||
if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) {
|
||||
throw new BusinessException(403, "店铺不存在或不可见");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,9 +221,11 @@ public class ContactInfoServiceImpl implements ContactInfoService {
|
||||
return vo;
|
||||
}
|
||||
vo.setContactUserId(user.getId());
|
||||
vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount());
|
||||
vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname()
|
||||
: SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY));
|
||||
String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone();
|
||||
vo.setPhone(contactPhone);
|
||||
// 全场景脱敏:联系信息接口不再返回号码,真实号码只通过 /contact-info/dial 单次取号。
|
||||
vo.setPhone(null);
|
||||
vo.setPhoneAvailable(StringUtils.hasText(contactPhone));
|
||||
vo.setWechatId(user.getWechatId());
|
||||
vo.setWechatAvailable(StringUtils.hasText(user.getWechatId()));
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 拨号场景及其入参含义。
|
||||
*/
|
||||
public enum DialScene {
|
||||
|
||||
/**
|
||||
* 店铺店长:targetId 为店铺ID。
|
||||
*/
|
||||
SHOP_MANAGER,
|
||||
/**
|
||||
* 订单美甲师:targetId 为订单ID。
|
||||
*/
|
||||
ORDER_ARTIST,
|
||||
/**
|
||||
* 作品美甲师:targetId 为作品ID,可选 artistId 指定美甲师。
|
||||
*/
|
||||
PRODUCT_ARTIST,
|
||||
/**
|
||||
* 平台客服:targetId 忽略。
|
||||
*/
|
||||
PLATFORM;
|
||||
|
||||
/**
|
||||
* 解析前端传入的场景值。
|
||||
*/
|
||||
public static DialScene fromCode(String code) {
|
||||
if (!StringUtils.hasText(code)) {
|
||||
throw new BusinessException(400, "拨号场景不能为空");
|
||||
}
|
||||
try {
|
||||
return DialScene.valueOf(code.trim().toUpperCase());
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new BusinessException(400, "不支持的拨号场景");
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
|
||||
|
||||
/**
|
||||
* 拨号号码提供方:直拨真实号码或隐私号。
|
||||
*/
|
||||
public interface DialTargetProvider {
|
||||
|
||||
/**
|
||||
* 配置值标识,与 jayucloud-artlist.dial.provider 对应。
|
||||
*/
|
||||
String name();
|
||||
|
||||
/**
|
||||
* 将已通过授权校验的真实号码转换为拨号响应。
|
||||
*/
|
||||
DialResponseVO resolve(String rawPhone);
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 直拨真实号码的提供方。
|
||||
*/
|
||||
@Component
|
||||
public class DirectDialTargetProvider implements DialTargetProvider {
|
||||
|
||||
/**
|
||||
* 直拨号码的有效提示时长,仅用于前端控制展示,不做服务端缓存。
|
||||
*/
|
||||
private static final int EXPIRES_IN_SECONDS = 300;
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "direct";
|
||||
}
|
||||
|
||||
@Override
|
||||
public DialResponseVO resolve(String rawPhone) {
|
||||
DialResponseVO vo = new DialResponseVO();
|
||||
vo.setMode("DIRECT");
|
||||
vo.setDialNumber(rawPhone);
|
||||
vo.setExpiresInSeconds(EXPIRES_IN_SECONDS);
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 隐私号提供方占位实现:未对接隐私号平台时明确报错,绝不回退成真实号码。
|
||||
*/
|
||||
@Component
|
||||
public class PlaceholderPrivacyNumberProvider implements DialTargetProvider {
|
||||
|
||||
/**
|
||||
* 隐私号未配置的业务码。
|
||||
*/
|
||||
public static final int NOT_CONFIGURED_CODE = 9001;
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "privacy-number";
|
||||
}
|
||||
|
||||
@Override
|
||||
public DialResponseVO resolve(String rawPhone) {
|
||||
throw new BusinessException(NOT_CONFIGURED_CODE, "隐私号码服务未配置,暂时无法拨号");
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 单次拨号取号响应。号码本身不进审计、日志与缓存。
|
||||
*/
|
||||
@Data
|
||||
public class DialResponseVO {
|
||||
|
||||
/**
|
||||
* 拨号模式:DIRECT=直拨真实号码,PRIVACY_NUMBER=隐私号码。
|
||||
*/
|
||||
private String mode;
|
||||
|
||||
/**
|
||||
* 拨号号码;PRIVACY_NUMBER 未对接时不会返回真实号码。
|
||||
*/
|
||||
private String dialNumber;
|
||||
|
||||
/**
|
||||
* 本次号码的有效时长(秒),供前端控制缓存时间。
|
||||
*/
|
||||
private Integer expiresInSeconds;
|
||||
}
|
||||
+45
-7
@@ -38,6 +38,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.service.ShopRoleService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniAuthService;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.system.service.LegalAgreementService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
@@ -89,6 +90,7 @@ public class UserController {
|
||||
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final UserService userService;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
/**
|
||||
* Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
@@ -138,6 +140,10 @@ public class UserController {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final LegalAgreementService legalAgreementService;
|
||||
/**
|
||||
* Variable `jwtUtil`: resolves the optional logged-in user on endpoints excluded from authentication.
|
||||
*/
|
||||
private final com.xiaowang.jayucloud.artlist.core.utils.JwtUtil jwtUtil;
|
||||
/**
|
||||
* Purpose: securityAuditLogService supports UserController.java by holding or executing the security audit log service business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
@@ -359,7 +365,7 @@ public class UserController {
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount))
|
||||
);
|
||||
boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete());
|
||||
String message = available ? "账号可用" : "账号已被注册";
|
||||
@@ -377,7 +383,7 @@ public class UserController {
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
@@ -421,7 +427,7 @@ public class UserController {
|
||||
public Result<AvailabilityVO> checkPhoneAvailability(@PathVariable String phone) {
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, phone)
|
||||
.eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
boolean available = userDO == null;
|
||||
@@ -550,7 +556,7 @@ public class UserController {
|
||||
boolean success = userService.register(registerRequestDTO);
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()))
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
@@ -597,8 +603,9 @@ public class UserController {
|
||||
@PostMapping("/send-verification-code")
|
||||
@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())) {
|
||||
String phone = resolveSendCodePhone(request, sendVerificationCodeRequestDTO);
|
||||
requestThrottleService.checkSendCode(request, phone);
|
||||
if (!verificationCodeService.canResend(phone)) {
|
||||
/**
|
||||
* 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.
|
||||
@@ -607,10 +614,41 @@ public class UserController {
|
||||
*/
|
||||
throw new RuntimeException("验证码发送过于频繁,请1分钟后再试");
|
||||
}
|
||||
verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone(), sendVerificationCodeRequestDTO.getSceneCode());
|
||||
verificationCodeService.sendVerificationCode(phone, sendVerificationCodeRequestDTO.getSceneCode());
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改密码等"发给自己"的验证码场景:号码由服务端按当前登录用户取,客户端传参忽略。
|
||||
*/
|
||||
private String resolveSendCodePhone(HttpServletRequest request, SendVerificationCodeRequestDTO dto) {
|
||||
String sceneCode = dto.getSceneCode();
|
||||
if (!"USER_CHANGE_PASSWORD_SMS_CODE".equals(sceneCode)) {
|
||||
return dto.getPhone();
|
||||
}
|
||||
Long userId = resolveOptionalUserId(request);
|
||||
if (userId == null) {
|
||||
return dto.getPhone();
|
||||
}
|
||||
return userService.getBoundPhone(userId);
|
||||
}
|
||||
|
||||
private Long resolveOptionalUserId(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
if (userId != null) {
|
||||
return userId;
|
||||
}
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (authorization == null || !authorization.startsWith("Bearer ")) {
|
||||
return null;
|
||||
}
|
||||
String token = authorization.substring("Bearer ".length()).trim();
|
||||
if (!jwtUtil.validateToken(token) || !jwtUtil.isAccessToken(token)) {
|
||||
return null;
|
||||
}
|
||||
return jwtUtil.getUserIdFromToken(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过手机号验证码重置密码
|
||||
*
|
||||
|
||||
+27
-7
@@ -12,6 +12,8 @@ import lombok.EqualsAndHashCode;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.AccountPhoneTypeHandler;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneEncryptionTypeHandler;
|
||||
/**
|
||||
* 系统用户信息表 DO
|
||||
* 对应数据库表 t_user
|
||||
@@ -22,7 +24,7 @@ import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity;
|
||||
@Getter
|
||||
@Setter
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_user")
|
||||
@TableName(value = "t_user", autoResultMap = true)
|
||||
public class UserDO extends BaseEntity {
|
||||
|
||||
/**
|
||||
@@ -44,23 +46,41 @@ public class UserDO extends BaseEntity {
|
||||
private String nickname;
|
||||
|
||||
/**
|
||||
* 用户账号(登录用)
|
||||
* 用户账号(登录用,AES-GCM 密文,落库列 account;实体中保持明文,便于业务使用)
|
||||
*/
|
||||
@TableField("account")
|
||||
@TableField(value = "account", typeHandler = AccountPhoneTypeHandler.class)
|
||||
private String account;
|
||||
|
||||
/**
|
||||
* 手机号
|
||||
* 账号哈希(HMAC-SHA256,十六进制小写),所有账号等值查询统一使用
|
||||
*/
|
||||
@TableField("phone")
|
||||
@TableField("account_hash")
|
||||
private String accountHash;
|
||||
|
||||
/**
|
||||
* 手机号(AES-GCM 密文,落库列 phone_cipher;实体中保持明文,便于业务使用)
|
||||
*/
|
||||
@TableField(value = "phone_cipher", typeHandler = PhoneEncryptionTypeHandler.class)
|
||||
private String phone;
|
||||
|
||||
/**
|
||||
* 联系电话
|
||||
* 手机号哈希(HMAC-SHA256,十六进制小写),用于等值查询与唯一去重
|
||||
*/
|
||||
@TableField("contact_phone")
|
||||
@TableField("phone_hash")
|
||||
private String phoneHash;
|
||||
|
||||
/**
|
||||
* 联系电话(AES-GCM 密文,落库列 contact_phone_cipher;实体中保持明文)
|
||||
*/
|
||||
@TableField(value = "contact_phone_cipher", typeHandler = PhoneEncryptionTypeHandler.class)
|
||||
private String contactPhone;
|
||||
|
||||
/**
|
||||
* 联系电话哈希(HMAC-SHA256,十六进制小写),用于等值查询
|
||||
*/
|
||||
@TableField("contact_phone_hash")
|
||||
private String contactPhoneHash;
|
||||
|
||||
/**
|
||||
* 生日
|
||||
*/
|
||||
|
||||
+5
@@ -394,4 +394,9 @@ public interface UserService extends IService<UserDO> {
|
||||
* @return boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO);
|
||||
|
||||
/**
|
||||
* 获取当前登录用户已绑定的手机号(明文,仅用于服务端发码,不返回前端)。
|
||||
*/
|
||||
String getBoundPhone(Long userId);
|
||||
}
|
||||
|
||||
+83
-83
@@ -6,6 +6,7 @@ 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.xiaowang.jayucloud.artlist.core.config.BrandProperties;
|
||||
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.artlist.core.common.dto.*;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.*;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.*;
|
||||
@@ -48,6 +49,8 @@ import com.xiaowang.jayucloud.artlist.core.modules.system.support.AdminDefaultPa
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionCatalog;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.security.UserSessionService;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionPolicy;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext;
|
||||
@@ -118,10 +121,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
|
||||
private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5);
|
||||
/**
|
||||
* Purpose: DELETED_PHONE_MARKER supports UserServiceImpl.java by holding or executing the deleted phone marker business role.
|
||||
* Purpose: DELETED_ACCOUNT_MARKER supports UserServiceImpl.java by holding or executing the deleted account marker business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private static final String DELETED_PHONE_MARKER = "_deleted_";
|
||||
private static final String DELETED_ACCOUNT_MARKER = "_deleted_";
|
||||
/**
|
||||
* Purpose: LOGIN_FAIL_KEY_PREFIX supports UserServiceImpl.java by holding or executing the login fail key prefix business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
@@ -170,6 +173,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
private final UserInviteCodeMapper userInviteCodeMapper;
|
||||
private final BrandProperties brandProperties;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
/**
|
||||
* Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
@@ -369,7 +373,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
// 检查账号是否已存在
|
||||
UserDO existingUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, validatedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(validatedAccount))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
if (existingUser != null) {
|
||||
@@ -534,7 +538,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) {
|
||||
UserDO existingUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
if (existingUser != null) {
|
||||
@@ -653,19 +657,34 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now())
|
||||
);
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
String deletedAccount = buildDeletedAccount(userDO);
|
||||
return userMapper.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<UserDO>()
|
||||
.eq(UserDO::getId, id)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.set(UserDO::getAccount, buildDeletedAccount(userDO))
|
||||
.set(UserDO::getPhone, buildDeletedPhone(userDO))
|
||||
.set(UserDO::getStatus, 0)
|
||||
.set(UserDO::getIsDelete, 1)
|
||||
.set(UserDO::getUpdateTime, now)
|
||||
buildSoftDeleteUpdate(id,
|
||||
phoneCrypto.encryptAccount(deletedAccount),
|
||||
phoneCrypto.index(deletedAccount),
|
||||
now)
|
||||
) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造账号注销更新条件:账号改为占位值,手机号/联系电话的密文与哈希一并清空,避免数据残留。
|
||||
*/
|
||||
static LambdaUpdateWrapper<UserDO> buildSoftDeleteUpdate(Long id, String encryptedAccount, String accountHash, LocalDateTime now) {
|
||||
return new LambdaUpdateWrapper<UserDO>()
|
||||
.eq(UserDO::getId, id)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.set(UserDO::getAccount, encryptedAccount)
|
||||
.set(UserDO::getAccountHash, accountHash)
|
||||
.set(UserDO::getPhone, null)
|
||||
.set(UserDO::getPhoneHash, null)
|
||||
.set(UserDO::getContactPhone, null)
|
||||
.set(UserDO::getContactPhoneHash, null)
|
||||
.set(UserDO::getStatus, 0)
|
||||
.set(UserDO::getIsDelete, 1)
|
||||
.set(UserDO::getUpdateTime, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID获取用户信息
|
||||
* @param id 用户ID
|
||||
@@ -683,7 +702,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @param userDO parameter `userDO` supplied by the caller
|
||||
* @return return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
return convertToVO(userDO);
|
||||
return convertToVO(userDO, SensitiveFieldPolicy.Scenario.SELF_PROFILE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -697,7 +716,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
return userDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -718,7 +737,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.in(UserDO::getId, userIds)
|
||||
);
|
||||
return userDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -735,7 +754,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.eq(UserDO::getType, type)
|
||||
);
|
||||
return userDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -749,7 +768,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
@@ -761,7 +780,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @param userDO parameter `userDO` supplied by the caller
|
||||
* @return return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
return convertToVO(userDO);
|
||||
return convertToVO(userDO, SensitiveFieldPolicy.Scenario.SELF_PROFILE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -770,7 +789,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @param userDO 用户DO
|
||||
* @return 用户VO
|
||||
*/
|
||||
private UserVO convertToVO(UserDO userDO) {
|
||||
private UserVO convertToVO(UserDO userDO, SensitiveFieldPolicy.Scenario scenario) {
|
||||
UserVO userVO = new UserVO();
|
||||
userVO.setId(userDO.getId());
|
||||
List<ShopSimpleVO> shopOptions = resolveShopOptions(userDO, true, false);
|
||||
@@ -791,9 +810,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList()));
|
||||
userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList()));
|
||||
userVO.setNickname(userDO.getNickname());
|
||||
userVO.setAccount(userDO.getAccount());
|
||||
userVO.setPhone(userDO.getPhone());
|
||||
userVO.setContactPhone(userDO.getContactPhone());
|
||||
userVO.setAccount(SensitiveFieldPolicy.account(userDO.getAccount(), scenario));
|
||||
userVO.setPhone(SensitiveFieldPolicy.phone(userDO.getPhone(), scenario));
|
||||
userVO.setContactPhone(SensitiveFieldPolicy.phone(userDO.getContactPhone(), scenario));
|
||||
userVO.setBirthday(userDO.getBirthday());
|
||||
userVO.setWechatId(userDO.getWechatId());
|
||||
userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode()));
|
||||
@@ -869,7 +888,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
@@ -919,7 +938,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, normalizedPhone)
|
||||
.eq(UserDO::getPhoneHash, phoneCrypto.index(normalizedPhone))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
@@ -974,7 +993,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
@@ -1022,7 +1041,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount());
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount))
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -1085,7 +1104,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone())
|
||||
.eq(UserDO::getPhoneHash, phoneCrypto.index(phoneLoginRequestDTO.getPhone()))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
|
||||
@@ -1126,7 +1145,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) {
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, phone)
|
||||
.eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
@@ -1239,7 +1258,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount());
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount))
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -1448,7 +1467,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
UserDO existingUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, validatedAccount)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(validatedAccount))
|
||||
);
|
||||
|
||||
if (existingUser != null) {
|
||||
@@ -1471,7 +1490,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
UserDO existingPhoneUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, registerRequestDTO.getPhone())
|
||||
.eq(UserDO::getPhoneHash, phoneCrypto.index(registerRequestDTO.getPhone()))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
|
||||
@@ -1541,7 +1560,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
UserDO existingUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, phone)
|
||||
.eq(UserDO::getAccountHash, phoneCrypto.index(phone))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
@@ -1896,10 +1915,17 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
wrapper.eq(UserDO::getIsDelete, 0);
|
||||
// 不再过滤普通用户,由前端根据用户角色进行过滤
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
wrapper.and(w -> w.like(UserDO::getAccount, keyword)
|
||||
.or().like(UserDO::getNickname, keyword)
|
||||
.or().like(UserDO::getPhone, keyword)
|
||||
.or().like(UserDO::getContactPhone, keyword));
|
||||
String keywordPhoneHash = phoneCrypto.isMobilePhone(keyword) ? phoneCrypto.index(keyword) : null;
|
||||
String keywordAccountHash = phoneCrypto.index(keyword);
|
||||
wrapper.and(w -> {
|
||||
// 账号落库为密文,不能模糊检索,统一走 account_hash 精确匹配
|
||||
w.eq(UserDO::getAccountHash, keywordAccountHash).or().like(UserDO::getNickname, keyword);
|
||||
// 手机号只做精确匹配:密文不可模糊检索,统一走 phone_hash
|
||||
if (keywordPhoneHash != null) {
|
||||
w.or().eq(UserDO::getPhoneHash, keywordPhoneHash)
|
||||
.or().eq(UserDO::getContactPhoneHash, keywordPhoneHash);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (shopId != null && shopId > 0) {
|
||||
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
|
||||
@@ -1951,7 +1977,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
Page<UserDO> userPage = userMapper.selectPage(pageParam, wrapper);
|
||||
|
||||
PageResultVO<UserVO> result = new PageResultVO<>();
|
||||
result.setList(userPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList()));
|
||||
result.setList(userPage.getRecords().stream().map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)).collect(Collectors.toList()));
|
||||
result.setTotal(userPage.getTotal());
|
||||
result.setPage(page);
|
||||
result.setSize(size);
|
||||
@@ -2211,7 +2237,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @return boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) {
|
||||
String oldPhone = updatePhoneDTO.getOldPhone();
|
||||
// 原手机号由服务端按当前登录用户读取,客户端传入的 oldPhone 仅为兼容旧协议,不参与校验。
|
||||
String newPhone = updatePhoneDTO.getNewPhone();
|
||||
String verificationCode = updatePhoneDTO.getVerificationCode();
|
||||
|
||||
@@ -2231,14 +2257,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
throw new RuntimeException("当前账号未绑定手机号");
|
||||
}
|
||||
if (!userDO.getPhone().equals(oldPhone)) {
|
||||
/**
|
||||
* 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("原手机号不匹配");
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `validateVerificationCode`.
|
||||
@@ -2263,6 +2281,19 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* 获取当前登录用户已绑定手机号的明文,仅用于服务端发码。
|
||||
*/
|
||||
public String getBoundPhone(Long userId) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
if (!StringUtils.hasText(userDO.getPhone())) {
|
||||
throw new BusinessException(400, "当前账号未绑定手机号");
|
||||
}
|
||||
return userDO.getPhone();
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Run business method `resetPasswordByPhone`.
|
||||
@@ -2284,9 +2315,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
validateVerificationCode(phone, verificationCode);
|
||||
|
||||
// 根据手机号查找用户
|
||||
// 根据手机号哈希查找用户
|
||||
LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class);
|
||||
wrapper.eq(UserDO::getPhone, phone);
|
||||
wrapper.eq(UserDO::getPhoneHash, phoneCrypto.index(phone));
|
||||
wrapper.eq(UserDO::getIsDelete, 0);
|
||||
UserDO userDO = userMapper.selectOne(wrapper);
|
||||
|
||||
@@ -2334,26 +2365,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @param 50 parameter `50` supplied by the caller
|
||||
* @return return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `buildDeletedPhone`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param userDO parameter `userDO` supplied by the caller
|
||||
* @return private String result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private String buildDeletedPhone(UserDO userDO) {
|
||||
String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString();
|
||||
String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone";
|
||||
/**
|
||||
* Run business method `trimDeletedPlaceholder`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param suffix parameter `suffix` supplied by the caller
|
||||
* @param 50 parameter `50` supplied by the caller
|
||||
* @return return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
|
||||
return trimDeletedPlaceholder(base + DELETED_ACCOUNT_MARKER + suffix, 50);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2499,7 +2511,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @return private String result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private String buildLoginFailKey(String account) {
|
||||
return LOGIN_FAIL_KEY_PREFIX + account.trim();
|
||||
String indexedAccount = StringUtils.hasText(account) ? phoneCrypto.index(account) : null;
|
||||
return LOGIN_FAIL_KEY_PREFIX + (indexedAccount == null ? "anonymous" : indexedAccount);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2969,9 +2982,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (isDeletedPlaceholderPhone(normalizedPhone)) {
|
||||
return normalizedPhone;
|
||||
}
|
||||
if (!normalizedPhone.matches(PHONE_REGEX)) {
|
||||
/**
|
||||
* Run business method `RuntimeException`.
|
||||
@@ -2991,16 +3001,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
return normalizedPhone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `isDeletedPlaceholderPhone`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param phone parameter `phone` supplied by the caller
|
||||
* @return private boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private boolean isDeletedPlaceholderPhone(String phone) {
|
||||
return StringUtils.hasText(phone) && phone.contains(DELETED_PHONE_MARKER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `ensurePhoneNotUsed`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -3010,7 +3010,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
private void ensurePhoneNotUsed(String phone, Long currentUserId) {
|
||||
LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, phone)
|
||||
.eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
|
||||
.eq(UserDO::getIsDelete, 0);
|
||||
if (currentUserId != null) {
|
||||
wrapper.ne(UserDO::getId, currentUserId);
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.support.privacy;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* V5 迁移之后的账号补写:把 account_hash 为空的历史行(如 V1 种子账号 xiaowang)
|
||||
* 加密 account 并回填 account_hash,之后所有账号查询可统一走哈希等值条件。
|
||||
*
|
||||
* <p>只处理无哈希的行,幂等;已处理行不会重复更新。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AccountHashBackfillRunner implements ApplicationRunner {
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
List<UserDO> candidates = userMapper.selectList(Wrappers.<UserDO>lambdaQuery()
|
||||
.isNull(UserDO::getAccountHash)
|
||||
.isNotNull(UserDO::getAccount));
|
||||
if (candidates.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
int updated = 0;
|
||||
for (UserDO user : candidates) {
|
||||
String plainAccount = user.getAccount();
|
||||
if (!StringUtils.hasText(plainAccount)) {
|
||||
continue;
|
||||
}
|
||||
userMapper.update(null, new LambdaUpdateWrapper<UserDO>()
|
||||
.eq(UserDO::getId, user.getId())
|
||||
.set(UserDO::getAccount, phoneCrypto.encryptAccount(plainAccount))
|
||||
.set(UserDO::getAccountHash, phoneCrypto.index(plainAccount)));
|
||||
updated++;
|
||||
}
|
||||
log.info("账号加密回填完成,共处理 {} 条", updated);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.support.privacy;
|
||||
|
||||
import org.apache.ibatis.type.BaseTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* 账号 TypeHandler:写库时一律 AES-GCM 加密,读库时仅解密 enc:v1: 前缀的密文。
|
||||
* 与 JC-Salon-Core 的 AccountPhoneTypeHandler 同名同结构。
|
||||
*/
|
||||
public class AccountPhoneTypeHandler extends BaseTypeHandler<String> {
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException {
|
||||
ps.setString(index, PhoneCrypto.current().encryptAccount(parameter));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||
return PhoneCrypto.current().decryptAccount(rs.getString(columnName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return PhoneCrypto.current().decryptAccount(rs.getString(columnIndex));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||
return PhoneCrypto.current().decryptAccount(cs.getString(columnIndex));
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.support.privacy;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* 手机号加密与索引组件,算法与 JC-Salon-Core 的 PhoneCrypto 逐字对齐:
|
||||
* <ul>
|
||||
* <li>加密:AES/GCM/NoPadding,12 字节随机 IV,128 位 tag,前缀 {@code enc:v1:},载荷为 Base64(IV||密文);</li>
|
||||
* <li>索引:HMAC-SHA256,输入为 {@code value.trim()},输出十六进制小写;</li>
|
||||
* <li>手机号识别:{@code 1[3-9]\d{9}}。</li>
|
||||
* </ul>
|
||||
* 两条线使用同一把 index-key,phone_hash 才可跨线比对;密文因随机 IV 各自独立,不要求可比。
|
||||
*/
|
||||
@Component
|
||||
public class PhoneCrypto {
|
||||
private static final String CIPHER_PREFIX = "enc:v1:";
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private static volatile PhoneCrypto current;
|
||||
|
||||
private final PhoneCryptoProperties properties;
|
||||
private byte[] encryptionKey;
|
||||
private byte[] indexKey;
|
||||
|
||||
public PhoneCrypto(PhoneCryptoProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void initialize() {
|
||||
encryptionKey = decodeKey(properties.getEncryptionKey(), "phone-crypto.encryption-key");
|
||||
indexKey = decodeKey(properties.getIndexKey(), "phone-crypto.index-key");
|
||||
if (encryptionKey.length != 32 || indexKey.length < 32) {
|
||||
throw new IllegalStateException("手机号加密与索引密钥必须分别配置为至少32字节的Base64密钥");
|
||||
}
|
||||
if (Arrays.equals(encryptionKey, indexKey)) {
|
||||
throw new IllegalStateException("手机号加密密钥与索引密钥必须独立");
|
||||
}
|
||||
current = this;
|
||||
}
|
||||
|
||||
public String encrypt(String value) {
|
||||
if (!StringUtils.hasText(value) || value.startsWith(CIPHER_PREFIX)) return value;
|
||||
try {
|
||||
byte[] iv = new byte[12];
|
||||
RANDOM.nextBytes(iv);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv));
|
||||
byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] payload = new byte[iv.length + encrypted.length];
|
||||
System.arraycopy(iv, 0, payload, 0, iv.length);
|
||||
System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length);
|
||||
return CIPHER_PREFIX + Base64.getEncoder().encodeToString(payload);
|
||||
} catch (GeneralSecurityException exception) {
|
||||
throw new IllegalStateException("手机号加密失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String value) {
|
||||
if (!StringUtils.hasText(value) || !value.startsWith(CIPHER_PREFIX)) return value;
|
||||
try {
|
||||
byte[] payload = Base64.getDecoder().decode(value.substring(CIPHER_PREFIX.length()));
|
||||
if (payload.length < 29) throw new IllegalArgumentException("手机号密文格式无效");
|
||||
byte[] iv = Arrays.copyOfRange(payload, 0, 12);
|
||||
byte[] encrypted = Arrays.copyOfRange(payload, 12, payload.length);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv));
|
||||
return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
|
||||
} catch (GeneralSecurityException | IllegalArgumentException exception) {
|
||||
throw new IllegalStateException("手机号解密失败,请检查密钥或数据完整性", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号加密:ArtList 允许字母数字自定义账号,因此非空账号一律加密。
|
||||
*/
|
||||
public String encryptAccount(String value) {
|
||||
return encrypt(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号解密:仅对 {@code enc:v1:} 前缀的密文解密,历史明文账号原样返回。
|
||||
*/
|
||||
public String decryptAccount(String value) {
|
||||
return decrypt(value);
|
||||
}
|
||||
|
||||
public boolean isEncrypted(String value) {
|
||||
return value != null && value.startsWith(CIPHER_PREFIX);
|
||||
}
|
||||
|
||||
public boolean isMobilePhone(String value) {
|
||||
return value != null && value.trim().matches("1[3-9]\\d{9}");
|
||||
}
|
||||
|
||||
public String mask(String value) {
|
||||
if (!StringUtils.hasText(value)) return value;
|
||||
String plain = isEncrypted(value) ? decrypt(value) : value;
|
||||
return isMobilePhone(plain) ? plain.substring(0, 3) + "****" + plain.substring(7) : plain;
|
||||
}
|
||||
|
||||
public String index(String value) {
|
||||
if (!StringUtils.hasText(value)) return null;
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(indexKey, "HmacSHA256"));
|
||||
byte[] digest = mac.doFinal(value.trim().getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (GeneralSecurityException exception) {
|
||||
throw new IllegalStateException("敏感字段索引生成失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
public static PhoneCrypto current() {
|
||||
PhoneCrypto instance = current;
|
||||
if (instance == null) throw new IllegalStateException("手机号加密组件尚未初始化");
|
||||
return instance;
|
||||
}
|
||||
|
||||
private byte[] decodeKey(String value, String name) {
|
||||
if (!StringUtils.hasText(value)) throw new IllegalStateException("缺少Nacos配置: jayucloud-artlist.privacy." + name);
|
||||
try {
|
||||
return Base64.getDecoder().decode(value.trim());
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IllegalStateException("Nacos配置必须使用Base64编码: " + name, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.support.privacy;
|
||||
|
||||
import org.apache.ibatis.type.BaseTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* 手机号密文列的类型处理器,与 JC-Salon-Core 的 PhoneEncryptionTypeHandler 一致。
|
||||
* 仅作用于实体读写;QueryWrapper 条件不会经过类型处理器,按手机号查询必须使用 phone_hash。
|
||||
*/
|
||||
public class PhoneEncryptionTypeHandler extends BaseTypeHandler<String> {
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException {
|
||||
ps.setString(index, PhoneCrypto.current().encrypt(parameter));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||
return PhoneCrypto.current().decrypt(rs.getString(columnName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return PhoneCrypto.current().decrypt(rs.getString(columnIndex));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||
return PhoneCrypto.current().decrypt(cs.getString(columnIndex));
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.support.privacy;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 手机号 / 账号的集中脱敏策略。
|
||||
*
|
||||
* <p>后端始终完整保存明文语义(落库为 AES-GCM 密文),但返回前端、写日志、写审计时一律脱敏:
|
||||
* 不再存在任何"返回完整号码"的场景。需要真实号码时只走 {@code POST /contact-info/dial} 单次取号。</p>
|
||||
*/
|
||||
public final class SensitiveFieldPolicy {
|
||||
|
||||
/**
|
||||
* 调用场景,仅用于表达调用方语义;所有场景的输出均为脱敏值。
|
||||
*/
|
||||
public enum Scenario {
|
||||
SELF_PROFILE,
|
||||
ADMIN_LIST,
|
||||
THIRD_PARTY,
|
||||
DIAL,
|
||||
LOG
|
||||
}
|
||||
|
||||
private SensitiveFieldPolicy() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 手机号按场景返回脱敏值(138****0000)。
|
||||
*/
|
||||
public static String phone(String value, Scenario scenario) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return value;
|
||||
}
|
||||
String plain = PhoneCrypto.current().isEncrypted(value) ? PhoneCrypto.current().decrypt(value) : value;
|
||||
return PhoneCrypto.current().mask(plain);
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号按场景返回脱敏值;手机号形态账号按手机号规则脱敏,其余保留前两位。
|
||||
*/
|
||||
public static String account(String value, Scenario scenario) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return value;
|
||||
}
|
||||
String plain = PhoneCrypto.current().isEncrypted(value) ? PhoneCrypto.current().decryptAccount(value) : value;
|
||||
if (PhoneCrypto.current().isMobilePhone(plain)) {
|
||||
return PhoneCrypto.current().mask(plain);
|
||||
}
|
||||
return plain.length() <= 2 ? "***" : plain.substring(0, 2) + "***";
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.artlist.core.support.security;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
@@ -55,6 +56,10 @@ public class OperationGuardService {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final ObjectMapper objectMapper;
|
||||
/**
|
||||
* Purpose: phoneCrypto supports OperationGuardService.java by hashing phone numbers before they become Redis key segments.
|
||||
*/
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
/**
|
||||
* Purpose: tryAcquire supports OperationGuardService.java by holding or executing the try acquire business role.
|
||||
@@ -186,7 +191,8 @@ public class OperationGuardService {
|
||||
readBodyField(request, key)
|
||||
);
|
||||
if (StringUtils.hasText(value)) {
|
||||
return sanitize(value);
|
||||
// 手机号/账号不落 Redis 键:统一替换为哈希
|
||||
return ("phone".equals(key) || "account".equals(key)) ? phoneCrypto.index(value) : sanitize(value);
|
||||
}
|
||||
}
|
||||
return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI());
|
||||
|
||||
+16
@@ -107,6 +107,22 @@ public class RequestThrottleService {
|
||||
assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 联系方式查询限流:按登录用户维度。
|
||||
*/
|
||||
public void checkContactInfoRead(HttpServletRequest request, Long userId) {
|
||||
assertAllowed("contact-info-read", request, userId == null ? "" : String.valueOf(userId),
|
||||
rateLimitProperties.getContactInfoRead(), "联系方式查询过于频繁,请稍后再试");
|
||||
}
|
||||
|
||||
/**
|
||||
* 单次拨号取号限流:按登录用户维度,避免批量撞取号码。
|
||||
*/
|
||||
public void checkContactDial(HttpServletRequest request, Long userId) {
|
||||
assertAllowed("contact-dial", request, userId == null ? "" : String.valueOf(userId),
|
||||
rateLimitProperties.getContactDial(), "拨号取号过于频繁,请稍后再试");
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: recordLoginFailure supports RequestThrottleService.java by holding or executing the record login failure business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
-- =============================================================================
|
||||
-- V2 手机号加密与手机号哈希(ArtList)
|
||||
-- 日期:2026-11-04
|
||||
-- 口径:不做数据迁移,空库初始化。本迁移只调整结构,不回填历史数据。
|
||||
-- 说明:
|
||||
-- - t_user.phone / t_user.contact_phone 改为密文列 phone_cipher / contact_phone_cipher;
|
||||
-- - 新增 phone_hash / contact_phone_hash,用于等值查询与去重;
|
||||
-- - 哈希算法与 Salon 一致:HMAC-SHA256(规范化手机号),规范化为 trim;
|
||||
-- - 加密算法与 Salon 一致:AES/GCM/NoPadding,12 字节随机 IV,128 位 tag。
|
||||
-- 可重复执行:所有 DDL 均先查 information_schema 再执行。
|
||||
-- =============================================================================
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_v2_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v2_drop_column_if_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v2_drop_index_if_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v2_add_index_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v2_add_unique_index_if_not_exists;
|
||||
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE sp_v2_add_column_if_not_exists(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_column VARCHAR(64),
|
||||
IN p_definition VARCHAR(500)
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = DATABASE() AND table_name = p_table AND column_name = p_column
|
||||
) THEN
|
||||
SET @ddl = CONCAT('ALTER TABLE `', p_table, '` ADD COLUMN `', p_column, '` ', p_definition);
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END $$
|
||||
|
||||
CREATE PROCEDURE sp_v2_drop_column_if_exists(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_column VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = DATABASE() AND table_name = p_table AND column_name = p_column
|
||||
) THEN
|
||||
SET @ddl = CONCAT('ALTER TABLE `', p_table, '` DROP COLUMN `', p_column, '`');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END $$
|
||||
|
||||
CREATE PROCEDURE sp_v2_drop_index_if_exists(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_index VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.statistics
|
||||
WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index
|
||||
) THEN
|
||||
SET @ddl = CONCAT('ALTER TABLE `', p_table, '` DROP INDEX `', p_index, '`');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END $$
|
||||
|
||||
CREATE PROCEDURE sp_v2_add_index_if_not_exists(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_index VARCHAR(64),
|
||||
IN p_columns VARCHAR(255)
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.statistics
|
||||
WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index
|
||||
) THEN
|
||||
SET @ddl = CONCAT('CREATE INDEX `', p_index, '` ON `', p_table, '` ', p_columns);
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END $$
|
||||
|
||||
CREATE PROCEDURE sp_v2_add_unique_index_if_not_exists(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_index VARCHAR(64),
|
||||
IN p_columns VARCHAR(255)
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.statistics
|
||||
WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index
|
||||
) THEN
|
||||
SET @ddl = CONCAT('CREATE UNIQUE INDEX `', p_index, '` ON `', p_table, '` ', p_columns);
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END $$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
CALL sp_v2_add_column_if_not_exists('t_user', 'phone_cipher', 'varchar(255) NULL COMMENT ''手机号密文(AES-GCM)''');
|
||||
CALL sp_v2_add_column_if_not_exists('t_user', 'phone_hash', 'char(64) NULL COMMENT ''手机号哈希(HMAC-SHA256,十六进制小写)''');
|
||||
CALL sp_v2_add_column_if_not_exists('t_user', 'contact_phone_cipher', 'varchar(255) NULL COMMENT ''联系电话密文(AES-GCM)''');
|
||||
CALL sp_v2_add_column_if_not_exists('t_user', 'contact_phone_hash', 'char(64) NULL COMMENT ''联系电话哈希(HMAC-SHA256,十六进制小写)''');
|
||||
|
||||
CALL sp_v2_drop_index_if_exists('t_user', 'idx_phone');
|
||||
CALL sp_v2_drop_column_if_exists('t_user', 'phone');
|
||||
CALL sp_v2_drop_column_if_exists('t_user', 'contact_phone');
|
||||
|
||||
-- MySQL 唯一索引允许多行 NULL,因此未绑定手机号的用户不受影响。
|
||||
CALL sp_v2_add_unique_index_if_not_exists('t_user', 'uk_user_phone_hash', '(phone_hash)');
|
||||
CALL sp_v2_add_index_if_not_exists('t_user', 'idx_user_contact_phone_hash', '(contact_phone_hash)');
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_v2_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v2_drop_column_if_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v2_drop_index_if_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v2_add_index_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v2_add_unique_index_if_not_exists;
|
||||
@@ -0,0 +1,110 @@
|
||||
-- 隐私政策与用户协议条款修订:对齐手机号/账号 AES-GCM 加密存储、HMAC 不可逆索引与按场景脱敏展示
|
||||
-- 版本:2026.11.04
|
||||
-- 说明:仅停用旧版本并新增协议版本,不修改已在任一环境执行的 V1 协议正文。
|
||||
-- 版本号说明:并行改造已占用 V3(账号加密与账号哈希),本次协议修订顺延为 V4。
|
||||
|
||||
UPDATE t_legal_agreement
|
||||
SET status = 0, update_time = NOW()
|
||||
WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY')
|
||||
AND is_delete = 0
|
||||
AND status = 1;
|
||||
|
||||
INSERT INTO t_legal_agreement
|
||||
(id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
|
||||
VALUES
|
||||
(313931273555138003, 'USER_TERMS', '用户协议', '2026.11.04',
|
||||
'欢迎使用 JayuCloud ArtList。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。本协议与《隐私政策》共同构成你使用本服务的基础规则。
|
||||
|
||||
一、协议接受与版本
|
||||
你在登录或注册前应完整阅读本协议和《隐私政策》并主动选择同意;不同意时不能完成注册或继续使用。本协议版本为 2026.11.04,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。
|
||||
|
||||
二、账号与安全
|
||||
1. 你应使用本人手机号注册和登录,手机号用于身份识别、验证码校验、订单联系和账号找回。
|
||||
2. 手机号与账号按《隐私政策》所述采用 AES-GCM 加密存储,并以 phone_hash/account_hash 不可逆索引支持登录与去重;客户端页面按场景展示脱敏或完整号码,完整号码仅限权限校验通过的必要业务场景。
|
||||
3. 你应妥善保管账号、验证码和登录设备,不得转借、出租、出售账号,不得绕过权限校验访问他人信息。
|
||||
4. 发现账号异常、手机号被冒用或验证码泄露时,应及时修改资料、解绑手机号并联系客服。
|
||||
|
||||
三、预约、订单与会员
|
||||
1. 预约与订单信息应真实、准确;你应确保填写的联系人手机号已获得联系人授权。
|
||||
2. 订单金额、会员余额、优惠券和售后规则以页面展示和门店确认为准;本平台当前不发起在线支付,充值档位仅作展示,实际充值、退款和余额变动由门店按线下流程处理。
|
||||
3. 不得利用订单、优惠券、会员权益进行虚假交易、套现、刷单或欺诈。
|
||||
|
||||
四、用户内容
|
||||
你上传的头像、作品图片、评价等内容应来源合法,不得包含违法、侵权、暴力、色情、欺诈或侵害他人权益的信息。你授予平台为提供服务所必需的展示、存储和处理权限;平台可对违规内容采取删除、屏蔽或限制功能等措施。
|
||||
|
||||
五、个人信息与保密
|
||||
1. 你不得收集、导出、转卖或向无关第三方提供通过平台获取的他人手机号、订单或会员信息。
|
||||
2. 完整手机号仅在本人资料维护、管理端编辑、门店或客服拨号等必要业务场景,且权限校验通过时由服务端使用,任何客户端页面不得作为批量获取完整号码的工具。
|
||||
|
||||
六、账号注销与数据留存
|
||||
1. 你可在小程序设置中申请注销;注销后账号不可登录,系统清除账号手机号密文和 phone_hash 索引,将账号标识替换为注销占位,并更新 account_hash。
|
||||
2. 订单、预约、会员余额、售后和交易记录在去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。
|
||||
3. 法律法规另有强制留存要求的,按法定期限保存。
|
||||
|
||||
七、未成年人
|
||||
不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,不得注册或下单。
|
||||
|
||||
八、服务调整、责任与联系
|
||||
1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。
|
||||
2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。
|
||||
3. 隐私相关申请可从设置发起或联系在线客服;其他问题请联系运营方公布的客服渠道【待业务确认】。
|
||||
|
||||
本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。',
|
||||
1, NOW(), NOW(), NOW(), 0),
|
||||
(313931273555138004, 'PRIVACY_POLICY', '隐私政策', '2026.11.04',
|
||||
'JayuCloud ArtList 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。本政策说明我们如何处理这些个人信息。
|
||||
|
||||
一、处理的信息及用途
|
||||
1. 登录与账号:你通过微信登录授权获取 OpenID 与 UnionID,用于识别和绑定账号;你主动授权手机号或输入手机号完成注册登录,手机号用于注册登录、验证码校验、订单联系、售后处理和账号找回,不用于营销。
|
||||
2. 账号标识:账号用于身份识别、权限校验和操作归属记录;账号与手机号均使用 AES-GCM 加密存储。
|
||||
3. 资料:昵称、头像仅在你主动补充或更新时处理。
|
||||
4. 业务信息:预约、订单、会员余额与余额变动、优惠券、售后、消息和客服记录,用于履行交易和服务。
|
||||
5. 安全运行:服务端处理网络地址、登录会话、客户端本地生成的随机设备标识和操作审计信息,用于登录安全、风险控制和审计;不采集 IMEI、MAC、通讯录、麦克风或持续定位。
|
||||
6. 内容与图片:你主动上传的头像、作品图片等文件存储于对象存储,用于资料展示和服务履约;本服务当前不接入第三方内容安全审核平台和地图服务,如后续启用将更新本政策并另行告知。
|
||||
|
||||
二、加密存储与检索索引
|
||||
1. 手机号与账号使用 AES-GCM 加密后落库,不以明文存入数据库;密文带版本标识。
|
||||
2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供。
|
||||
3. 为支持登录、去重和查询匹配,系统以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引;该索引不能反推手机号或账号原文,不对外展示。
|
||||
4. 备份、导出和迁移沿用同等加密要求。
|
||||
|
||||
三、按场景脱敏展示
|
||||
1. 订单、预约、售后、消息、客户服务和后台列表等常规场景展示脱敏号码。
|
||||
2. 本人资料维护、管理端编辑、门店或客服拨号等必要业务联系场景,在登录态、门店或订单可见范围和权限校验通过时展示完整号码;完整号码不向无权限页面批量返回。
|
||||
3. 脱敏由服务端集中策略执行;客户端不得缓存、截屏传播或向无关第三方提供完整号码。
|
||||
|
||||
四、第三方共享
|
||||
我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的:
|
||||
1. 微信:微信登录、手机号授权和订阅消息。
|
||||
2. 短信服务商:通过部署环境配置的 MessageHub 短信通道发送验证码、绑定/解绑和必要业务通知。
|
||||
3. 消息通道:通过 MessageHub 等已配置通道推送站内或订阅消息。
|
||||
4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。
|
||||
我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。
|
||||
|
||||
五、保存期限与删除
|
||||
1. 账号注销:可在小程序设置中提交注销申请;注销后账号不可登录,系统清除账号手机号密文和 phone_hash 索引,将账号标识替换为注销占位,并更新 account_hash。
|
||||
2. 订单、预约、会员余额、售后和交易记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。
|
||||
3. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。
|
||||
4. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。
|
||||
|
||||
六、你的权利
|
||||
1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在设置中更换。
|
||||
2. 删除与注销:可在设置中申请注销;也可请求删除非交易必需的资料。
|
||||
3. 撤回同意:可在设置或联系客服撤回授权;撤回后不影响撤回前已进行的处理。
|
||||
4. 投诉与咨询:可联系在线客服或运营方公布的客服渠道【待业务确认】;我们将在收到请求后按适用法律规定的期限响应。
|
||||
5. 请注意:为保障交易安全,订单、余额和售后记录在法定或约定留存期内可能无法立即删除。
|
||||
|
||||
七、未成年人保护
|
||||
不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,我们不会处理其个人信息。如发现误收集,将停止处理并删除。
|
||||
|
||||
八、安全措施与安全事件响应
|
||||
我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。
|
||||
|
||||
九、跨境传输
|
||||
目前我们不涉及向境外提供个人信息。如未来发生跨境传输,将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。
|
||||
|
||||
十、政策更新与联系
|
||||
本政策版本为 2026.11.04,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在设置中查看当前版本;其他问题请联系在线客服或运营方公布的客服渠道【待业务确认】。
|
||||
|
||||
本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。',
|
||||
1, NOW(), NOW(), NOW(), 0);
|
||||
@@ -0,0 +1,118 @@
|
||||
-- ============================================================
|
||||
-- ArtList V5:账号加密与账号哈希
|
||||
-- 日期:2026-11-04
|
||||
--
|
||||
-- 版本号说明:V3 从未在任何环境执行过;并行分支已先占用 V4
|
||||
-- (V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql),
|
||||
-- 在 out-of-order:false 前提下本文件使用 V5,保证 V1→V2→V4→V5 顺序天然正确。
|
||||
--
|
||||
-- 语义:
|
||||
-- 1. t_user.account 列改为存放 AES-GCM 密文(enc:v1: 前缀),列名与 Salon 保持一致;
|
||||
-- 2. 新增 account_hash(HMAC-SHA256 十六进制),并建立唯一索引 uk_user_account_hash,
|
||||
-- 所有账号等值查询统一走 account_hash;
|
||||
-- 3. 删除依赖明文 account 的唯一索引 uk_account;
|
||||
-- 4. 不做 SQL 数据迁移:历史/种子账号(如 xiaowang)由应用启动时
|
||||
-- AccountHashBackfillRunner 加密并回填 hash。
|
||||
--
|
||||
-- 幂等:information_schema 判存在 + 存储过程,沿用 V2 风格;可安全重放。
|
||||
-- ============================================================
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_v5_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v5_drop_index_if_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v5_add_unique_index_if_not_exists;
|
||||
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE sp_v5_add_column_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64),
|
||||
IN p_definition TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ',
|
||||
p_definition
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_v5_drop_index_if_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` DROP INDEX `', p_index_name, '`'
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_v5_add_unique_index_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_columns TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ',
|
||||
p_columns
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
-- 1. 账号列改为密文容器(与 Salon 对齐:varchar(128) NULL)
|
||||
ALTER TABLE t_user
|
||||
MODIFY COLUMN account varchar(128) NULL COMMENT '账号AES-GCM密文(enc:v1: 前缀)';
|
||||
|
||||
-- 2. 新增账号 HMAC 索引列
|
||||
CALL sp_v5_add_column_if_not_exists(
|
||||
't_user',
|
||||
'account_hash',
|
||||
"char(64) NULL COMMENT '账号HMAC-SHA256索引'"
|
||||
);
|
||||
|
||||
-- 3. 删除依赖明文账号的唯一索引
|
||||
CALL sp_v5_drop_index_if_exists('t_user', 'uk_account');
|
||||
|
||||
-- 4. 新增账号哈希唯一索引(MySQL 唯一索引允许多行 NULL)
|
||||
CALL sp_v5_add_unique_index_if_not_exists(
|
||||
't_user',
|
||||
'uk_user_account_hash',
|
||||
'(account_hash)'
|
||||
);
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_v5_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v5_drop_index_if_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_v5_add_unique_index_if_not_exists;
|
||||
@@ -0,0 +1,119 @@
|
||||
-- V6:协议文本改为全场景脱敏与单次拨号取号
|
||||
-- 版本:2026.11.04-R2
|
||||
-- 说明:V4 已发布 2026.11.04 版本协议文本;本次仅新增修订版本并停用旧版本,不修改 V1/V2/V4 文件内容。
|
||||
-- 变更点:所有推送前端的号码一律脱敏;电话联系改为按需单次拨号取号,可对接隐私号码且未配置时明确不可用。
|
||||
|
||||
UPDATE t_legal_agreement
|
||||
SET status = 0,
|
||||
update_time = NOW()
|
||||
WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY')
|
||||
AND is_delete = 0
|
||||
AND status = 1;
|
||||
|
||||
INSERT INTO t_legal_agreement
|
||||
(id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
|
||||
VALUES
|
||||
(313931273555138005, 'USER_TERMS', '用户协议', '2026.11.04-R2',
|
||||
'欢迎使用 JayuCloud ArtList。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。本协议与《隐私政策》共同构成你使用本服务的基础规则。
|
||||
|
||||
一、协议接受与版本
|
||||
你在登录或注册前应完整阅读本协议和《隐私政策》并主动选择同意;不同意时不能完成注册或继续使用。本协议版本为 2026.11.04-R2,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。
|
||||
|
||||
二、账号与安全
|
||||
1. 你应使用本人手机号注册和登录,手机号用于身份识别、验证码校验、订单联系和账号找回。
|
||||
2. 手机号与账号按《隐私政策》所述采用 AES-GCM 加密存储,并以 phone_hash/account_hash 不可逆索引支持登录与去重;客户端页面一律展示脱敏号码,需要电话联系时通过单次拨号取号接口按需获取当次可拨号码,该接口可对接隐私号码且不会回退为真实号码。
|
||||
3. 你应妥善保管账号、验证码和登录设备,不得转借、出租、出售账号,不得绕过权限校验访问他人信息。
|
||||
4. 发现账号异常、手机号被冒用或验证码泄露时,应及时修改资料、解绑手机号并联系客服。
|
||||
|
||||
三、预约、订单与会员
|
||||
1. 预约与订单信息应真实、准确;你应确保填写的联系人手机号已获得联系人授权。
|
||||
2. 订单金额、会员余额、优惠券和售后规则以页面展示和门店确认为准;本平台当前不发起在线支付,充值档位仅作展示,实际充值、退款和余额变动由门店按线下流程处理。
|
||||
3. 不得利用订单、优惠券、会员权益进行虚假交易、套现、刷单或欺诈。
|
||||
|
||||
四、用户内容
|
||||
你上传的头像、作品图片、评价等内容应来源合法,不得包含违法、侵权、暴力、色情、欺诈或侵害他人权益的信息。你授予平台为提供服务所必需的展示、存储和处理权限;平台可对违规内容采取删除、屏蔽或限制功能等措施。
|
||||
|
||||
五、个人信息与保密
|
||||
1. 你不得收集、导出、转卖或向无关第三方提供通过平台获取的他人手机号、订单或会员信息。
|
||||
2. 任何客户端页面均不展示完整手机号;需要电话联系时,仅在登录态与可见范围、权限校验通过后通过单次拨号取号接口获取当次可拨号码,平台不向客户端批量返回、缓存或提供长期有效的号码。
|
||||
|
||||
六、账号注销与数据留存
|
||||
1. 你可在小程序设置中申请注销;注销后账号不可登录,系统清除账号手机号密文、联系电话密文及相关哈希索引,将账号标识替换为注销占位,并更新 account_hash。
|
||||
2. 订单、预约、会员余额、售后和交易记录在去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。
|
||||
3. 法律法规另有强制留存要求的,按法定期限保存。
|
||||
|
||||
七、未成年人
|
||||
不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,不得注册或下单。
|
||||
|
||||
八、服务调整、责任与联系
|
||||
1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。
|
||||
2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。
|
||||
3. 隐私相关申请可从设置发起或联系在线客服;其他问题请联系运营方公布的客服渠道【待业务确认】。
|
||||
|
||||
本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。',
|
||||
1, NOW(), NOW(), NOW(), 0),
|
||||
(313931273555138006, 'PRIVACY_POLICY', '隐私政策', '2026.11.04-R2',
|
||||
'JayuCloud ArtList 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。本政策说明我们如何处理这些个人信息。
|
||||
|
||||
一、处理的信息及用途
|
||||
1. 登录与账号:你通过微信登录授权获取 OpenID 与 UnionID,用于识别和绑定账号;你主动授权手机号或输入手机号完成注册登录,手机号用于注册登录、验证码校验、订单联系、售后处理和账号找回,不用于营销。
|
||||
2. 账号标识:账号用于身份识别、权限校验和操作归属记录;账号与手机号均使用 AES-GCM 加密存储。
|
||||
3. 资料:昵称、头像仅在你主动补充或更新时处理。
|
||||
4. 业务信息:预约、订单、会员余额与余额变动、优惠券、售后、消息和客服记录,用于履行交易和服务。
|
||||
5. 安全运行:服务端处理网络地址、登录会话、客户端本地生成的随机设备标识和操作审计信息,用于登录安全、风险控制和审计;不采集 IMEI、MAC、通讯录、麦克风或持续定位。
|
||||
6. 内容与图片:你主动上传的头像、作品图片等文件存储于对象存储,用于资料展示和服务履约;本服务当前不接入第三方内容安全审核平台和地图服务,如后续启用将更新本政策并另行告知。
|
||||
|
||||
二、加密存储与检索索引
|
||||
1. 手机号与账号使用 AES-GCM 加密后落库,不以明文存入数据库;密文带版本标识。
|
||||
2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供。
|
||||
3. 为支持登录、去重和查询匹配,系统以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引;该索引不能反推手机号或账号原文,不对外展示。
|
||||
4. 备份、导出和迁移沿用同等加密要求。
|
||||
|
||||
三、全场景脱敏与单次拨号取号
|
||||
1. 本人资料、管理端列表与编辑、订单、预约、售后、消息、客户服务和后台列表等所有返回客户端的场景,一律展示脱敏号码与脱敏账号;服务端不对客户端返回完整手机号。
|
||||
2. 需要电话联系时,客户端在点击联系入口后调用单次拨号取号接口;服务端按场景校验登录态、订单归属、门店可见范围与权限后,返回当次可拨号码或隐私号码,响应带有效期标识,前端不缓存、不落库、不写入日志。
|
||||
3. 平台可对接隐私号码服务;未配置隐私号码时接口明确返回不可用错误,不会回退为真实号码。
|
||||
4. 日志、审计、消息记录与缓存不得保存完整手机号或完整账号;审计仅记录操作人、时间、场景与结果。
|
||||
|
||||
四、第三方共享
|
||||
我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的:
|
||||
1. 微信:微信登录、手机号授权和订阅消息。
|
||||
2. 短信服务商:通过部署环境配置的 MessageHub 短信通道发送验证码、绑定/解绑和必要业务通知。
|
||||
3. 消息通道:通过 MessageHub 等已配置通道推送站内或订阅消息。
|
||||
4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。
|
||||
我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。
|
||||
|
||||
五、保存期限与删除
|
||||
1. 账号注销:可在小程序设置中提交注销申请;注销后账号不可登录,系统清除账号手机号密文、联系电话密文及相关哈希索引,将账号标识替换为注销占位,并更新 account_hash。
|
||||
2. 订单、预约、会员余额、售后和交易记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。
|
||||
3. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。
|
||||
4. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。
|
||||
|
||||
六、你的权利
|
||||
1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在设置中更换,展示值为脱敏值。
|
||||
2. 删除与注销:可在设置中申请注销;也可请求删除非交易必需的资料。
|
||||
3. 撤回同意:可在设置或联系客服撤回授权;撤回后不影响撤回前已进行的处理。
|
||||
4. 投诉与咨询:可联系在线客服或运营方公布的客服渠道【待业务确认】;我们将在收到请求后按适用法律规定的期限响应。
|
||||
5. 请注意:为保障交易安全,订单、余额和售后记录在法定或约定留存期内可能无法立即删除。
|
||||
|
||||
七、未成年人保护
|
||||
不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,我们不会处理其个人信息。如发现误收集,将停止处理并删除。
|
||||
|
||||
八、安全措施与安全事件响应
|
||||
我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。
|
||||
|
||||
九、跨境传输
|
||||
目前我们不涉及向境外提供个人信息。如未来发生跨境传输,将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。
|
||||
|
||||
十、政策更新与联系
|
||||
本政策版本为 2026.11.04-R2,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在设置中查看当前版本;其他问题请联系在线客服或运营方公布的客服渠道【待业务确认】。
|
||||
|
||||
本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。',
|
||||
1, NOW(), NOW(), NOW(), 0)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
title = VALUES(title),
|
||||
content = VALUES(content),
|
||||
status = VALUES(status),
|
||||
effective_time = VALUES(effective_time),
|
||||
is_delete = 0,
|
||||
update_time = NOW();
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactDialService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
|
||||
import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ContactDialControllerTest {
|
||||
@Mock
|
||||
private ContactInfoService contactInfoService;
|
||||
@Mock
|
||||
private ContactDialService contactDialService;
|
||||
@Mock
|
||||
private RequestThrottleService requestThrottleService;
|
||||
@Mock
|
||||
private SecurityAuditLogService securityAuditLogService;
|
||||
|
||||
private ContactInfoController controller;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new ContactInfoController(contactInfoService, contactDialService, requestThrottleService,
|
||||
securityAuditLogService);
|
||||
request = new MockHttpServletRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnonymousCallerWith403() {
|
||||
DialRequestDTO dialRequestDTO = new DialRequestDTO();
|
||||
dialRequestDTO.setScene("PLATFORM");
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class, () ->
|
||||
controller.dial(request, dialRequestDTO));
|
||||
|
||||
assertEquals(403, exception.getCode());
|
||||
verify(contactDialService, never()).dial(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void successRecordsAuditWithoutNumber() {
|
||||
request.setAttribute("userId", 1L);
|
||||
request.setAttribute("account", "xiaowang");
|
||||
DialRequestDTO dialRequestDTO = new DialRequestDTO();
|
||||
dialRequestDTO.setScene("SHOP_MANAGER");
|
||||
dialRequestDTO.setTargetId(88L);
|
||||
DialResponseVO response = new DialResponseVO();
|
||||
response.setMode("DIRECT");
|
||||
response.setDialNumber("13800000000");
|
||||
response.setExpiresInSeconds(300);
|
||||
when(contactDialService.dial(eq(1L), any())).thenReturn(response);
|
||||
|
||||
controller.dial(request, dialRequestDTO);
|
||||
|
||||
verify(requestThrottleService).checkContactDial(request, 1L);
|
||||
verify(securityAuditLogService).record(eq(1L), eq("xiaowang"), eq("CONTACT_DIAL_SHOP_MANAGER"),
|
||||
eq("SUCCESS"), eq(null), eq(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttledRequestDoesNotReachDialService() {
|
||||
request.setAttribute("userId", 1L);
|
||||
DialRequestDTO dialRequestDTO = new DialRequestDTO();
|
||||
dialRequestDTO.setScene("PLATFORM");
|
||||
org.mockito.Mockito.doThrow(new RuntimeException("拨号取号过于频繁,请稍后再试"))
|
||||
.when(requestThrottleService).checkContactDial(request, 1L);
|
||||
|
||||
RuntimeException exception = assertThrows(RuntimeException.class, () ->
|
||||
controller.dial(request, dialRequestDTO));
|
||||
|
||||
assertEquals("拨号取号过于频繁,请稍后再试", exception.getMessage());
|
||||
verify(contactDialService, never()).dial(any(), any());
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.artlist.core.config.DialProperties;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialTargetProvider;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DirectDialTargetProvider;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.PlaceholderPrivacyNumberProvider;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ContactDialServiceTest {
|
||||
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
@Mock
|
||||
private ShopMapper shopMapper;
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
@Mock
|
||||
private OrderMapper orderMapper;
|
||||
@Mock
|
||||
private OrderItemMapper orderItemMapper;
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
private DialProperties dialProperties;
|
||||
private ContactDialServiceImpl contactDialService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
dialProperties = new DialProperties();
|
||||
dialProperties.setProvider("direct");
|
||||
DialTargetProvider[] providers = {
|
||||
new DirectDialTargetProvider(),
|
||||
new PlaceholderPrivacyNumberProvider()
|
||||
};
|
||||
contactDialService = new ContactDialServiceImpl(userMapper, shopMapper, productMapper, orderMapper,
|
||||
orderItemMapper, userShopBindingSupport, dialProperties, Arrays.asList(providers));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnonymousCallerWith403() {
|
||||
BusinessException exception = assertThrows(BusinessException.class, () ->
|
||||
contactDialService.dial(null, platformRequest()));
|
||||
assertEquals(403, exception.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void platformSceneReturnsDirectNumber() {
|
||||
UserDO caller = user(1L, 1);
|
||||
UserDO admin = user(9L, 4);
|
||||
admin.setPhone("13800000000");
|
||||
when(userMapper.selectById(1L)).thenReturn(caller);
|
||||
when(userMapper.selectOne(any())).thenReturn(admin);
|
||||
|
||||
DialResponseVO response = contactDialService.dial(1L, platformRequest());
|
||||
|
||||
assertEquals("DIRECT", response.getMode());
|
||||
assertEquals("13800000000", response.getDialNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void orderArtistRejectsOrderOfOtherUser() {
|
||||
UserDO caller = user(1L, 1);
|
||||
OrderDO order = new OrderDO();
|
||||
order.setId(100L);
|
||||
order.setUserId(2L);
|
||||
order.setIsDelete(0);
|
||||
when(userMapper.selectById(1L)).thenReturn(caller);
|
||||
when(orderMapper.selectById(100L)).thenReturn(order);
|
||||
|
||||
DialRequestDTO request = new DialRequestDTO();
|
||||
request.setScene("ORDER_ARTIST");
|
||||
request.setTargetId(100L);
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class, () ->
|
||||
contactDialService.dial(1L, request));
|
||||
assertEquals(403, exception.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void privacyNumberProviderNeverFallsBackToRealNumber() {
|
||||
dialProperties.setProvider("privacy-number");
|
||||
UserDO caller = user(1L, 1);
|
||||
UserDO admin = user(9L, 4);
|
||||
admin.setPhone("13800000000");
|
||||
when(userMapper.selectById(1L)).thenReturn(caller);
|
||||
when(userMapper.selectOne(any())).thenReturn(admin);
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class, () ->
|
||||
contactDialService.dial(1L, platformRequest()));
|
||||
|
||||
assertEquals(PlaceholderPrivacyNumberProvider.NOT_CONFIGURED_CODE, exception.getCode());
|
||||
}
|
||||
|
||||
private DialRequestDTO platformRequest() {
|
||||
DialRequestDTO request = new DialRequestDTO();
|
||||
request.setScene("PLATFORM");
|
||||
return request;
|
||||
}
|
||||
|
||||
private UserDO user(Long id, Integer type) {
|
||||
UserDO user = new UserDO();
|
||||
user.setId(id);
|
||||
user.setType(type);
|
||||
user.setIsDelete(0);
|
||||
user.setStatus(1);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.support.privacy;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PhoneCryptoTest {
|
||||
|
||||
private static final String ENCRYPTION_KEY = "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM=";
|
||||
private static final String INDEX_KEY = "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU=";
|
||||
|
||||
private PhoneCrypto phoneCrypto;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
PhoneCryptoProperties properties = new PhoneCryptoProperties();
|
||||
properties.setEncryptionKey(ENCRYPTION_KEY);
|
||||
properties.setIndexKey(INDEX_KEY);
|
||||
phoneCrypto = new PhoneCrypto(properties);
|
||||
phoneCrypto.initialize();
|
||||
}
|
||||
|
||||
@Test
|
||||
void encryptAndDecryptRoundTrip() {
|
||||
String phone = "13800000000";
|
||||
String cipher = phoneCrypto.encrypt(phone);
|
||||
assertTrue(cipher.startsWith("enc:v1:"));
|
||||
assertEquals(phone, phoneCrypto.decrypt(cipher));
|
||||
assertNotEquals(cipher, phoneCrypto.encrypt(phone), "随机IV使同一明文的密文不同");
|
||||
}
|
||||
|
||||
@Test
|
||||
void hashIsStableForSamePhone() {
|
||||
String phone = "13800000000";
|
||||
String first = phoneCrypto.index(phone);
|
||||
String second = phoneCrypto.index(phone);
|
||||
assertEquals(first, second);
|
||||
assertEquals(64, first.length());
|
||||
assertEquals(first, first.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizationOnlyTrimsToMatchSalon() {
|
||||
assertEquals(phoneCrypto.index("13800000000"), phoneCrypto.index(" 13800000000 "));
|
||||
assertNotEquals(phoneCrypto.index("13800000000"), phoneCrypto.index("+8613800000000"));
|
||||
assertNotEquals(phoneCrypto.index("13800000000"), phoneCrypto.index("138-0000-0000"));
|
||||
assertFalse(phoneCrypto.isMobilePhone("+8613800000000"));
|
||||
assertFalse(phoneCrypto.isMobilePhone("138-0000-0000"));
|
||||
assertTrue(phoneCrypto.isMobilePhone("13800000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hashOfUnknownPhoneDoesNotMatchRegisteredPhone() {
|
||||
assertNotEquals(phoneCrypto.index("13900000000"), phoneCrypto.index("13800000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskKeepsPrefixAndSuffix() {
|
||||
assertEquals("138****0000", phoneCrypto.mask("13800000000"));
|
||||
assertEquals("138****0000", phoneCrypto.mask(phoneCrypto.encrypt("13800000000")));
|
||||
assertEquals("zhangsan", phoneCrypto.mask("zhangsan"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountIsAlwaysEncryptedAndDecryptsBack() {
|
||||
String account = "xiaowang";
|
||||
String cipher = phoneCrypto.encryptAccount(account);
|
||||
assertTrue(cipher.startsWith("enc:v1:"));
|
||||
assertEquals(account, phoneCrypto.decryptAccount(cipher));
|
||||
// 数值型自定义账号同样加密,不采用 Salon 的"仅手机号形态加密"条件
|
||||
String digitAccount = "20261104";
|
||||
assertTrue(phoneCrypto.encryptAccount(digitAccount).startsWith("enc:v1:"));
|
||||
assertEquals(digitAccount, phoneCrypto.decryptAccount(phoneCrypto.encryptAccount(digitAccount)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyPlainAccountIsReadableAndHashIsStable() {
|
||||
// V1 种子账号历史上是明文,无 enc:v1: 前缀时原样返回
|
||||
assertEquals("xiaowang", phoneCrypto.decryptAccount("xiaowang"));
|
||||
assertEquals(phoneCrypto.index("xiaowang"), phoneCrypto.index(" xiaowang "));
|
||||
assertEquals(64, phoneCrypto.index("xiaowang").length());
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.xiaowang.jayucloud.artlist.core.support.privacy;
|
||||
|
||||
import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class SensitiveFieldPolicyTest {
|
||||
|
||||
private static final String ENCRYPTION_KEY = "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM=";
|
||||
private static final String INDEX_KEY = "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU=";
|
||||
private static final String PHONE = "13800000000";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
PhoneCryptoProperties properties = new PhoneCryptoProperties();
|
||||
properties.setEncryptionKey(ENCRYPTION_KEY);
|
||||
properties.setIndexKey(INDEX_KEY);
|
||||
PhoneCrypto crypto = new PhoneCrypto(properties);
|
||||
crypto.initialize();
|
||||
}
|
||||
|
||||
@Test
|
||||
void phoneIsMaskedInEveryScenario() {
|
||||
assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.SELF_PROFILE));
|
||||
assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.ADMIN_LIST));
|
||||
assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.THIRD_PARTY));
|
||||
assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.DIAL));
|
||||
assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.LOG));
|
||||
assertEquals("138****0000", SensitiveFieldPolicy.phone(PhoneCrypto.current().encrypt(PHONE), SensitiveFieldPolicy.Scenario.DIAL));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountIsMaskedInEveryScenario() {
|
||||
assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.SELF_PROFILE));
|
||||
assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.ADMIN_LIST));
|
||||
assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.THIRD_PARTY));
|
||||
assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.DIAL));
|
||||
assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.LOG));
|
||||
assertEquals("138****0000", SensitiveFieldPolicy.account(PHONE, SensitiveFieldPolicy.Scenario.ADMIN_LIST));
|
||||
assertEquals("***", SensitiveFieldPolicy.account("ab", SensitiveFieldPolicy.Scenario.LOG));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encryptedAccountIsMaskedAfterDecrypt() {
|
||||
assertEquals("xi***", SensitiveFieldPolicy.account(PhoneCrypto.current().encryptAccount("xiaowang"), SensitiveFieldPolicy.Scenario.SELF_PROFILE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullAndBlankValuesStayUnchanged() {
|
||||
assertEquals(null, SensitiveFieldPolicy.phone(null, SensitiveFieldPolicy.Scenario.LOG));
|
||||
assertEquals("", SensitiveFieldPolicy.account("", SensitiveFieldPolicy.Scenario.ADMIN_LIST));
|
||||
}
|
||||
}
|
||||
@@ -202,7 +202,8 @@ export interface InviteCodeVO {
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UpdatePhoneRequest {
|
||||
oldPhone: string
|
||||
/** 兼容旧协议保留;服务端按当前登录用户取原手机号,不再使用该字段。 */
|
||||
oldPhone?: string
|
||||
newPhone: string
|
||||
verificationCode: string
|
||||
}
|
||||
@@ -319,6 +320,20 @@ export interface ContactInfoVO {
|
||||
platformContactText?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 拨号场景:与后端 /contact-info/dial 的 scene 取值一致。
|
||||
*/
|
||||
export type ContactDialScene = 'SHOP_MANAGER' | 'ORDER_ARTIST' | 'PRODUCT_ARTIST' | 'PLATFORM'
|
||||
|
||||
/**
|
||||
* 单次拨号取号结果;DIRECT 为直拨真实号码,PRIVACY_NUMBER 为隐私号码。
|
||||
*/
|
||||
export interface DialContactResult {
|
||||
mode: 'DIRECT' | 'PRIVACY_NUMBER'
|
||||
dialNumber: string
|
||||
expiresInSeconds: number
|
||||
}
|
||||
|
||||
/**
|
||||
* userApi groups all API calls for this page domain.
|
||||
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
|
||||
@@ -385,7 +400,7 @@ export const userApi = {
|
||||
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
|
||||
* @param data: { phone: string; sceneCode?: string } caller-supplied value for `data: { phone: string; sceneCode?: string }`
|
||||
*/
|
||||
sendVerificationCode: (data: { phone: string; sceneCode?: string }) => {
|
||||
sendVerificationCode: (data: { phone?: string; sceneCode?: string }) => {
|
||||
return api.post('/user/send-verification-code', data)
|
||||
},
|
||||
/**
|
||||
@@ -459,6 +474,10 @@ export const userApi = {
|
||||
getPlatformContact: async (): Promise<ContactInfoVO> => {
|
||||
return await api.get<ContactInfoVO>('/contact-info/platform') as unknown as ContactInfoVO
|
||||
},
|
||||
// 单次拨号取号:号码不缓存到本地,拨号完成后即丢弃。
|
||||
dialContact: async (scene: ContactDialScene, targetId?: IdType, artistId?: IdType): Promise<DialContactResult> => {
|
||||
return await api.post<DialContactResult>('/contact-info/dial', { scene, targetId, artistId }) as unknown as DialContactResult
|
||||
},
|
||||
/**
|
||||
* `deactivateAccount` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
|
||||
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
|
||||
|
||||
@@ -625,8 +625,8 @@ const handleChangePhoneSubmit = async () => {
|
||||
changePhoneLoading.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
// 原手机号由服务端按当前登录用户读取,前端不再回传可能已脱敏的号码。
|
||||
await userApi.updatePhone({
|
||||
oldPhone: userInfo.value.phone!,
|
||||
newPhone: changePhoneForm.newPhone,
|
||||
verificationCode: changePhoneForm.verificationCode
|
||||
})
|
||||
|
||||
@@ -9,6 +9,20 @@ import { BRAND_CONFIG } from '@/config/brand'
|
||||
const router = useRouter()
|
||||
const loading = ref(false)
|
||||
const contact = ref<ContactInfoVO | null>(null)
|
||||
const dialing = ref(false)
|
||||
|
||||
/** 平台客服拨号:点击后才单次取号,号码不落页面状态。 */
|
||||
const dialPlatform = async () => {
|
||||
dialing.value = true
|
||||
try {
|
||||
const result = await userApi.dialContact('PLATFORM')
|
||||
window.location.href = `tel:${result.dialNumber}`
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '获取客服号码失败')
|
||||
} finally {
|
||||
dialing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const loadContact = async () => {
|
||||
loading.value = true
|
||||
@@ -46,7 +60,9 @@ onMounted(loadContact)
|
||||
<section class="section-card">
|
||||
<h3>平台联系信息</h3>
|
||||
<p v-if="contact?.contactName">{{ contact.contactName }} {{ contact.roleLabel || '' }}</p>
|
||||
<p v-if="contact?.phoneAvailable && contact.phone">电话:{{ contact.phone }}</p>
|
||||
<p v-if="contact?.phoneAvailable">
|
||||
<a-button type="primary" size="small" :loading="dialing" @click="dialPlatform">拨打客服电话</a-button>
|
||||
</p>
|
||||
<p v-if="contact?.wechatAvailable && contact.wechatId">微信:{{ contact.wechatId }}</p>
|
||||
<p v-if="contact?.platformContactText">{{ contact.platformContactText }}</p>
|
||||
<p v-if="!contact">暂无可展示的客服信息,请稍后重试或通过订单详情联系服务人员。</p>
|
||||
|
||||
@@ -19,6 +19,7 @@ const reviews = ref<OrderArtistReviewVO[]>([])
|
||||
const changeRequests = ref<OrderArtistChangeRequestVO[]>([])
|
||||
const afterSales = ref<AfterSaleVO[]>([])
|
||||
const contact = ref<ContactInfoVO | null>(null)
|
||||
const dialing = ref(false)
|
||||
const quoteReply = ref('')
|
||||
const quoteSubmitting = ref(false)
|
||||
const quoteConfirming = ref(false)
|
||||
@@ -130,6 +131,20 @@ const loadRelated = async () => {
|
||||
contact.value = contactInfo
|
||||
}
|
||||
|
||||
/** 单次取号后立即拨号:不缓存号码,仅使用本次返回的 dialNumber。 */
|
||||
const dialArtist = async () => {
|
||||
if (!orderId.value) return
|
||||
dialing.value = true
|
||||
try {
|
||||
const result = await userApi.dialContact('ORDER_ARTIST', orderId.value)
|
||||
window.location.href = `tel:${result.dialNumber}`
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '获取拨号号码失败')
|
||||
} finally {
|
||||
dialing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const loadOrder = async () => {
|
||||
if (!orderId.value) {
|
||||
order.value = null
|
||||
@@ -334,7 +349,9 @@ onMounted(loadOrder)
|
||||
<section v-if="contact" class="section-card">
|
||||
<h3>联系信息</h3>
|
||||
<p>{{ contact.contactName || contact.roleLabel || '服务联系人' }}</p>
|
||||
<p v-if="contact.phoneAvailable && contact.phone">电话:{{ contact.phone }}</p>
|
||||
<p v-if="contact.phoneAvailable">
|
||||
<a-button size="small" :loading="dialing" @click="dialArtist">拨打美甲师电话</a-button>
|
||||
</p>
|
||||
<p v-if="contact.wechatAvailable && contact.wechatId">微信:{{ contact.wechatId }}</p>
|
||||
<p v-if="contact.platformContactText">{{ contact.platformContactText }}</p>
|
||||
</section>
|
||||
|
||||
@@ -238,7 +238,7 @@ const handleSendVerificationCode = async () => {
|
||||
|
||||
try {
|
||||
await runWithGlobalLoading(() => userApi.sendVerificationCode({
|
||||
phone: userPhone.value,
|
||||
// 号码由服务端按当前登录用户读取,前端只传场景,避免回传已脱敏的展示值。
|
||||
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
|
||||
}))
|
||||
message.success('验证码发送成功')
|
||||
|
||||
@@ -373,6 +373,9 @@ const editForm = reactive({
|
||||
wechatQrCode: ''
|
||||
})
|
||||
|
||||
/** 打开编辑弹窗时的联系电话原值,用于判断用户是否真实修改过(未修改则不提交该字段)。 */
|
||||
const originalContactPhone = ref('')
|
||||
|
||||
/** getDraftKey is a local helper used by this page script. */
|
||||
const getDraftKey = () => buildDraftStorageKey('profile-edit')
|
||||
|
||||
@@ -596,6 +599,7 @@ const handleEditProfile = () => {
|
||||
editForm.avatar = userInfo.value.avatar || ''
|
||||
editForm.signature = userInfo.value.signature || ''
|
||||
editForm.contactPhone = userInfo.value.contactPhone || ''
|
||||
originalContactPhone.value = editForm.contactPhone
|
||||
editForm.birthday = userInfo.value.birthday || ''
|
||||
editForm.wechatId = userInfo.value.wechatId || ''
|
||||
editForm.wechatQrCode = userInfo.value.wechatQrCode || ''
|
||||
@@ -742,15 +746,17 @@ const handleSaveProfile = async () => {
|
||||
saving.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await userApi.updateUserInfo({
|
||||
const payload = {
|
||||
nickname: editForm.nickname,
|
||||
avatar: editForm.avatar,
|
||||
signature: editForm.signature,
|
||||
contactPhone: editForm.contactPhone,
|
||||
birthday: editForm.birthday || undefined,
|
||||
wechatId: editForm.wechatId,
|
||||
wechatQrCode: editForm.wechatQrCode
|
||||
})
|
||||
wechatQrCode: editForm.wechatQrCode,
|
||||
// 只有联系电话真实变更时才提交,避免把接口回填值(可能已脱敏)原样写回
|
||||
...(editForm.contactPhone !== originalContactPhone.value ? { contactPhone: editForm.contactPhone } : {})
|
||||
}
|
||||
await userApi.updateUserInfo(payload)
|
||||
await fetchUserInfo()
|
||||
})
|
||||
message.success('资料更新成功')
|
||||
|
||||
@@ -226,16 +226,12 @@
|
||||
<p class="contact-name">{{ contactInfo.contactName || contactInfo.roleLabel || '联系人' }}</p>
|
||||
<div class="contact-row">
|
||||
<span>联系电话</span>
|
||||
<strong>{{ contactInfo.phoneAvailable ? contactInfo.phone : '暂无电话' }}</strong>
|
||||
<strong>{{ contactInfo.phoneAvailable ? '点击下方按钮获取当次号码' : '暂无电话' }}</strong>
|
||||
</div>
|
||||
<div class="contact-actions">
|
||||
<a-button v-if="contactInfo.phoneAvailable" type="primary" :href="`tel:${contactInfo.phone}`">
|
||||
<a-button v-if="contactInfo.phoneAvailable" type="primary" :loading="dialing" @click="dialManager">
|
||||
<PhoneOutlined />
|
||||
拨号
|
||||
</a-button>
|
||||
<a-button v-if="contactInfo.phoneAvailable" @click="copyToClipboard(contactInfo.phone || '', '联系电话')">
|
||||
<CopyOutlined />
|
||||
复制电话
|
||||
拨打店长电话
|
||||
</a-button>
|
||||
</div>
|
||||
<div class="contact-row">
|
||||
@@ -372,6 +368,7 @@ const contactOpen = ref(false)
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const contactInfo = ref<ContactInfoVO>({})
|
||||
const dialing = ref(false)
|
||||
/**
|
||||
* Purpose: mapOpen supports ShopDetailView.vue by holding or executing the map open page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
@@ -617,11 +614,24 @@ const openWechatContact = async () => {
|
||||
window.location.href = 'weixin://'
|
||||
}
|
||||
|
||||
/** copyContactInfo copies all available contact channels in one action. */
|
||||
/** 单次取号后立即拨号:页面不缓存号码,仅使用本次返回的 dialNumber。 */
|
||||
const dialManager = async () => {
|
||||
if (!shopInfo.value.id) return
|
||||
dialing.value = true
|
||||
try {
|
||||
const result = await userApi.dialContact('SHOP_MANAGER', shopInfo.value.id)
|
||||
window.location.href = `tel:${result.dialNumber}`
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '获取拨号号码失败')
|
||||
} finally {
|
||||
dialing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** copyContactInfo copies the WeChat channel only; phone numbers are no longer rendered or cached. */
|
||||
const copyContactInfo = async () => {
|
||||
const lines = [
|
||||
contactInfo.value.contactName || contactInfo.value.roleLabel || '联系人',
|
||||
contactInfo.value.phoneAvailable && contactInfo.value.phone ? `电话:${contactInfo.value.phone}` : '',
|
||||
contactInfo.value.wechatAvailable && contactInfo.value.wechatId ? `微信:${contactInfo.value.wechatId}` : ''
|
||||
].filter(Boolean)
|
||||
await copyToClipboard(lines.join('\n'), '联系方式')
|
||||
|
||||
@@ -144,6 +144,18 @@ module.exports = {
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* 单次拨号取号:号码不缓存,仅用于本次拨号。
|
||||
* scene: SHOP_MANAGER / ORDER_ARTIST / PRODUCT_ARTIST / PLATFORM
|
||||
*/
|
||||
dialContact(scene, targetId, artistId) {
|
||||
return request({
|
||||
url: '/contact-info/dial',
|
||||
method: 'POST',
|
||||
data: { scene, targetId, artistId }
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getShopManagerContact supports user.js by holding or executing the get shop manager contact page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
|
||||
@@ -30,6 +30,18 @@ Page({
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 平台客服拨号:点击后才单次取号,号码不保存。
|
||||
*/
|
||||
async handleDialPlatform() {
|
||||
try {
|
||||
const dial = await userApi.dialContact('PLATFORM')
|
||||
wx.makePhoneCall({ phoneNumber: dial.dialNumber })
|
||||
} catch (error) {
|
||||
wx.showToast({ title: error.message || '获取客服号码失败', icon: 'none' })
|
||||
}
|
||||
},
|
||||
|
||||
openRoute(event) {
|
||||
const route = event.currentTarget.dataset.route
|
||||
const pureRoute = String(route || '').split('?')[0]
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
<text class="section-title">平台联系信息</text>
|
||||
<block wx:if="{{contact}}">
|
||||
<text wx:if="{{contact.contactName}}" class="contact-line">{{contact.contactName}} {{contact.roleLabel || ''}}</text>
|
||||
<text wx:if="{{contact.phoneAvailable && contact.phone}}" class="contact-line">电话:{{contact.phone}}</text>
|
||||
<text wx:if="{{contact.phoneAvailable}}" class="contact-line">
|
||||
<view class="primary-btn" bindtap="handleDialPlatform">拨打客服电话</view>
|
||||
</text>
|
||||
<text wx:if="{{contact.wechatAvailable && contact.wechatId}}" class="contact-line">微信:{{contact.wechatId}}</text>
|
||||
<text wx:if="{{contact.platformContactText}}" class="contact-line">{{contact.platformContactText}}</text>
|
||||
</block>
|
||||
|
||||
@@ -131,6 +131,21 @@ Page({
|
||||
navigation.navigate('/pages/after-sales/index', { orderId: this.data.id })
|
||||
},
|
||||
|
||||
/**
|
||||
* 点击后才单次取号并拨号,页面不保存号码。
|
||||
*/
|
||||
async handleDialArtist() {
|
||||
if (!this.data.id) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const dial = await userApi.dialContact('ORDER_ARTIST', this.data.id)
|
||||
wx.makePhoneCall({ phoneNumber: dial.dialNumber })
|
||||
} catch (error) {
|
||||
wx.showToast({ title: error.message || '获取拨号号码失败', icon: 'none' })
|
||||
}
|
||||
},
|
||||
|
||||
async handleCancelOrder() {
|
||||
const confirmed = await new Promise(resolve => {
|
||||
wx.showModal({
|
||||
|
||||
@@ -51,7 +51,9 @@
|
||||
<view wx:if="{{contact}}" class="page-card contact-card">
|
||||
<text class="section-title">联系信息</text>
|
||||
<text class="contact-line">{{contact.contactName || contact.roleLabel || '服务联系人'}}</text>
|
||||
<text wx:if="{{contact.phoneAvailable && contact.phone}}" class="contact-line">电话:{{contact.phone}}</text>
|
||||
<text wx:if="{{contact.phoneAvailable}}" class="contact-line">
|
||||
<view class="soft-chip" bindtap="handleDialArtist">拨打美甲师电话</view>
|
||||
</text>
|
||||
<text wx:if="{{contact.wechatAvailable && contact.wechatId}}" class="contact-line">微信:{{contact.wechatId}}</text>
|
||||
<text wx:if="{{contact.platformContactText}}" class="contact-line">{{contact.platformContactText}}</text>
|
||||
</view>
|
||||
|
||||
@@ -739,22 +739,9 @@ Page({
|
||||
},
|
||||
|
||||
async handleChangePhoneSubmit() {
|
||||
const userInfo = this.data.userInfo || {}
|
||||
const oldPhone = String(userInfo.phone || '').trim()
|
||||
const newPhone = String(this.data.changePhoneForm.newPhone || '').trim()
|
||||
const verificationCode = String(this.data.changePhoneForm.verificationCode || '').trim()
|
||||
|
||||
/**
|
||||
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
||||
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
||||
*/
|
||||
if (!oldPhone) {
|
||||
wx.showToast({
|
||||
title: '请先绑定手机号',
|
||||
icon: 'none'
|
||||
})
|
||||
return
|
||||
}
|
||||
// 原手机号由服务端按当前登录用户取,页面展示的是脱敏值,不再回传。
|
||||
|
||||
if (!phoneRegex.test(newPhone)) {
|
||||
wx.showToast({
|
||||
@@ -782,7 +769,6 @@ Page({
|
||||
|
||||
try {
|
||||
await runWithLoading(() => userApi.updatePhone({
|
||||
oldPhone,
|
||||
newPhone,
|
||||
verificationCode
|
||||
}))
|
||||
@@ -829,8 +815,8 @@ Page({
|
||||
}
|
||||
|
||||
try {
|
||||
// 号码由服务端按当前登录用户读取,前端只传场景。
|
||||
await runWithLoading(() => authApi.sendVerificationCode({
|
||||
phone,
|
||||
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
|
||||
}))
|
||||
wx.showToast({
|
||||
|
||||
@@ -180,8 +180,8 @@ Page({
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleContactManager retrieves and shows the current shop manager contact.
|
||||
* Usage: bind it to the contact button and require login before exposing phone data.
|
||||
* Purpose: handleContactManager 点击后才单次取号并拨号,页面不再保存或展示号码。
|
||||
* Usage: 绑定到联系按钮,要求登录后由服务端按场景鉴权。
|
||||
*/
|
||||
async handleContactManager() {
|
||||
const shopInfo = this.data.shopInfo
|
||||
@@ -191,20 +191,9 @@ Page({
|
||||
try {
|
||||
const contact = await userApi.getShopManagerContact(shopInfo.id)
|
||||
this.setData({ managerContact: contact })
|
||||
if (contact && contact.phoneAvailable && contact.phone) {
|
||||
wx.showModal({
|
||||
title: contact.contactName || '店长联系方式',
|
||||
content: `${contact.roleLabel || '店长'}:${contact.phone}`,
|
||||
confirmText: '拨打',
|
||||
cancelText: '复制',
|
||||
success: res => {
|
||||
if (res.confirm) {
|
||||
wx.makePhoneCall({ phoneNumber: contact.phone })
|
||||
} else {
|
||||
wx.setClipboardData({ data: contact.phone })
|
||||
}
|
||||
}
|
||||
})
|
||||
if (contact && contact.phoneAvailable) {
|
||||
const dial = await userApi.dialContact('SHOP_MANAGER', shopInfo.id)
|
||||
wx.makePhoneCall({ phoneNumber: dial.dialNumber })
|
||||
return
|
||||
}
|
||||
wx.showToast({
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
<view class="contact-row">
|
||||
<view class="primary-btn contact-btn" bindtap="handleContactManager">联系店长</view>
|
||||
<view wx:if="{{managerContact}}" class="contact-copy">
|
||||
{{managerContact.contactName || '店长'}} · {{managerContact.phoneAvailable ? managerContact.phone : (managerContact.platformContactText || '暂无电话')}}
|
||||
{{managerContact.contactName || '店长'}} · {{managerContact.phoneAvailable ? '点击“联系店长”获取当次号码' : (managerContact.platformContactText || '暂无电话')}}
|
||||
</view>
|
||||
</view>
|
||||
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.xiaowang.jayucloud.salon.core.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 协议同意校验拦截器:在身份解析之后、业务方法之前阻断未同意当前协议版本的已登录用户。
|
||||
* 未登录请求不在此校验;判定组件故障时放行并告警,避免协议缓存/数据库异常导致全站不可用。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AgreementAcceptanceInterceptor implements HandlerInterceptor {
|
||||
|
||||
public static final int AGREEMENT_VERSION_REQUIRED_CODE = 4510;
|
||||
|
||||
public static final String AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE = "AGREEMENT_VERSION_REQUIRED";
|
||||
|
||||
private final AgreementVersionCacheService agreementVersionCacheService;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
Object userIdAttribute = request.getAttribute("userId");
|
||||
if (!(userIdAttribute instanceof Number)) {
|
||||
return true;
|
||||
}
|
||||
Long userId = ((Number) userIdAttribute).longValue();
|
||||
try {
|
||||
Map<String, String> currentVersions = agreementVersionCacheService.currentVersions();
|
||||
Map<String, String> acceptedVersions = agreementVersionCacheService.acceptedVersions(userId);
|
||||
List<String> pendingTypes = new ArrayList<>();
|
||||
for (Map.Entry<String, String> entry : currentVersions.entrySet()) {
|
||||
if (!Objects.equals(entry.getValue(), acceptedVersions.get(entry.getKey()))) {
|
||||
pendingTypes.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
if (pendingTypes.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
writeAgreementRequired(response, currentVersions, pendingTypes);
|
||||
return false;
|
||||
} catch (Exception exception) {
|
||||
// 可用性优先:协议校验只是附加门禁,Redis/DB 故障时放行主业务,记录告警供监控排查。
|
||||
log.warn("协议同意校验失败,已放行请求 path={} userId={}", request.getRequestURI(), userId, exception);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeAgreementRequired(HttpServletResponse response,
|
||||
Map<String, String> currentVersions,
|
||||
List<String> pendingTypes) throws Exception {
|
||||
String versionText = currentVersions.values().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.joining("/"));
|
||||
String message = "用户协议与隐私政策已更新(当前版本 " + versionText + "),请阅读并同意后继续使用";
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("businessCode", AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE);
|
||||
data.put("currentVersions", currentVersions);
|
||||
data.put("pendingTypes", pendingTypes);
|
||||
Result<Map<String, Object>> result = new Result<>(AGREEMENT_VERSION_REQUIRED_CODE, message, data);
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(result));
|
||||
}
|
||||
}
|
||||
+2
@@ -28,6 +28,8 @@ public class RateLimitProperties {
|
||||
|
||||
private LimitRule orderCreate = new LimitRule(10, 60);
|
||||
|
||||
private LimitRule customerDial = new LimitRule(10, 60);
|
||||
|
||||
@Data
|
||||
/**
|
||||
* Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role.
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.xiaowang.jayucloud.salon.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
/**
|
||||
* 部署环境标识。
|
||||
* 用于微信内容审核回调的跨环境路由,必须由各环境 Nacos 显式配置,缺失时启动失败。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@Validated
|
||||
@ConfigurationProperties(prefix = "jayucloud-salon.deploy")
|
||||
public class SalonDeployProperties {
|
||||
|
||||
@NotBlank
|
||||
@Pattern(regexp = "dev|sit|prod", message = "部署环境标识必须是 dev、sit 或 prod")
|
||||
private String env;
|
||||
}
|
||||
+91
-40
@@ -13,6 +13,86 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
*/
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private static final String[] AUTH_FREE_PATHS = {
|
||||
"/user/login",
|
||||
"/user/register",
|
||||
"/user/check/**",
|
||||
"/user/refresh-token",
|
||||
"/user/send-verification-code",
|
||||
"/user/phone-login",
|
||||
"/user/wechat-mini/auto-login",
|
||||
"/user/wechat-mini/phone-login",
|
||||
"/user/wechat-mini/confirm-login",
|
||||
"/user/wechat-mini/status",
|
||||
"/user/wechat-mini/quick-login",
|
||||
"/integration/wechat/content-moderation/callback",
|
||||
"/user/workbench/register/**",
|
||||
"/user/workbench/shops/available",
|
||||
"/user/reset-password-by-phone",
|
||||
"/legal-agreement/current",
|
||||
"/legal-agreement/current/**",
|
||||
"/legal-agreement/pending",
|
||||
"/api/legal-agreement/current",
|
||||
"/api/legal-agreement/current/**",
|
||||
"/api/legal-agreement/pending",
|
||||
"/product/get/**",
|
||||
"/product/list/**",
|
||||
"/comment/list/product/**",
|
||||
"/api/comment/list/product/**",
|
||||
"/nail-artist/profile/**",
|
||||
"/nail-artist/*/availability",
|
||||
"/nail-artist/*/reviews",
|
||||
"/shop/get/**",
|
||||
"/shop/trust-profile/**",
|
||||
"/shop/list",
|
||||
"/shop/list/public",
|
||||
"/shop/list/simple",
|
||||
"/tag/list/all",
|
||||
"/tag/list/filter-options",
|
||||
"/file/get-signed-url/**",
|
||||
"/admin/auth/login",
|
||||
"/admin/auth/refresh",
|
||||
"/error",
|
||||
"/health/**"
|
||||
};
|
||||
|
||||
/**
|
||||
* 协议同意门禁额外放行:同意接口、协议阅读页、账号认证类操作、外部回调与健康检查。
|
||||
* 这些路径不校验协议版本,避免版本发布后把已登录用户或外部回调锁在门外。
|
||||
*/
|
||||
private static final String[] AGREEMENT_EXTRA_FREE_PATHS = {
|
||||
"/legal-agreement/accept",
|
||||
"/api/legal-agreement/accept",
|
||||
"/legal-agreement/admin/**",
|
||||
"/api/legal-agreement/admin/**",
|
||||
"/user/logout",
|
||||
"/user/info",
|
||||
"/user/agreement-consent/**",
|
||||
"/user/switch-shop",
|
||||
"/user/relation/me",
|
||||
"/user/invite-code/resolve",
|
||||
"/user/bind-phone",
|
||||
"/user/unbind-phone",
|
||||
"/user/unbind-phone/**",
|
||||
"/user/wechat-mini/bind-phone",
|
||||
"/user/bind-email",
|
||||
"/user/password",
|
||||
"/user/phone",
|
||||
"/user/send-current-password-code",
|
||||
"/user/reset-password/**",
|
||||
"/user/upload-avatar/**",
|
||||
"/user/upload-profile-image/**",
|
||||
"/user/deactivate",
|
||||
"/legal/**",
|
||||
"/integration/**",
|
||||
"/api/integration/**",
|
||||
"/actuator/**",
|
||||
"/static/**",
|
||||
"/assets/**",
|
||||
"/index.html",
|
||||
"/favicon.ico"
|
||||
};
|
||||
|
||||
/**
|
||||
* Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
@@ -23,6 +103,10 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor;
|
||||
/**
|
||||
* Purpose: agreementAcceptanceInterceptor 在鉴权之后校验协议同意状态。
|
||||
*/
|
||||
private final AgreementAcceptanceInterceptor agreementAcceptanceInterceptor;
|
||||
|
||||
@Override
|
||||
/**
|
||||
@@ -37,45 +121,12 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
registry.addInterceptor(authInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.order(0)
|
||||
.excludePathPatterns(
|
||||
"/user/login",
|
||||
"/user/register",
|
||||
"/user/check/**",
|
||||
"/user/refresh-token",
|
||||
"/user/send-verification-code",
|
||||
"/user/phone-login",
|
||||
"/user/wechat-mini/auto-login",
|
||||
"/user/wechat-mini/phone-login",
|
||||
"/user/wechat-mini/confirm-login",
|
||||
"/user/wechat-mini/status",
|
||||
"/user/wechat-mini/quick-login",
|
||||
"/integration/wechat/content-moderation/callback",
|
||||
"/user/workbench/register/**",
|
||||
"/user/workbench/shops/available",
|
||||
"/user/reset-password-by-phone",
|
||||
"/legal-agreement/current",
|
||||
"/legal-agreement/current/**",
|
||||
"/api/legal-agreement/current",
|
||||
"/api/legal-agreement/current/**",
|
||||
"/product/get/**",
|
||||
"/product/list/**",
|
||||
"/comment/list/product/**",
|
||||
"/api/comment/list/product/**",
|
||||
"/nail-artist/profile/**",
|
||||
"/nail-artist/*/availability",
|
||||
"/nail-artist/*/reviews",
|
||||
"/shop/get/**",
|
||||
"/shop/trust-profile/**",
|
||||
"/shop/list",
|
||||
"/shop/list/public",
|
||||
"/shop/list/simple",
|
||||
"/tag/list/all",
|
||||
"/tag/list/filter-options",
|
||||
"/file/get-signed-url/**",
|
||||
"/admin/auth/login",
|
||||
"/admin/auth/refresh",
|
||||
"/error",
|
||||
"/health/**"
|
||||
);
|
||||
.excludePathPatterns(AUTH_FREE_PATHS);
|
||||
|
||||
registry.addInterceptor(agreementAcceptanceInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.order(1)
|
||||
.excludePathPatterns(AUTH_FREE_PATHS)
|
||||
.excludePathPatterns(AGREEMENT_EXTRA_FREE_PATHS);
|
||||
}
|
||||
}
|
||||
|
||||
+28
@@ -33,6 +33,8 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.CustomerDialService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
@@ -49,6 +51,7 @@ import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.validation.Valid;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
@@ -65,6 +68,7 @@ public class AdminManagerController {
|
||||
private final ProductService productService;
|
||||
private final ShopService shopService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final CustomerDialService customerDialService;
|
||||
|
||||
@GetMapping("/planning/calendar")
|
||||
@RequirePermission("schedule:view")
|
||||
@@ -179,6 +183,30 @@ public class AdminManagerController {
|
||||
return Result.success(userService.listCustomersForAppointment(page, size, keyword, shopId));
|
||||
}
|
||||
|
||||
@PostMapping("/customers/{customerId}/dial")
|
||||
@RequirePermission("user:view")
|
||||
public Result<CustomerDialVO> dialCustomer(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
@PathVariable Long customerId,
|
||||
@RequestParam(required = false) Long appointmentId,
|
||||
@RequestParam(required = false) Long orderId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
return Result.success(customerDialService.dial(currentUser, customerId, appointmentId, orderId, request));
|
||||
}
|
||||
|
||||
@PostMapping("/customers/dial")
|
||||
@RequirePermission("user:view")
|
||||
public Result<CustomerDialVO> dialCustomerForGuest(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
@RequestParam(required = false) Long customerId,
|
||||
@RequestParam(required = false) Long appointmentId,
|
||||
@RequestParam(required = false) Long orderId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
return Result.success(customerDialService.dial(currentUser, customerId, appointmentId, orderId, request));
|
||||
}
|
||||
|
||||
@GetMapping("/customers/{id}")
|
||||
@RequirePermission("user:view")
|
||||
public Result<UserVO> customer(HttpServletRequest request, @PathVariable Long id) {
|
||||
|
||||
+3
@@ -11,7 +11,10 @@ public class AppointmentCustomerOptionVO {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long id;
|
||||
private String name;
|
||||
/** 脱敏后的手机号,永不返回完整号码 */
|
||||
private String phone;
|
||||
/** 是否存在可拨打的手机号,呼叫按钮据此展示 */
|
||||
private Boolean phoneAvailable;
|
||||
private String avatar;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
|
||||
+7
-1
@@ -37,6 +37,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSu
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningCalendarSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningTodayOverviewSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningArtistCountVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningArtistVO;
|
||||
@@ -103,6 +104,7 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
private final WechatSubscribeMessageService wechatSubscribeMessageService;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Override
|
||||
public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) {
|
||||
@@ -621,7 +623,11 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId());
|
||||
vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId());
|
||||
vo.setCustomerName(customer == null ? firstNonBlank(order == null ? null : order.getCustomerNameSnapshot(), "散客") : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户"));
|
||||
vo.setCustomerPhone(customer == null ? order == null ? null : order.getCustomerPhoneSnapshot() : firstNonBlank(customer.getContactPhone(), customer.getPhone(), ""));
|
||||
String plainPhone = customer == null
|
||||
? (order == null ? null : order.getCustomerPhoneSnapshot())
|
||||
: firstNonBlank(customer.getContactPhone(), customer.getPhone(), "");
|
||||
vo.setCustomerPhone(phoneCrypto.mask(plainPhone));
|
||||
vo.setCustomerPhoneAvailable(StringUtils.hasText(plainPhone) && !plainPhone.contains("*"));
|
||||
vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId());
|
||||
vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle())
|
||||
? reservation.getProductTitle()
|
||||
|
||||
+3
@@ -11,7 +11,10 @@ public class PlanningAppointmentVO {
|
||||
private Long orderItemId;
|
||||
private Long customerId;
|
||||
private String customerName;
|
||||
/** 脱敏后的客户手机号,完整号码仅通过拨号取号端点单次获取 */
|
||||
private String customerPhone;
|
||||
/** 是否存在可拨打的手机号,呼叫按钮据此展示 */
|
||||
private Boolean customerPhoneAvailable;
|
||||
private Long productId;
|
||||
private String productTitle;
|
||||
private Long artistId;
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 拨号取号配置。
|
||||
* provider 取值:direct(直拨真实号码)或 privacy-number(隐私号码,暂未对接)。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jayucloud-salon.dial")
|
||||
public class DialProperties {
|
||||
|
||||
private String provider = "direct";
|
||||
}
|
||||
+139
-5
@@ -2,30 +2,46 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/integration/wechat/content-moderation")
|
||||
public class WechatContentModerationCallbackController {
|
||||
private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By";
|
||||
private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop";
|
||||
|
||||
private final SecureIntegrationConfigService secureIntegrationConfigService;
|
||||
private final WechatMiniProperties wechatProperties;
|
||||
private final WechatCallbackCrypto crypto;
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final IntegrationProbeService integrationProbeService;
|
||||
private final ContentModerationForwardService contentModerationForwardService;
|
||||
private final SalonDeployProperties deployProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@GetMapping("/callback")
|
||||
@@ -54,12 +70,23 @@ public class WechatContentModerationCallbackController {
|
||||
MediaType.APPLICATION_XML_VALUE,
|
||||
MediaType.TEXT_XML_VALUE
|
||||
})
|
||||
public String callback(@RequestParam("timestamp") String timestamp,
|
||||
@RequestParam("nonce") String nonce,
|
||||
public String callback(@RequestParam(value = "timestamp", required = false) String timestamp,
|
||||
@RequestParam(value = "nonce", required = false) String nonce,
|
||||
@RequestParam(value = "msg_signature", required = false) String messageSignature,
|
||||
@RequestParam(value = "signature", required = false) String signature,
|
||||
@RequestParam(value = "encrypt_type", required = false) String encryptType,
|
||||
@org.springframework.web.bind.annotation.RequestBody String body) throws Exception {
|
||||
@RequestHeader(value = "X-Moderation-Forward-By", required = false) String forwardBy,
|
||||
@RequestHeader(value = "X-Moderation-Forward-Hop", required = false) String forwardHop,
|
||||
@RequestHeader(value = "X-Timestamp", required = false) String forwardTimestamp,
|
||||
@RequestHeader(value = "X-Nonce", required = false) String forwardNonce,
|
||||
@RequestHeader(value = "X-Signature", required = false) String forwardSignature,
|
||||
@RequestBody String body) throws Exception {
|
||||
if (StringUtils.hasText(forwardBy) || StringUtils.hasText(forwardHop)) {
|
||||
return handleForwardedCallback(forwardBy, forwardHop, forwardTimestamp, forwardNonce, forwardSignature, body);
|
||||
}
|
||||
if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce)) {
|
||||
throw new IllegalArgumentException("微信审核回调缺少时间戳或随机串");
|
||||
}
|
||||
ModerationRuntimeConfig config = requireWechatConfig();
|
||||
String encrypted = extractEncryptedPayload(body);
|
||||
String expectedSignature = "aes".equalsIgnoreCase(encryptType) ? messageSignature : signature;
|
||||
@@ -90,12 +117,119 @@ public class WechatContentModerationCallbackController {
|
||||
extra = firstText(root, "extra", "Extra");
|
||||
}
|
||||
if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识");
|
||||
if (!integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) {
|
||||
contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra));
|
||||
if (claimLocally(taskId, suggest, reason, extra)) {
|
||||
return "success";
|
||||
}
|
||||
|
||||
String taskEnv = normalizeEnv(decodeTaskEnv(extra));
|
||||
String localEnv = deployProperties.getEnv();
|
||||
String forwardPayload = buildForwardPayload(taskId, suggest, reason, extra);
|
||||
if (!StringUtils.hasText(taskEnv)) {
|
||||
contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "回调 extra 缺少部署环境标识");
|
||||
log.warn("微信审核回调无法认领:extra 缺少环境标识,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
|
||||
taskId, localEnv, null);
|
||||
return "success";
|
||||
}
|
||||
if (taskEnv.equals(localEnv)) {
|
||||
contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "本环境未匹配到审核任务");
|
||||
log.warn("微信审核回调无法认领:本环境未匹配任务,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
|
||||
taskId, localEnv, taskEnv);
|
||||
return "success";
|
||||
}
|
||||
ModerationForwardConfig forwardConfig = contentModerationForwardService.runtimeConfig();
|
||||
if (!StringUtils.hasText(forwardConfig.targetFor(taskEnv))) {
|
||||
contentModerationForwardService.recordTargetMissing(taskId, localEnv, taskEnv, extra, forwardPayload);
|
||||
log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
|
||||
taskId, localEnv, taskEnv);
|
||||
return "success";
|
||||
}
|
||||
contentModerationForwardService.enqueue(taskId, localEnv, taskEnv, extra, forwardPayload);
|
||||
return "success";
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理转发进来的回调:只允许一跳,验签通过后仅在本地处理,不再二次转发。
|
||||
*/
|
||||
private String handleForwardedCallback(String forwardBy, String forwardHop, String timestamp,
|
||||
String nonce, String signature, String body) {
|
||||
if (!contentModerationForwardService.verifySignature(timestamp, nonce, signature, body)) {
|
||||
throw new IllegalArgumentException("跨环境转发签名校验失败");
|
||||
}
|
||||
String taskId;
|
||||
String suggest;
|
||||
String reason;
|
||||
String extra;
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(body == null ? "" : body);
|
||||
taskId = firstText(root, "trace_id", "traceId", "task_id");
|
||||
suggest = firstText(root, "suggest", "Suggest");
|
||||
if (!StringUtils.hasText(suggest)) suggest = "review";
|
||||
reason = firstText(root, "reason", "errmsg");
|
||||
if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调";
|
||||
extra = firstText(root, "extra", "Extra");
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalArgumentException("跨环境转发报文无法解析");
|
||||
}
|
||||
if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("跨环境转发报文缺少任务标识");
|
||||
|
||||
String hopText = forwardHop == null ? "1" : forwardHop.trim();
|
||||
int hop;
|
||||
try {
|
||||
hop = Integer.parseInt(hopText);
|
||||
} catch (NumberFormatException exception) {
|
||||
hop = 2;
|
||||
}
|
||||
String localEnv = deployProperties.getEnv();
|
||||
String sourceEnv = normalizeEnv(forwardBy);
|
||||
if (hop > 1 || (StringUtils.hasText(sourceEnv) && sourceEnv.equals(localEnv))) {
|
||||
contentModerationForwardService.recordUnclaimed(taskId, extra, body,
|
||||
"检测到转发环路或超过一跳,已丢弃");
|
||||
log.warn("微信审核回调转发被丢弃:环路或超过一跳,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
|
||||
taskId, sourceEnv, localEnv, hop);
|
||||
return "success";
|
||||
}
|
||||
log.info("收到跨环境转发的微信审核回调,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
|
||||
taskId, sourceEnv, localEnv, hop);
|
||||
if (!claimLocally(taskId, suggest, reason, extra)) {
|
||||
contentModerationForwardService.recordUnclaimed(taskId, extra, body, "转发目标环境仍未匹配到审核任务");
|
||||
log.warn("跨环境转发的微信审核回调未匹配到本地任务,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
|
||||
taskId, sourceEnv, localEnv, hop);
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
private boolean claimLocally(String taskId, String suggest, String reason, String extra) {
|
||||
if (integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) {
|
||||
return true;
|
||||
}
|
||||
return contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra));
|
||||
}
|
||||
|
||||
private String buildForwardPayload(String taskId, String suggest, String reason, String extra) {
|
||||
ObjectNode payload = objectMapper.createObjectNode();
|
||||
payload.put("trace_id", taskId);
|
||||
payload.put("suggest", suggest);
|
||||
payload.put("reason", reason);
|
||||
if (StringUtils.hasText(extra)) payload.put("extra", extra);
|
||||
return payload.toString();
|
||||
}
|
||||
|
||||
private String decodeTaskEnv(String extra) {
|
||||
if (!StringUtils.hasText(extra)) return null;
|
||||
try {
|
||||
JsonNode payload = objectMapper.readTree(extra);
|
||||
return firstText(payload, "env");
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeEnv(String value) {
|
||||
if (!StringUtils.hasText(value)) return null;
|
||||
String normalized = value.trim().toLowerCase(Locale.ROOT);
|
||||
return Arrays.asList("dev", "sit", "prod").contains(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
private String decodeSourceEnvVersion(String extra) {
|
||||
if (!StringUtils.hasText(extra)) return null;
|
||||
try {
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
|
||||
|
||||
/**
|
||||
* 拨号返回模式。
|
||||
*/
|
||||
public final class DialMode {
|
||||
|
||||
public static final String DIRECT = "DIRECT";
|
||||
|
||||
public static final String PRIVACY_NUMBER = "PRIVACY_NUMBER";
|
||||
|
||||
private DialMode() {
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
|
||||
|
||||
/**
|
||||
* 单次取号结果,仅在本次响应中返回,不落库、不写日志、不缓存。
|
||||
*/
|
||||
public class DialTarget {
|
||||
|
||||
private final String mode;
|
||||
private final String dialNumber;
|
||||
private final int expiresInSeconds;
|
||||
|
||||
public DialTarget(String mode, String dialNumber, int expiresInSeconds) {
|
||||
this.mode = mode;
|
||||
this.dialNumber = dialNumber;
|
||||
this.expiresInSeconds = expiresInSeconds;
|
||||
}
|
||||
|
||||
public String getMode() {
|
||||
return mode;
|
||||
}
|
||||
|
||||
public String getDialNumber() {
|
||||
return dialNumber;
|
||||
}
|
||||
|
||||
public int getExpiresInSeconds() {
|
||||
return expiresInSeconds;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
|
||||
/**
|
||||
* 拨号目标渠道。不同渠道返回不同的号码类型,调用方不得自行降级为真实号码。
|
||||
*/
|
||||
public interface DialTargetProvider {
|
||||
|
||||
/**
|
||||
* 配置项中使用的渠道标识,例如 direct、privacy-number。
|
||||
*/
|
||||
String providerKey();
|
||||
|
||||
/**
|
||||
* 解析本次拨号目标。
|
||||
*/
|
||||
DialTarget resolve(UserDO customer, OrderDO order);
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 直拨渠道:实时读取客户档案中的号码,仅在本次响应返回。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DirectDialTargetProvider implements DialTargetProvider {
|
||||
|
||||
public static final int NUMBER_UNAVAILABLE_CODE = 422;
|
||||
|
||||
public static final String NUMBER_UNAVAILABLE_BUSINESS_CODE = "DIAL_NUMBER_UNAVAILABLE";
|
||||
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Override
|
||||
public String providerKey() {
|
||||
return "direct";
|
||||
}
|
||||
|
||||
@Override
|
||||
public DialTarget resolve(UserDO customer, OrderDO order) {
|
||||
String plainPhone = resolvePlainPhone(customer, order);
|
||||
if (!StringUtils.hasText(plainPhone) || plainPhone.contains("*")) {
|
||||
throw new BusinessException(NUMBER_UNAVAILABLE_CODE,
|
||||
"该预约/订单未登记可拨打的手机号(" + NUMBER_UNAVAILABLE_BUSINESS_CODE + ")");
|
||||
}
|
||||
return new DialTarget(DialMode.DIRECT, plainPhone.trim(), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 号码来源优先级:订单/预约上的客户手机号快照优先,其次客户档案。
|
||||
*/
|
||||
private String resolvePlainPhone(UserDO customer, OrderDO order) {
|
||||
if (order != null && StringUtils.hasText(order.getCustomerPhoneSnapshot())) {
|
||||
String snapshot = phoneCrypto.decrypt(order.getCustomerPhoneSnapshot());
|
||||
if (StringUtils.hasText(snapshot)) {
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
if (customer != null) {
|
||||
if (StringUtils.hasText(customer.getContactPhone())) {
|
||||
String contactPhone = phoneCrypto.decrypt(customer.getContactPhone());
|
||||
if (StringUtils.hasText(contactPhone)) {
|
||||
return contactPhone;
|
||||
}
|
||||
}
|
||||
if (StringUtils.hasText(customer.getPhone())) {
|
||||
String phone = phoneCrypto.decrypt(customer.getPhone());
|
||||
if (StringUtils.hasText(phone)) {
|
||||
return phone;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 隐私号码占位渠道:未对接时明确报错,绝不静默回退为真实号码。
|
||||
*/
|
||||
@Component
|
||||
public class PlaceholderPrivacyNumberProvider implements DialTargetProvider {
|
||||
|
||||
public static final int NOT_CONFIGURED_CODE = 4250;
|
||||
|
||||
public static final String NOT_CONFIGURED_BUSINESS_CODE = "DIAL_PRIVACY_NUMBER_NOT_CONFIGURED";
|
||||
|
||||
@Override
|
||||
public String providerKey() {
|
||||
return "privacy-number";
|
||||
}
|
||||
|
||||
@Override
|
||||
public DialTarget resolve(UserDO customer, OrderDO order) {
|
||||
throw new BusinessException(NOT_CONFIGURED_CODE,
|
||||
"隐私号码服务未配置(" + NOT_CONFIGURED_BUSINESS_CODE + "),请联系平台开通");
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
@@ -26,16 +27,19 @@ public class WechatContentModerationProvider implements ContentModerationProvide
|
||||
private final ObjectMapper objectMapper;
|
||||
private final WechatMiniClientService wechatMiniClientService;
|
||||
private final ContentModerationProperties properties;
|
||||
private final SalonDeployProperties deployProperties;
|
||||
|
||||
public WechatContentModerationProvider(
|
||||
@Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate,
|
||||
ObjectMapper objectMapper,
|
||||
WechatMiniClientService wechatMiniClientService,
|
||||
ContentModerationProperties properties) {
|
||||
ContentModerationProperties properties,
|
||||
SalonDeployProperties deployProperties) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.objectMapper = objectMapper;
|
||||
this.wechatMiniClientService = wechatMiniClientService;
|
||||
this.properties = properties;
|
||||
this.deployProperties = deployProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -67,6 +71,7 @@ public class WechatContentModerationProvider implements ContentModerationProvide
|
||||
|
||||
public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) {
|
||||
Map<String, String> extra = new LinkedHashMap<>();
|
||||
extra.put("env", deployProperties.getEnv());
|
||||
extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion));
|
||||
extra.put("probeId", probeId);
|
||||
try {
|
||||
@@ -103,8 +108,11 @@ public class WechatContentModerationProvider implements ContentModerationProvide
|
||||
if (!"develop".equals(envVersion) && !"trial".equals(envVersion) && !"release".equals(envVersion)) {
|
||||
envVersion = "UNKNOWN";
|
||||
}
|
||||
Map<String, String> extra = new LinkedHashMap<>();
|
||||
extra.put("env", deployProperties.getEnv());
|
||||
extra.put("envVersion", envVersion);
|
||||
try {
|
||||
return objectMapper.writeValueAsString(Map.of("envVersion", envVersion));
|
||||
return objectMapper.writeValueAsString(extra);
|
||||
} catch (java.io.IOException exception) {
|
||||
throw new IllegalStateException("无法编码微信审核来源版本", exception);
|
||||
}
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.service;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 微信异步图片审核回调的跨环境转发。
|
||||
*/
|
||||
public interface ContentModerationForwardService {
|
||||
|
||||
ModerationForwardConfig runtimeConfig();
|
||||
|
||||
List<ModerationForwardRecordVO> listRecent(int limit);
|
||||
|
||||
/**
|
||||
* 记录无法认领的回调(extra 缺失或指向本环境但本地没有任务),不自动重试。
|
||||
*/
|
||||
void recordUnclaimed(String traceId, String extraJson, String payload, String note);
|
||||
|
||||
/**
|
||||
* 记录目标环境未配置的回调,不自动重试,配置补齐后可由补偿任务重放。
|
||||
*/
|
||||
void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload);
|
||||
|
||||
/**
|
||||
* 落库为 PENDING 并异步转发,确保微信回调在 5 秒内拿到 success。
|
||||
*/
|
||||
void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload);
|
||||
|
||||
/**
|
||||
* 重放到期的 RETRY 记录,最多 5 次,指数退避。
|
||||
*/
|
||||
int retryPending();
|
||||
|
||||
/**
|
||||
* 转发配置补齐后,把对应目标环境下的 TARGET_MISSING 记录重新排队。
|
||||
*/
|
||||
int requeueConfiguredTargets();
|
||||
|
||||
/**
|
||||
* 校验转发请求的 HMAC 签名、时间窗与 nonce 防重放。
|
||||
*/
|
||||
boolean verifySignature(String timestamp, String nonce, String signature, String body);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.service;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 客户拨号取号服务:按门店范围与订单上下文单次授权,号码不落库、不写日志、不缓存。
|
||||
*/
|
||||
public interface CustomerDialService {
|
||||
|
||||
CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request);
|
||||
}
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ContentModerationForwardServiceImpl implements ContentModerationForwardService {
|
||||
private static final String STATUS_PENDING = "PENDING";
|
||||
private static final String STATUS_SUCCESS = "SUCCESS";
|
||||
private static final String STATUS_RETRY = "RETRY";
|
||||
private static final String STATUS_FAILED = "FAILED";
|
||||
private static final String STATUS_NO_ENV = "NO_ENV";
|
||||
private static final String STATUS_TARGET_MISSING = "TARGET_MISSING";
|
||||
|
||||
private static final int MAX_RETRY = 5;
|
||||
private static final long SIGNATURE_WINDOW_SECONDS = 300;
|
||||
private static final long NONCE_TTL_SECONDS = 600;
|
||||
private static final String NONCE_KEY_PREFIX = "salon:content-moderation:forward:nonce:";
|
||||
private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By";
|
||||
private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop";
|
||||
|
||||
private static final AtomicInteger THREAD_INDEX = new AtomicInteger(1);
|
||||
private static final ExecutorService FORWARD_EXECUTOR = Executors.newFixedThreadPool(2, new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable runnable) {
|
||||
Thread thread = new Thread(runnable, "moderation-forward-" + THREAD_INDEX.getAndIncrement());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}
|
||||
});
|
||||
|
||||
private final ModerationCallbackForwardMapper forwardMapper;
|
||||
private final SecureIntegrationConfigService secureIntegrationConfigService;
|
||||
private final SalonDeployProperties deployProperties;
|
||||
private final RedisTemplate<String, Object> redisTemplate;
|
||||
private final ModerationForwardHttpClient forwardHttpClient;
|
||||
|
||||
@Override
|
||||
public ModerationForwardConfig runtimeConfig() {
|
||||
return secureIntegrationConfigService.getModerationForwardConfig();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ModerationForwardRecordVO> listRecent(int limit) {
|
||||
int size = limit <= 0 ? 10 : Math.min(limit, 50);
|
||||
List<ModerationCallbackForwardDO> rows = forwardMapper.selectList(new LambdaQueryWrapper<ModerationCallbackForwardDO>()
|
||||
.orderByDesc(ModerationCallbackForwardDO::getCreatedAt)
|
||||
.last("LIMIT " + size));
|
||||
return rows.stream().map(this::toVO).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordUnclaimed(String traceId, String extraJson, String payload, String note) {
|
||||
if (!StringUtils.hasText(traceId)) {
|
||||
log.warn("微信审核回调无法认领且缺少任务标识,note={}", note);
|
||||
return;
|
||||
}
|
||||
log.warn("微信审核回调无法认领,traceId={}, sourceEnv={}, targetEnv={}, hop=0, note={}",
|
||||
traceId, deployProperties.getEnv(), null, note);
|
||||
ModerationCallbackForwardDO row = build(traceId, deployProperties.getEnv(), null, extraJson, payload, STATUS_NO_ENV, note);
|
||||
saveQuietly(row);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) {
|
||||
log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
|
||||
traceId, sourceEnv, targetEnv);
|
||||
ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload,
|
||||
STATUS_TARGET_MISSING, "目标环境未配置转发地址");
|
||||
saveQuietly(row);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) {
|
||||
ModerationCallbackForwardDO existing = findByTrace(traceId);
|
||||
if (existing != null) {
|
||||
log.info("微信审核回调转发已存在记录,traceId={}, sourceEnv={}, targetEnv={}, status={}",
|
||||
traceId, sourceEnv, targetEnv, existing.getStatus());
|
||||
return;
|
||||
}
|
||||
ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload, STATUS_PENDING, null);
|
||||
if (!saveQuietly(row)) return;
|
||||
log.info("微信审核回调进入跨环境转发,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
|
||||
traceId, sourceEnv, targetEnv);
|
||||
FORWARD_EXECUTOR.execute(() -> dispatchById(row.getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Scheduled(fixedDelay = 60000)
|
||||
public int retryPending() {
|
||||
List<ModerationCallbackForwardDO> rows = forwardMapper.selectList(new LambdaQueryWrapper<ModerationCallbackForwardDO>()
|
||||
.eq(ModerationCallbackForwardDO::getStatus, STATUS_RETRY)
|
||||
.lt(ModerationCallbackForwardDO::getRetryCount, MAX_RETRY)
|
||||
.orderByAsc(ModerationCallbackForwardDO::getId)
|
||||
.last("LIMIT 50"));
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int attempted = 0;
|
||||
for (ModerationCallbackForwardDO row : rows) {
|
||||
if (!backoffElapsed(row, now)) continue;
|
||||
attempted++;
|
||||
dispatchById(row.getId());
|
||||
}
|
||||
return attempted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int requeueConfiguredTargets() {
|
||||
ModerationForwardConfig config = runtimeConfig();
|
||||
if (!config.ready() || config.getTargets() == null || config.getTargets().isEmpty()) return 0;
|
||||
List<String> configuredEnvs = config.getTargets().entrySet().stream()
|
||||
.filter(entry -> StringUtils.hasText(entry.getValue()))
|
||||
.map(Map.Entry::getKey)
|
||||
.toList();
|
||||
if (configuredEnvs.isEmpty()) return 0;
|
||||
return forwardMapper.update(null, new UpdateWrapper<ModerationCallbackForwardDO>()
|
||||
.eq("status", STATUS_TARGET_MISSING)
|
||||
.in("target_env", configuredEnvs)
|
||||
.set("status", STATUS_RETRY)
|
||||
.set("retry_count", 0)
|
||||
.set("last_error", null)
|
||||
.set("updated_at", LocalDateTime.now()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verifySignature(String timestamp, String nonce, String signature, String body) {
|
||||
if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) return false;
|
||||
ModerationForwardConfig config = runtimeConfig();
|
||||
if (!config.ready()) return false;
|
||||
long epochSeconds;
|
||||
try {
|
||||
epochSeconds = Long.parseLong(timestamp.trim());
|
||||
} catch (NumberFormatException exception) {
|
||||
return false;
|
||||
}
|
||||
if (Math.abs(System.currentTimeMillis() / 1000 - epochSeconds) > SIGNATURE_WINDOW_SECONDS) return false;
|
||||
if (!reserveNonce(nonce.trim())) return false;
|
||||
String expected = sign(config.getSecret(), timestamp.trim(), nonce.trim(), body == null ? "" : body);
|
||||
return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
|
||||
signature.trim().toLowerCase(java.util.Locale.ROOT).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private void dispatchById(Long id) {
|
||||
ModerationCallbackForwardDO row = forwardMapper.selectById(id);
|
||||
if (row == null || STATUS_SUCCESS.equals(row.getStatus())) return;
|
||||
ModerationForwardConfig config = runtimeConfig();
|
||||
if (!config.ready()) {
|
||||
markFailed(row, "跨环境转发未启用或共享密钥缺失", false);
|
||||
return;
|
||||
}
|
||||
String target = config.targetFor(row.getTargetEnv());
|
||||
if (!StringUtils.hasText(target)) {
|
||||
row.setStatus(STATUS_TARGET_MISSING);
|
||||
row.setLastError("目标环境未配置转发地址");
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
forwardMapper.updateById(row);
|
||||
log.warn("微信审核回调转发目标缺失,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
|
||||
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
||||
String nonce = UUID.randomUUID().toString().replace("-", "");
|
||||
String signature = sign(config.getSecret(), timestamp, nonce, row.getPayload() == null ? "" : row.getPayload());
|
||||
Map<String, String> headers = new java.util.HashMap<>();
|
||||
headers.put(FORWARD_BY_HEADER, deployProperties.getEnv());
|
||||
headers.put(FORWARD_HOP_HEADER, "1");
|
||||
headers.put("X-Timestamp", timestamp);
|
||||
headers.put("X-Nonce", nonce);
|
||||
headers.put("X-Signature", signature);
|
||||
boolean accepted = forwardHttpClient.post(target, row.getPayload(), headers);
|
||||
if (accepted) {
|
||||
row.setStatus(STATUS_SUCCESS);
|
||||
row.setLastError(null);
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
forwardMapper.updateById(row);
|
||||
log.info("微信审核回调跨环境转发成功,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
|
||||
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
|
||||
} else {
|
||||
markRetry(row, "目标环境返回异常状态");
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
markRetry(row, "目标环境不可达或请求失败");
|
||||
}
|
||||
}
|
||||
|
||||
private void markRetry(ModerationCallbackForwardDO row, String error) {
|
||||
int retries = (row.getRetryCount() == null ? 0 : row.getRetryCount()) + 1;
|
||||
row.setRetryCount(retries);
|
||||
row.setLastError(clip(error, 500));
|
||||
row.setStatus(retries >= MAX_RETRY ? STATUS_FAILED : STATUS_RETRY);
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
forwardMapper.updateById(row);
|
||||
log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, retryCount={}, status={}",
|
||||
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv(), retries, row.getStatus());
|
||||
}
|
||||
|
||||
private void markFailed(ModerationCallbackForwardDO row, String error, boolean retry) {
|
||||
if (retry) {
|
||||
markRetry(row, error);
|
||||
return;
|
||||
}
|
||||
row.setStatus(STATUS_FAILED);
|
||||
row.setLastError(clip(error, 500));
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
forwardMapper.updateById(row);
|
||||
log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, status=FAILED",
|
||||
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
|
||||
}
|
||||
|
||||
private boolean backoffElapsed(ModerationCallbackForwardDO row, LocalDateTime now) {
|
||||
if (row.getUpdatedAt() == null) return true;
|
||||
long minutes = 1L << Math.min(Math.max(row.getRetryCount() == null ? 0 : row.getRetryCount(), 0), 5);
|
||||
return !row.getUpdatedAt().plusMinutes(minutes).isAfter(now);
|
||||
}
|
||||
|
||||
private boolean reserveNonce(String nonce) {
|
||||
try {
|
||||
Boolean fresh = redisTemplate.opsForValue().setIfAbsent(NONCE_KEY_PREFIX + nonce, "1",
|
||||
Duration.ofSeconds(NONCE_TTL_SECONDS));
|
||||
return Boolean.TRUE.equals(fresh);
|
||||
} catch (RuntimeException exception) {
|
||||
log.warn("转发 nonce 防重放写入失败,按拒绝处理");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String sign(String secret, String timestamp, String nonce, String body) {
|
||||
try {
|
||||
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
String canonical = timestamp + "\n" + nonce + "\n" + sha256Hex(body);
|
||||
return hex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (java.security.GeneralSecurityException exception) {
|
||||
throw new IllegalStateException("转发签名计算失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String sha256Hex(String value) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return hex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (java.security.NoSuchAlgorithmException exception) {
|
||||
throw new IllegalStateException("无法计算报文摘要", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String hex(byte[] bytes) {
|
||||
StringBuilder builder = new StringBuilder(bytes.length * 2);
|
||||
for (byte item : bytes) builder.append(String.format("%02x", item));
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private ModerationCallbackForwardDO build(String traceId, String sourceEnv, String targetEnv,
|
||||
String extraJson, String payload, String status, String error) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
|
||||
row.setTraceId(clip(traceId, 128));
|
||||
row.setSourceEnv(clip(sourceEnv, 16));
|
||||
row.setTargetEnv(StringUtils.hasText(targetEnv) ? clip(targetEnv, 16) : null);
|
||||
row.setExtraJson(clip(extraJson, 256));
|
||||
row.setPayload(payload);
|
||||
row.setStatus(status);
|
||||
row.setRetryCount(0);
|
||||
row.setLastError(clip(error, 500));
|
||||
row.setCreatedAt(now);
|
||||
row.setUpdatedAt(now);
|
||||
return row;
|
||||
}
|
||||
|
||||
private boolean saveQuietly(ModerationCallbackForwardDO row) {
|
||||
try {
|
||||
forwardMapper.insert(row);
|
||||
return true;
|
||||
} catch (DuplicateKeyException exception) {
|
||||
log.info("微信审核回调转发记录已存在,traceId={}", row.getTraceId());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private ModerationCallbackForwardDO findByTrace(String traceId) {
|
||||
if (!StringUtils.hasText(traceId)) return null;
|
||||
return forwardMapper.selectOne(new LambdaQueryWrapper<ModerationCallbackForwardDO>()
|
||||
.eq(ModerationCallbackForwardDO::getTraceId, traceId)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
private ModerationForwardRecordVO toVO(ModerationCallbackForwardDO row) {
|
||||
ModerationForwardRecordVO vo = new ModerationForwardRecordVO();
|
||||
vo.setId(row.getId());
|
||||
vo.setTraceId(row.getTraceId());
|
||||
vo.setSourceEnv(row.getSourceEnv());
|
||||
vo.setTargetEnv(row.getTargetEnv());
|
||||
vo.setStatus(row.getStatus());
|
||||
vo.setRetryCount(row.getRetryCount());
|
||||
vo.setLastError(row.getLastError());
|
||||
vo.setCreatedAt(row.getCreatedAt());
|
||||
vo.setUpdatedAt(row.getUpdatedAt());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private String clip(String value, int max) {
|
||||
if (!StringUtils.hasText(value)) return null;
|
||||
String trimmed = value.trim();
|
||||
return trimmed.length() <= max ? trimmed : trimmed.substring(0, max);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
FORWARD_EXECUTOR.shutdownNow();
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO;
|
||||
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.privacy.config.DialProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTarget;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTargetProvider;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.CustomerDialService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 客户拨号取号实现:先校验门店范围与订单归属,再按配置渠道单次取号并记录审计。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CustomerDialServiceImpl implements CustomerDialService {
|
||||
|
||||
private static final String AUDIT_ACTION = SecurityAuditActions.CUSTOMER_DIAL;
|
||||
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final UserService userService;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final RequestThrottleService requestThrottleService;
|
||||
private final SecurityAuditSupport securityAuditSupport;
|
||||
private final DialProperties dialProperties;
|
||||
private final List<DialTargetProvider> providers;
|
||||
|
||||
@Override
|
||||
public CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request) {
|
||||
adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再拨号");
|
||||
Long currentShopId = currentUser.getShopId();
|
||||
requestThrottleService.checkCustomerDial(request, currentUser.getId());
|
||||
|
||||
if (customerId == null && appointmentId == null && orderId == null) {
|
||||
throw new BusinessException(400, "请提供预约或订单信息后再拨号(DIAL_TARGET_REQUIRED)");
|
||||
}
|
||||
|
||||
OrderDO order = null;
|
||||
if (appointmentId != null) {
|
||||
OrderItemDO item = orderItemMapper.selectById(appointmentId);
|
||||
if (item == null || Objects.equals(1, item.getIsDelete())) {
|
||||
throw new BusinessException(404, "预约不存在");
|
||||
}
|
||||
order = orderMapper.selectById(item.getOrderId());
|
||||
if (order == null || Objects.equals(1, order.getIsDelete())) {
|
||||
throw new BusinessException(404, "预约关联订单不存在");
|
||||
}
|
||||
}
|
||||
if (orderId != null) {
|
||||
if (order != null && !Objects.equals(orderId, order.getId())) {
|
||||
throw new BusinessException(403, "预约与订单不匹配,或无权拨打");
|
||||
}
|
||||
if (order == null) {
|
||||
order = orderMapper.selectById(orderId);
|
||||
if (order == null || Objects.equals(1, order.getIsDelete())) {
|
||||
throw new BusinessException(404, "订单不存在");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (order != null && !Objects.equals(currentShopId, order.getShopId())) {
|
||||
throw new BusinessException(403, "无权拨打其他店铺预约/订单客户");
|
||||
}
|
||||
|
||||
UserDO customer = resolveCustomer(currentUser, customerId, order);
|
||||
Long auditCustomerId = customer == null ? null : customer.getId();
|
||||
|
||||
DialTargetProvider provider = resolveProvider();
|
||||
String reason = "customerId=" + auditCustomerId
|
||||
+ ";appointmentId=" + appointmentId
|
||||
+ ";orderId=" + (order == null ? null : order.getId())
|
||||
+ ";provider=" + provider.providerKey();
|
||||
try {
|
||||
DialTarget target = provider.resolve(customer, order);
|
||||
securityAuditSupport.success(request, AUDIT_ACTION, reason + ";mode=" + target.getMode() + ";result=SUCCESS");
|
||||
CustomerDialVO vo = new CustomerDialVO();
|
||||
vo.setMode(target.getMode());
|
||||
vo.setDialNumber(target.getDialNumber());
|
||||
vo.setExpiresInSeconds(target.getExpiresInSeconds());
|
||||
return vo;
|
||||
} catch (BusinessException exception) {
|
||||
securityAuditSupport.fail(request, AUDIT_ACTION,
|
||||
reason + ";result=FAIL;errorCode=" + exception.getCode());
|
||||
throw exception;
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, AUDIT_ACTION,
|
||||
reason + ";result=FAIL;errorType=" + exception.getClass().getSimpleName());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析目标客户:优先使用显式 customerId,其次订单关联客户;散客预约返回 null,不要求客户有账号。
|
||||
*/
|
||||
private UserDO resolveCustomer(UserDO currentUser, Long customerId, OrderDO order) {
|
||||
Long targetCustomerId = customerId;
|
||||
if (targetCustomerId == null && order != null) {
|
||||
targetCustomerId = order.getUserId();
|
||||
}
|
||||
if (targetCustomerId == null) {
|
||||
return null;
|
||||
}
|
||||
if (order != null && !Objects.equals(targetCustomerId, order.getUserId())) {
|
||||
throw new BusinessException(403, "该客户与预约/订单不匹配,或无权拨打");
|
||||
}
|
||||
UserDO customer = userService.getById(targetCustomerId);
|
||||
if (customer == null || Objects.equals(1, customer.getIsDelete()) || !Objects.equals(0, customer.getType())) {
|
||||
throw new BusinessException(404, "客户不存在");
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, targetCustomerId, "无权拨打其他店铺客户");
|
||||
return customer;
|
||||
}
|
||||
|
||||
private DialTargetProvider resolveProvider() {
|
||||
String configured = StringUtils.hasText(dialProperties.getProvider())
|
||||
? dialProperties.getProvider().trim()
|
||||
: "direct";
|
||||
for (DialTargetProvider provider : providers) {
|
||||
if (configured.equalsIgnoreCase(provider.providerKey())) {
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
throw new BusinessException(500, "拨号渠道配置无效(jayucloud-salon.dial.provider=" + configured + ")");
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.support;
|
||||
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 跨环境审核回调转发客户端,固定 3 秒超时,失败以异常抛出由上层登记重试。
|
||||
*/
|
||||
@Component
|
||||
public class ModerationForwardHttpClient {
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
public ModerationForwardHttpClient() {
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(3000);
|
||||
factory.setReadTimeout(3000);
|
||||
this.restTemplate = new RestTemplate(factory);
|
||||
}
|
||||
|
||||
public boolean post(String url, String body, Map<String, String> headers) {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.forEach(httpHeaders::set);
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(url, new HttpEntity<>(body, httpHeaders), String.class);
|
||||
return response.getStatusCode().is2xxSuccessful();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 单次拨号取号响应。
|
||||
*/
|
||||
@Data
|
||||
public class CustomerDialVO {
|
||||
|
||||
/** DIRECT:真实号码;PRIVACY_NUMBER:隐私号码 */
|
||||
private String mode;
|
||||
|
||||
/** 本次可拨打的号码,仅用于当前客户端一次性拨号 */
|
||||
private String dialNumber;
|
||||
|
||||
/** 号码有效秒数,DIRECT 为 0 表示不设时效 */
|
||||
private Integer expiresInSeconds;
|
||||
}
|
||||
+1
@@ -108,6 +108,7 @@ public final class SecurityAuditActions {
|
||||
public static final String ANALYTICS_VIEW = "ANALYTICS_VIEW";
|
||||
public static final String PERFORMANCE_VIEW = "PERFORMANCE_VIEW";
|
||||
public static final String SECURE_CONFIG_UPDATE = "SECURE_CONFIG_UPDATE";
|
||||
public static final String CUSTOMER_DIAL = "CUSTOMER_DIAL";
|
||||
|
||||
private SecurityAuditActions() {
|
||||
}
|
||||
|
||||
+28
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
|
||||
@@ -31,6 +32,7 @@ import java.util.List;
|
||||
public class AdminSecureIntegrationConfigController {
|
||||
private final SecureIntegrationConfigService secureIntegrationConfigService;
|
||||
private final IntegrationProbeService integrationProbeService;
|
||||
private final ContentModerationForwardService contentModerationForwardService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final SecurityAuditSupport securityAuditSupport;
|
||||
|
||||
@@ -40,6 +42,7 @@ public class AdminSecureIntegrationConfigController {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser);
|
||||
config.setProbeResults(integrationProbeService.listLatest(currentUser));
|
||||
config.setModerationForwardRecent(contentModerationForwardService.listRecent(10));
|
||||
return Result.success(config);
|
||||
}
|
||||
|
||||
@@ -82,6 +85,31 @@ public class AdminSecureIntegrationConfigController {
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/content-moderation-forward")
|
||||
@RequirePermission("messagehub:config:manage")
|
||||
@OperationGuard(action = "secure-moderation-forward-config-save", ttlSeconds = 5, message = "跨环境转发设置正在保存,请勿重复提交")
|
||||
public Result<SecureIntegrationConfigVO> saveModerationForwardConfig(HttpServletRequest request,
|
||||
@Valid @RequestBody SecureIntegrationConfigDTO dto) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
try {
|
||||
secureIntegrationConfigService.saveModerationForwardConfig(currentUser, dto);
|
||||
int requeued = contentModerationForwardService.requeueConfiguredTargets();
|
||||
if (requeued > 0) {
|
||||
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
|
||||
"section=CONTENT_MODERATION_FORWARD,requeued=" + requeued);
|
||||
} else {
|
||||
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
|
||||
"section=CONTENT_MODERATION_FORWARD");
|
||||
}
|
||||
SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser);
|
||||
config.setModerationForwardRecent(contentModerationForwardService.listRecent(10));
|
||||
return Result.success(config);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=CONTENT_MODERATION_FORWARD");
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/probe-results")
|
||||
@RequirePermission("messagehub:config:manage")
|
||||
public Result<List<IntegrationProbeResultVO>> listProbeResults(HttpServletRequest request) {
|
||||
|
||||
+28
@@ -6,9 +6,11 @@ import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.dto.LegalAgreementDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -47,6 +49,10 @@ public class LegalAgreementController {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final RequestThrottleService requestThrottleService;
|
||||
/**
|
||||
* Purpose: agreementVersionCacheService 在同意成功后清除该用户的协议缓存。
|
||||
*/
|
||||
private final AgreementVersionCacheService agreementVersionCacheService;
|
||||
|
||||
@GetMapping("/current")
|
||||
/**
|
||||
@@ -68,6 +74,28 @@ public class LegalAgreementController {
|
||||
return Result.success(legalAgreementService.getCurrentAgreement(type));
|
||||
}
|
||||
|
||||
@GetMapping("/pending")
|
||||
/**
|
||||
* Purpose: pending 返回当前协议版本;登录用户额外返回是否已同意新版本。免登录只返回当前版本。
|
||||
*/
|
||||
public Result<AgreementPendingVO> pending(HttpServletRequest request) {
|
||||
requestThrottleService.checkAgreementRead(request, "PENDING");
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(legalAgreementService.getPendingAgreements(userId));
|
||||
}
|
||||
|
||||
@PostMapping("/accept")
|
||||
/**
|
||||
* Purpose: accept 记录登录用户对当前发布协议版本的同意。
|
||||
*/
|
||||
public Result<AgreementPendingVO> accept(HttpServletRequest request,
|
||||
@RequestParam(required = false) String clientType) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
legalAgreementService.acceptCurrentAgreements(userId, clientType, request);
|
||||
agreementVersionCacheService.evictUser(userId);
|
||||
return Result.success(legalAgreementService.getPendingAgreements(userId));
|
||||
}
|
||||
|
||||
@GetMapping("/admin/list")
|
||||
@RequirePermission("legal_agreement:manage")
|
||||
/**
|
||||
|
||||
+7
@@ -2,6 +2,8 @@ package com.xiaowang.jayucloud.salon.core.modules.system.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class SecureIntegrationConfigDTO {
|
||||
private String mapProvider;
|
||||
@@ -19,4 +21,9 @@ public class SecureIntegrationConfigDTO {
|
||||
private String moderationEncodingAesKey;
|
||||
private Boolean clearModerationCallbackToken;
|
||||
private Boolean clearModerationEncodingAesKey;
|
||||
|
||||
private Boolean moderationForwardEnabled;
|
||||
private Map<String, String> moderationForwardTargets;
|
||||
private String moderationForwardSecret;
|
||||
private Boolean clearModerationForwardSecret;
|
||||
}
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("t_moderation_callback_forward")
|
||||
public class ModerationCallbackForwardDO {
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("trace_id")
|
||||
private String traceId;
|
||||
|
||||
@TableField("source_env")
|
||||
private String sourceEnv;
|
||||
|
||||
@TableField("target_env")
|
||||
private String targetEnv;
|
||||
|
||||
@TableField("extra_json")
|
||||
private String extraJson;
|
||||
|
||||
@TableField("payload")
|
||||
private String payload;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("retry_count")
|
||||
private Integer retryCount;
|
||||
|
||||
@TableField("last_error")
|
||||
private String lastError;
|
||||
|
||||
@TableField("created_at")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@TableField("updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface ModerationCallbackForwardMapper extends BaseMapper<ModerationCallbackForwardDO> {
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.secure;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ModerationForwardConfig {
|
||||
private boolean enabled;
|
||||
private Map<String, String> targets;
|
||||
private String secret;
|
||||
|
||||
public static ModerationForwardConfig disabled() {
|
||||
return new ModerationForwardConfig(false, Collections.emptyMap(), "");
|
||||
}
|
||||
|
||||
public String targetFor(String env) {
|
||||
if (!enabled || env == null || targets == null) return null;
|
||||
String target = targets.get(env);
|
||||
return StringUtils.hasText(target) ? target.trim() : null;
|
||||
}
|
||||
|
||||
public boolean ready() {
|
||||
return enabled && StringUtils.hasText(secret);
|
||||
}
|
||||
}
|
||||
+5
@@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.salon.core.modules.system.service;
|
||||
import com.xiaowang.jayucloud.salon.core.common.dto.AgreementAwareRequest;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.dto.LegalAgreementDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO;
|
||||
|
||||
@@ -31,6 +32,10 @@ public interface LegalAgreementService {
|
||||
|
||||
UserAgreementConsentVO getMyConsent(Long userId);
|
||||
|
||||
AgreementPendingVO getPendingAgreements(Long userId);
|
||||
|
||||
void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest httpRequest);
|
||||
|
||||
void requireAccepted(AgreementAwareRequest request);
|
||||
|
||||
void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest);
|
||||
|
||||
+5
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.service;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
@@ -14,6 +15,10 @@ public interface SecureIntegrationConfigService {
|
||||
|
||||
void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto);
|
||||
|
||||
void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto);
|
||||
|
||||
ModerationForwardConfig getModerationForwardConfig();
|
||||
|
||||
Map<String, String> getMapRuntimeConfig(UserDO currentUser);
|
||||
|
||||
ModerationRuntimeConfig getModerationRuntimeConfig();
|
||||
|
||||
+54
@@ -11,6 +11,7 @@ import com.xiaowang.jayucloud.salon.core.modules.system.mapper.LegalAgreementMap
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -20,6 +21,8 @@ import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -170,6 +173,57 @@ public class LegalAgreementServiceImpl implements LegalAgreementService {
|
||||
return new UserAgreementConsentVO(versions);
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: getPendingAgreements 返回当前协议版本与该用户的同意状态;未登录时只返回当前版本。
|
||||
*/
|
||||
public AgreementPendingVO getPendingAgreements(Long userId) {
|
||||
Map<String, String> currentVersions = new LinkedHashMap<>();
|
||||
Map<String, String> acceptedVersions = new LinkedHashMap<>();
|
||||
List<String> pendingTypes = new ArrayList<>();
|
||||
Map<String, String> accepted = userId == null
|
||||
? Collections.emptyMap()
|
||||
: getMyConsent(userId).getConsentVersions();
|
||||
for (String type : List.of(USER_TERMS, PRIVACY_POLICY)) {
|
||||
LegalAgreementDO current = findCurrentAgreement(type);
|
||||
if (current == null) {
|
||||
continue;
|
||||
}
|
||||
currentVersions.put(type, current.getVersion());
|
||||
String acceptedVersion = accepted == null ? null : accepted.get(type);
|
||||
if (StringUtils.hasText(acceptedVersion)) {
|
||||
acceptedVersions.put(type, acceptedVersion);
|
||||
}
|
||||
if (!StringUtils.hasText(acceptedVersion) || !current.getVersion().equals(acceptedVersion)) {
|
||||
pendingTypes.add(type);
|
||||
}
|
||||
}
|
||||
Boolean pending = userId == null ? null : !pendingTypes.isEmpty();
|
||||
return new AgreementPendingVO(pending, currentVersions, acceptedVersions, pendingTypes);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
/**
|
||||
* Purpose: acceptCurrentAgreements 记录用户对当前发布版本的同意,不依赖客户端上报版本。
|
||||
*/
|
||||
public void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest httpRequest) {
|
||||
if (userId == null) {
|
||||
throw new RuntimeException("请先登录后再同意协议");
|
||||
}
|
||||
String normalizedClientType = StringUtils.hasText(clientType)
|
||||
? clientType.trim().toUpperCase()
|
||||
: "WEB";
|
||||
String ip = resolveClientIp(httpRequest);
|
||||
for (String type : List.of(USER_TERMS, PRIVACY_POLICY)) {
|
||||
LegalAgreementDO current = findCurrentAgreement(type);
|
||||
if (current == null) {
|
||||
throw new RuntimeException("当前协议未配置,请联系管理员");
|
||||
}
|
||||
upsertConsent(userId, type, current.getVersion(), "agreement-gate", normalizedClientType, ip);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: requireAccepted supports LegalAgreementServiceImpl.java by holding or executing the require accepted business role.
|
||||
|
||||
+142
@@ -1,6 +1,9 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO;
|
||||
@@ -8,12 +11,14 @@ import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegration
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SecureIntegrationConfigMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.SecureConfigEncryptionService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -22,15 +27,18 @@ import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConfigService {
|
||||
private static final String MAP = "MAP";
|
||||
private static final String MODERATION = "CONTENT_MODERATION";
|
||||
private static final String MODERATION_FORWARD = "CONTENT_MODERATION_FORWARD";
|
||||
private static final String SYSTEM = "SYSTEM";
|
||||
private static final String LEGACY_MAP_MIGRATED = "LEGACY_MAP_MIGRATED";
|
||||
private static final String WECHAT_CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback";
|
||||
@@ -40,6 +48,7 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
|
||||
private final SecureConfigEncryptionService encryptionService;
|
||||
private final ContentModerationProperties moderationProperties;
|
||||
private final WechatMiniProperties wechatMiniProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@@ -80,6 +89,12 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
|
||||
result.setWechatMiniAppId(StringUtils.hasText(wechatMiniProperties.getAppId())
|
||||
? wechatMiniProperties.getAppId() : "");
|
||||
result.setMockProviderAllowed(isMockAllowed());
|
||||
|
||||
ModerationForwardConfig forwardConfig = getModerationForwardConfig();
|
||||
result.setModerationForwardEnabled(forwardConfig.isEnabled());
|
||||
result.setModerationForwardTargets(forwardConfig.getTargets());
|
||||
result.setModerationForwardSecretConfigured(StringUtils.hasText(forwardConfig.getSecret()));
|
||||
|
||||
result.setUpdatedAt(latestUpdateTime());
|
||||
return result;
|
||||
}
|
||||
@@ -163,6 +178,77 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
|
||||
writeValue(MODERATION, "PROVIDER", provider, false, currentUser.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto) {
|
||||
requirePlatformAdmin(currentUser);
|
||||
requireEncryptionKey();
|
||||
|
||||
boolean enabled = Boolean.TRUE.equals(dto.getModerationForwardEnabled());
|
||||
Map<String, String> targets = normalizeForwardTargets(dto.getModerationForwardTargets());
|
||||
for (Map.Entry<String, String> entry : targets.entrySet()) {
|
||||
if (!isValidForwardTarget(entry.getValue())) {
|
||||
throw new IllegalArgumentException("跨环境转发地址不合法(" + entry.getKey()
|
||||
+ "),必须精确指向 /api/integration/wechat/content-moderation/callback,且 HTTP 仅允许内网主机");
|
||||
}
|
||||
}
|
||||
|
||||
ModerationForwardConfig current = getModerationForwardConfig();
|
||||
String secret;
|
||||
if (Boolean.TRUE.equals(dto.getClearModerationForwardSecret())) {
|
||||
secret = "";
|
||||
} else if (StringUtils.hasText(dto.getModerationForwardSecret())) {
|
||||
secret = dto.getModerationForwardSecret().trim();
|
||||
} else {
|
||||
secret = current.getSecret();
|
||||
}
|
||||
if (StringUtils.hasText(secret) && !secret.matches("[A-Za-z0-9+/=_\\-]{16,128}")) {
|
||||
throw new IllegalArgumentException("跨环境转发共享密钥需要为 16-128 位字母、数字或常用符号");
|
||||
}
|
||||
if (enabled) {
|
||||
if (!StringUtils.hasText(secret)) {
|
||||
throw new IllegalArgumentException("启用跨环境回调转发时必须配置共享密钥");
|
||||
}
|
||||
if (targets.isEmpty()) {
|
||||
throw new IllegalArgumentException("启用跨环境回调转发时至少需要配置一个目标环境地址");
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("enabled", enabled);
|
||||
payload.put("targets", targets);
|
||||
payload.put("secret", secret);
|
||||
try {
|
||||
writeValue(MODERATION_FORWARD, "CONFIG", objectMapper.writeValueAsString(payload), true, currentUser.getId());
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new IllegalStateException("无法保存跨环境转发配置", exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModerationForwardConfig getModerationForwardConfig() {
|
||||
if (!encryptionService.isConfigured()) return ModerationForwardConfig.disabled();
|
||||
String json = readValue(MODERATION_FORWARD, "CONFIG", "");
|
||||
if (!StringUtils.hasText(json)) return ModerationForwardConfig.disabled();
|
||||
try {
|
||||
JsonNode node = objectMapper.readTree(json);
|
||||
boolean enabled = node.path("enabled").asBoolean(false);
|
||||
Map<String, String> targets = new LinkedHashMap<>();
|
||||
JsonNode targetsNode = node.path("targets");
|
||||
if (targetsNode.isObject()) {
|
||||
targetsNode.fields().forEachRemaining(entry -> {
|
||||
if (StringUtils.hasText(entry.getValue().asText(""))) {
|
||||
targets.put(entry.getKey(), entry.getValue().asText(""));
|
||||
}
|
||||
});
|
||||
}
|
||||
return new ModerationForwardConfig(enabled, targets, node.path("secret").asText(""));
|
||||
} catch (JsonProcessingException exception) {
|
||||
log.warn("跨环境转发配置解析失败,按未启用处理");
|
||||
return ModerationForwardConfig.disabled();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public Map<String, String> getMapRuntimeConfig(UserDO currentUser) {
|
||||
@@ -362,6 +448,62 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> normalizeForwardTargets(Map<String, String> raw) {
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
if (raw == null) return result;
|
||||
for (String env : Arrays.asList("dev", "sit", "prod")) {
|
||||
String value = raw.get(env);
|
||||
if (StringUtils.hasText(value)) result.put(env, value.trim());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只允许指向内容审核回调路径:HTTPS 放行(各环境对外地址通常为 HTTPS 域名),
|
||||
* HTTP 仅允许私网/本机主机,避免被配置为任意公网地址造成 SSRF。
|
||||
*/
|
||||
private boolean isValidForwardTarget(String value) {
|
||||
if (!StringUtils.hasText(value)) return false;
|
||||
try {
|
||||
URI uri = new URI(value.trim());
|
||||
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
|
||||
String host = uri.getHost();
|
||||
if (!"https".equals(scheme) && !"http".equals(scheme)) return false;
|
||||
if (!StringUtils.hasText(host)) return false;
|
||||
if (uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null) return false;
|
||||
if (!WECHAT_CALLBACK_PATH.equals(uri.getRawPath())) return false;
|
||||
return !"http".equals(scheme) || isPrivateHost(host);
|
||||
} catch (URISyntaxException exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isPrivateHost(String host) {
|
||||
String normalized = host.toLowerCase(Locale.ROOT);
|
||||
if (normalized.startsWith("[") && normalized.endsWith("]")) {
|
||||
normalized = normalized.substring(1, normalized.length() - 1);
|
||||
}
|
||||
if ("localhost".equals(normalized) || normalized.endsWith(".localhost")
|
||||
|| normalized.endsWith(".local") || normalized.endsWith(".internal")) {
|
||||
return true;
|
||||
}
|
||||
if (normalized.contains(":")) {
|
||||
return normalized.startsWith("::1") || normalized.startsWith("fc") || normalized.startsWith("fd");
|
||||
}
|
||||
String[] parts = normalized.split("\\.");
|
||||
if (parts.length != 4) return false;
|
||||
try {
|
||||
int first = Integer.parseInt(parts[0]);
|
||||
int second = Integer.parseInt(parts[1]);
|
||||
if (first == 10 || first == 127) return true;
|
||||
if (first == 192 && second == 168) return true;
|
||||
if (first == 172 && second >= 16 && second <= 31) return true;
|
||||
return first == 169 && second == 254;
|
||||
} catch (NumberFormatException exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizedProvider(String value) {
|
||||
return upper(value, "DISABLED");
|
||||
}
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.support;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 协议版本缓存:当前发布版本缓存 4 分钟,用户已同意版本缓存 10 分钟。
|
||||
* 版本发布走 SQL 迁移,没有代码钩子,依赖短 TTL 自然收敛;accept 成功时主动清除该用户缓存。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AgreementVersionCacheService {
|
||||
|
||||
private static final String CURRENT_VERSIONS_KEY = "jayucloud:agreement:current-versions:v1";
|
||||
|
||||
private static final String USER_VERSIONS_KEY_PREFIX = "jayucloud:agreement:user-versions:";
|
||||
|
||||
private static final Duration CURRENT_VERSIONS_TTL = Duration.ofMinutes(4);
|
||||
|
||||
private static final Duration USER_VERSIONS_TTL = Duration.ofMinutes(10);
|
||||
|
||||
private static final TypeReference<Map<String, String>> STRING_MAP_TYPE = new TypeReference<Map<String, String>>() {
|
||||
};
|
||||
|
||||
private final LegalAgreementService legalAgreementService;
|
||||
|
||||
private final UserAgreementConsentMapper consentMapper;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public Map<String, String> currentVersions() {
|
||||
Map<String, String> cached = readCache(CURRENT_VERSIONS_KEY);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Map<String, String> loaded = legalAgreementService.getPendingAgreements(null).getCurrentVersions();
|
||||
writeCache(CURRENT_VERSIONS_KEY, loaded, CURRENT_VERSIONS_TTL);
|
||||
return loaded == null ? Collections.emptyMap() : loaded;
|
||||
}
|
||||
|
||||
public Map<String, String> acceptedVersions(Long userId) {
|
||||
if (userId == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
String key = userVersionsKey(userId);
|
||||
Map<String, String> cached = readCache(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Map<String, String> loaded = consentMapper.selectList(new LambdaQueryWrapper<UserAgreementConsentDO>()
|
||||
.eq(UserAgreementConsentDO::getUserId, userId))
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
UserAgreementConsentDO::getAgreementType,
|
||||
UserAgreementConsentDO::getVersion,
|
||||
(left, right) -> right,
|
||||
LinkedHashMap::new));
|
||||
writeCache(key, loaded, USER_VERSIONS_TTL);
|
||||
return loaded;
|
||||
}
|
||||
|
||||
public void evictUser(Long userId) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stringRedisTemplate.delete(userVersionsKey(userId));
|
||||
} catch (Exception exception) {
|
||||
log.warn("清除协议同意缓存失败 userId={}", userId, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String userVersionsKey(Long userId) {
|
||||
return USER_VERSIONS_KEY_PREFIX + userId;
|
||||
}
|
||||
|
||||
private Map<String, String> readCache(String key) {
|
||||
try {
|
||||
String json = stringRedisTemplate.opsForValue().get(key);
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.readValue(json, STRING_MAP_TYPE);
|
||||
} catch (Exception exception) {
|
||||
log.warn("读取协议版本缓存失败,回退数据库 key={}", key, exception);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeCache(String key, Map<String, String> value, Duration ttl) {
|
||||
try {
|
||||
stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value), ttl);
|
||||
} catch (Exception exception) {
|
||||
log.warn("写入协议版本缓存失败 key={}", key, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 协议重新同意状态:未登录时只返回当前版本,登录后额外返回已同意版本与待同意类型。
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AgreementPendingVO {
|
||||
|
||||
private Boolean pending;
|
||||
|
||||
private Map<String, String> currentVersions;
|
||||
|
||||
private Map<String, String> acceptedVersions;
|
||||
|
||||
private List<String> pendingTypes;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class ModerationForwardRecordVO {
|
||||
private Long id;
|
||||
private String traceId;
|
||||
private String sourceEnv;
|
||||
private String targetEnv;
|
||||
private String status;
|
||||
private Integer retryCount;
|
||||
private String lastError;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+6
@@ -4,6 +4,7 @@ import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class SecureIntegrationConfigVO {
|
||||
@@ -24,6 +25,11 @@ public class SecureIntegrationConfigVO {
|
||||
private String wechatMiniAppId;
|
||||
private Boolean mockProviderAllowed;
|
||||
|
||||
private Boolean moderationForwardEnabled;
|
||||
private Map<String, String> moderationForwardTargets;
|
||||
private Boolean moderationForwardSecretConfigured;
|
||||
private List<ModerationForwardRecordVO> moderationForwardRecent;
|
||||
|
||||
private Boolean encryptionKeyConfigured;
|
||||
private LocalDateTime updatedAt;
|
||||
/** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */
|
||||
|
||||
+6
-2
@@ -629,7 +629,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
AppointmentCustomerOptionVO customer = new AppointmentCustomerOptionVO();
|
||||
customer.setId(user.getId());
|
||||
customer.setName(user.getNickname());
|
||||
customer.setPhone(resolveCustomerPhone(user));
|
||||
String plainPhone = resolveCustomerPhone(user);
|
||||
customer.setPhone(phoneCrypto.mask(plainPhone));
|
||||
customer.setPhoneAvailable(StringUtils.hasText(plainPhone));
|
||||
customer.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
|
||||
customer.setCreatedAt(user.getCreateTime());
|
||||
return customer;
|
||||
@@ -658,7 +660,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
AppointmentCustomerOptionVO option = new AppointmentCustomerOptionVO();
|
||||
option.setId(user.getId());
|
||||
option.setName(user.getNickname());
|
||||
option.setPhone(resolveCustomerPhone(user));
|
||||
String plainPhone = resolveCustomerPhone(user);
|
||||
option.setPhone(phoneCrypto.mask(plainPhone));
|
||||
option.setPhoneAvailable(StringUtils.hasText(plainPhone));
|
||||
option.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
|
||||
option.setCreatedAt(user.getCreateTime());
|
||||
return option;
|
||||
|
||||
+8
@@ -90,6 +90,14 @@ public class RequestThrottleService {
|
||||
assertAllowed("agreement-read", request, sanitize(agreementType), rateLimitProperties.getAgreementRead(), "协议读取过于频繁,请稍后再试");
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户拨号取号按用户维度限流,避免管理员批量拉取完整号码。
|
||||
*/
|
||||
public void checkCustomerDial(HttpServletRequest request, Long userId) {
|
||||
assertAllowed("customer-dial", request, userId == null ? "" : String.valueOf(userId),
|
||||
rateLimitProperties.getCustomerDial(), "拨号取号过于频繁,请稍后再试");
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: checkAuthenticatedWrite supports RequestThrottleService.java by holding or executing the check authenticated write business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
-- 隐私政策与用户协议条款修订:对齐手机号/账号 AES-GCM 加密存储、HMAC 不可逆索引与按场景脱敏展示
|
||||
-- 版本:2026.11.04
|
||||
-- 说明:仅停用旧版本并新增协议版本,不修改已在任一环境执行的 V1/V3 协议正文。
|
||||
|
||||
UPDATE t_legal_agreement
|
||||
SET status = 0, update_time = NOW()
|
||||
WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY')
|
||||
AND is_delete = 0
|
||||
AND status = 1;
|
||||
|
||||
INSERT INTO t_legal_agreement
|
||||
(id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
|
||||
VALUES
|
||||
(313931273555140003, 'USER_TERMS', '用户协议', '2026.11.04',
|
||||
'欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。本协议与《隐私政策》共同构成你使用本服务的基础规则。
|
||||
|
||||
一、协议接受与版本
|
||||
你在登录前应完整阅读本协议和《隐私政策》,并主动选择同意。不同意时,我们不会交换微信登录凭证,你也不能继续使用。本协议版本为 2026.11.04,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。
|
||||
|
||||
二、账号与使用权限
|
||||
1. 微信 OpenID 用于识别和关联工作台账号;账号仅供本人使用,不得转借、出租或共享。
|
||||
2. 昵称和头像为可选资料;手机号可选绑定,不绑定不影响基础工作台功能。
|
||||
3. 你应妥善保管登录设备与账号,不得绕过权限校验访问他人数据。离职或不再获授权时,门店管理员可以调整或停用账号权限。
|
||||
4. 手机号及手机号形式的账号按《隐私政策》所述采用加密存储和不可逆索引;常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。你不得擅自收集、导出或向无关第三方提供完整号码。
|
||||
|
||||
三、业务资料与内容
|
||||
1. 你仅可录入履行门店业务所需且有权处理的客户、预约、作品、员工和经营资料,并确保上传文字、图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。
|
||||
2. 头像、作品、评论、店铺展示资料、公告和人工发布的消息会在公开前经过内容安全审核;未通过、待复核或服务异常的内容不会公开。
|
||||
3. 客户姓名和联系电话、预约与补单资料、备注、凭证、员工申请资料、内部审核说明和自动事务通知不纳入对外内容审核,但仍受门店权限和保密要求约束。
|
||||
|
||||
四、业务记录与金额
|
||||
订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值、订阅或平台虚拟权益购买。不得将工作台用于未经授权的资金收取、代收或虚拟权益交易。
|
||||
|
||||
五、账号注销与数据处理
|
||||
1. 你可在小程序“我的-账号设置”提交注销申请,并在处理前撤回。
|
||||
2. 管理员完成必要的门店移交或归档后,系统撤销会话并清理或匿名化 OpenID、昵称、头像、手机号等个人资料,目标处理期限为 15 个工作日。
|
||||
3. 解绑手机号经当前号码验证码核验后立即生效,系统清除手机号密文和检索索引。
|
||||
4. 必要的订单、预约和经营记录去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。
|
||||
|
||||
六、未成年人
|
||||
不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务。门店不得要求未成年人独立提交与其年龄不相适应的个人信息。
|
||||
|
||||
七、服务调整、责任与联系
|
||||
1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。
|
||||
2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。
|
||||
3. 隐私相关申请可从账号设置发起或联系所属门店管理员;其他问题请联系门店管理员或运营方公布的客服渠道【待业务确认】。
|
||||
|
||||
本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。',
|
||||
1, NOW(), NOW(), NOW(), 0),
|
||||
(313931273555140004, 'PRIVACY_POLICY', '隐私政策', '2026.11.04',
|
||||
'欢迎使用甲屿手纪 Salon 门店工作台。本政策说明我们如何处理店长、员工账号及门店业务资料中的个人信息。本政策与《用户协议》共同构成你使用本服务的基础规则。
|
||||
|
||||
一、我们处理的信息及用途
|
||||
1. 登录与账号:经你主动同意后,通过微信登录获取 OpenID,用于识别和关联账号;如你使用手机号注册或绑定,手机号仅用于注册登录、验证码校验、账号找回、订单联系和售后处理,不用于营销。
|
||||
2. 账号标识:账号用于身份识别、权限校验和操作归属记录。当账号本身为手机号时,该账号按手机号同等强度加密存储;其他账号标识仅用于身份识别,并通过不可逆索引支持查询匹配。
|
||||
3. 可选资料:昵称、头像仅在你主动补充或更新时处理。
|
||||
4. 门店业务资料:店长和员工可能录入客户姓名、可选联系电话、预约、作品、订单和经营记录,用于履行门店服务管理;这些资料不构成客户的小程序登录账号。
|
||||
5. 安全运行:服务端处理请求所需的网络地址、登录会话和操作审计信息,用于安全防护、故障排查和审计。我们不主动采集 IMEI、MAC、麦克风或持续定位信息;仅当你主动使用地图选点功能时,才会调用微信地图能力获取你选择的地点。
|
||||
6. 内容审核:头像、作品、评论、店铺展示资料、公告和人工发布的消息在对外展示前进行内容安全审核。
|
||||
|
||||
二、加密存储与检索索引
|
||||
1. 手机号以及手机号形式的账号使用 AES-GCM 加密后落库,密文带版本标识,不以明文存入数据库。
|
||||
2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供;密钥访问受配置权限和审计约束。
|
||||
3. 为实现登录、去重和查询匹配,系统另以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引。该索引不能反推出手机号或账号原文,且不用于对外展示。
|
||||
4. 数据导出、备份和迁移沿用同等加密要求;如发生密钥轮换,按版本标识兼容解密并逐步重加密。
|
||||
|
||||
三、按场景脱敏展示
|
||||
1. 常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。
|
||||
2. 仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。
|
||||
3. 脱敏规则由服务端统一执行,不依赖前端隐藏;客户端不得缓存、截屏传播或在无权限场景转述完整号码。
|
||||
4. 客户本人资料页、员工账号资料页默认展示脱敏号码;修改绑定手机号时通过短信验证码核验,不以页面明文号码作为身份凭证。
|
||||
|
||||
四、第三方共享
|
||||
我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的:
|
||||
1. 微信:微信登录、手机号授权、地图选点和内容安全审核(图片与文本)。
|
||||
2. 短信服务商:通过部署环境配置的短信通道发送验证码、绑定/解绑通知和必要的业务通知。
|
||||
3. 消息通道:通过 MessageHub 等已配置通道发送站内或订阅消息。
|
||||
4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。
|
||||
5. 地图服务:仅在你主动地图选点时,由微信内置地图能力(腾讯位置服务)处理所选位置。
|
||||
我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。
|
||||
|
||||
五、保存期限与删除
|
||||
1. 解绑手机号:通过当前号码验证码核验后,立即清除手机号密文及 phone_hash 索引。
|
||||
2. 账号注销:可在小程序“我的-账号设置”提交申请,处理前可撤回;管理员完成门店移交或归档后撤销会话,并在目标 15 个工作日内删除或匿名化 OpenID、昵称、头像和手机号等个人资料。
|
||||
3. 订单、预约和经营记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。
|
||||
4. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。
|
||||
5. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。
|
||||
|
||||
六、你的权利
|
||||
1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在账号设置中更换。
|
||||
2. 删除与注销:可在账号设置申请注销或解绑;也可请求删除非业务必需的资料。
|
||||
3. 撤回同意:可在账号设置或联系门店管理员撤回待处理的授权;撤回后不影响撤回前已进行的处理。
|
||||
4. 投诉与咨询:可联系所属门店管理员,或通过运营方公布的客服渠道提交隐私请求;具体客服渠道【待业务/法务确认】。
|
||||
5. 我们将在收到请求后按适用法律规定的期限响应;对于无法核验身份的请求,可能要求补充验证。
|
||||
|
||||
七、未成年人保护
|
||||
本服务主要面向门店经营人员。不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;我们不会在明知未取得监护人同意的情况下处理其个人信息。如发现误收集,将停止处理并删除。
|
||||
|
||||
八、安全措施与安全事件响应
|
||||
我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。
|
||||
|
||||
九、跨境传输
|
||||
目前我们不涉及向境外提供个人信息。如未来因业务需要发生跨境传输,我们将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。
|
||||
|
||||
十、政策更新与联系
|
||||
本政策版本为 2026.11.04,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在账号设置查看当前版本;其他问题请联系所属门店管理员。
|
||||
|
||||
本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。',
|
||||
1, NOW(), NOW(), NOW(), 0);
|
||||
@@ -0,0 +1,51 @@
|
||||
-- 隐私政策与用户协议条款修订:对齐“全场景脱敏 + 拨号按需单次取号 + 可接隐私号码”口径
|
||||
-- 版本:2026.11.04(V18)
|
||||
-- 说明:仅更新当前生效版本的条款正文,不新增协议版本、不触发重新同意;静态 HTML 正文由 public/legal 读库渲染,不再维护副本。
|
||||
|
||||
UPDATE t_legal_agreement
|
||||
SET content = REPLACE(
|
||||
content,
|
||||
'常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。',
|
||||
'所有页面统一脱敏展示;确需联系客户时,须通过门店数据权限与预约/订单上下文校验后按需单次取号拨号,不批量展示完整号码;接入隐私号码服务时返回临时隐私号码。'
|
||||
),
|
||||
update_time = NOW()
|
||||
WHERE agreement_type = 'USER_TERMS'
|
||||
AND status = 1
|
||||
AND is_delete = 0
|
||||
AND content LIKE '%常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。%';
|
||||
|
||||
UPDATE t_legal_agreement
|
||||
SET content = REPLACE(
|
||||
content,
|
||||
'常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。',
|
||||
'全部客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。'
|
||||
),
|
||||
update_time = NOW()
|
||||
WHERE agreement_type = 'PRIVACY_POLICY'
|
||||
AND status = 1
|
||||
AND is_delete = 0
|
||||
AND content LIKE '%常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。%';
|
||||
|
||||
UPDATE t_legal_agreement
|
||||
SET content = REPLACE(
|
||||
content,
|
||||
'仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。',
|
||||
'确需与客户进行业务联系时,由授权人员在门店数据权限和预约/订单上下文校验通过后按需单次取号:直拨模式仅返回本次拨号号码,隐私号码模式返回临时隐私号码;完整号码不下发列表、不落库、不写日志、不进入缓存,且隐私号码未开通时不会回退为真实号码。'
|
||||
),
|
||||
update_time = NOW()
|
||||
WHERE agreement_type = 'PRIVACY_POLICY'
|
||||
AND status = 1
|
||||
AND is_delete = 0
|
||||
AND content LIKE '%仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。%';
|
||||
|
||||
UPDATE t_legal_agreement
|
||||
SET content = REPLACE(
|
||||
content,
|
||||
'客户本人资料页、员工账号资料页默认展示脱敏号码;',
|
||||
'客户本人资料页、员工账号资料页一律展示脱敏号码;'
|
||||
),
|
||||
update_time = NOW()
|
||||
WHERE agreement_type = 'PRIVACY_POLICY'
|
||||
AND status = 1
|
||||
AND is_delete = 0
|
||||
AND content LIKE '%客户本人资料页、员工账号资料页默认展示脱敏号码;%';
|
||||
@@ -0,0 +1,30 @@
|
||||
-- 隐私政策与用户协议新版本发布:停用当前生效版本,并从停用前正文复制新版本
|
||||
-- 版本:2026.11.04-R2
|
||||
-- 说明:正文通过 INSERT ... SELECT 复制 V18 已修订的当前生效文本,不在 SQL 中重复维护长文本;
|
||||
-- V18 已在任一环境执行后不得修改,本文件仅新增版本。
|
||||
|
||||
UPDATE t_legal_agreement
|
||||
SET status = 0, update_time = NOW()
|
||||
WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY')
|
||||
AND is_delete = 0
|
||||
AND status = 1;
|
||||
|
||||
INSERT INTO t_legal_agreement
|
||||
(id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
|
||||
SELECT 313931273555140005, 'USER_TERMS', title, '2026.11.04-R2', content, 1,
|
||||
'2026-11-04 00:00:00', NOW(), NOW(), 0
|
||||
FROM t_legal_agreement
|
||||
WHERE agreement_type = 'USER_TERMS'
|
||||
AND is_delete = 0
|
||||
ORDER BY effective_time DESC, create_time DESC
|
||||
LIMIT 1;
|
||||
|
||||
INSERT INTO t_legal_agreement
|
||||
(id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
|
||||
SELECT 313931273555140006, 'PRIVACY_POLICY', title, '2026.11.04-R2', content, 1,
|
||||
'2026-11-04 00:00:00', NOW(), NOW(), 0
|
||||
FROM t_legal_agreement
|
||||
WHERE agreement_type = 'PRIVACY_POLICY'
|
||||
AND is_delete = 0
|
||||
ORDER BY effective_time DESC, create_time DESC
|
||||
LIMIT 1;
|
||||
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE IF NOT EXISTS t_moderation_callback_forward (
|
||||
id BIGINT NOT NULL COMMENT '主键ID',
|
||||
trace_id VARCHAR(128) NOT NULL COMMENT '微信异步图片审核任务标识 trace_id',
|
||||
source_env VARCHAR(16) NOT NULL COMMENT '实际收到微信回调的部署环境',
|
||||
target_env VARCHAR(16) NULL COMMENT '应处理该回调的部署环境',
|
||||
extra_json VARCHAR(256) NULL COMMENT '微信回调透传的 extra 原始内容',
|
||||
payload LONGTEXT NULL COMMENT '回调解密后的完整报文,仅用于补偿重放',
|
||||
status VARCHAR(16) NOT NULL COMMENT 'PENDING/SUCCESS/RETRY/FAILED/NO_ENV/TARGET_MISSING',
|
||||
retry_count INT NOT NULL DEFAULT 0 COMMENT '已重试次数',
|
||||
last_error VARCHAR(500) NULL COMMENT '最近一次失败原因(脱敏)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_moderation_callback_forward_trace (trace_id),
|
||||
KEY idx_moderation_callback_forward_status (status, updated_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='微信审核回调跨环境转发记录';
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.xiaowang.jayucloud.salon.core.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AgreementAcceptanceInterceptorTest {
|
||||
|
||||
@Mock private AgreementVersionCacheService agreementVersionCacheService;
|
||||
|
||||
private AgreementAcceptanceInterceptor interceptor;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
interceptor = new AgreementAcceptanceInterceptor(agreementVersionCacheService, objectMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsUnauthenticatedRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
assertTrue(interceptor.preHandle(request, response, new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsWhenAcceptedVersionsMatchCurrent() throws Exception {
|
||||
Map<String, String> versions = currentVersions();
|
||||
when(agreementVersionCacheService.currentVersions()).thenReturn(versions);
|
||||
when(agreementVersionCacheService.acceptedVersions(9L)).thenReturn(new LinkedHashMap<>(versions));
|
||||
|
||||
assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWithBusinessCodeWhenVersionPending() throws Exception {
|
||||
Map<String, String> versions = currentVersions();
|
||||
Map<String, String> accepted = new LinkedHashMap<>();
|
||||
accepted.put("USER_TERMS", "2026.11.04");
|
||||
when(agreementVersionCacheService.currentVersions()).thenReturn(versions);
|
||||
when(agreementVersionCacheService.acceptedVersions(9L)).thenReturn(accepted);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
assertFalse(interceptor.preHandle(authenticatedRequest(9L), response, new Object()));
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
JsonNode body = objectMapper.readTree(response.getContentAsString());
|
||||
assertEquals(AgreementAcceptanceInterceptor.AGREEMENT_VERSION_REQUIRED_CODE, body.get("code").asInt());
|
||||
assertEquals("2026.11.04-R2", body.get("data").get("currentVersions").get("USER_TERMS").asText());
|
||||
assertEquals("USER_TERMS", body.get("data").get("pendingTypes").get(0).asText());
|
||||
assertEquals(AgreementAcceptanceInterceptor.AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE,
|
||||
body.get("data").get("businessCode").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsOpenWhenGuardComponentThrows() throws Exception {
|
||||
when(agreementVersionCacheService.currentVersions()).thenThrow(new IllegalStateException("redis down"));
|
||||
|
||||
assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object()));
|
||||
}
|
||||
|
||||
private MockHttpServletRequest authenticatedRequest(Long userId) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setAttribute("userId", userId);
|
||||
return request;
|
||||
}
|
||||
|
||||
private Map<String, String> currentVersions() {
|
||||
Map<String, String> versions = new LinkedHashMap<>();
|
||||
versions.put("USER_TERMS", "2026.11.04-R2");
|
||||
versions.put("PRIVACY_POLICY", "2026.11.04-R2");
|
||||
return versions;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user