完成Salon小程序合规整改
This commit is contained in:
+1
@@ -32,6 +32,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
"com.xiaowang.jayucloud.salon.core.modules.payment.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.planning.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.product.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.privacy.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.registration.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.security.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.shop.mapper",
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.jayucloud.salon.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jayucloud-salon.privacy.phone-crypto")
|
||||
public class PhoneCryptoProperties {
|
||||
private String encryptionKey;
|
||||
private String indexKey;
|
||||
private boolean backfillEnabled;
|
||||
private int backfillPageSize = 500;
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@ import lombok.Data;
|
||||
public class UpdatePhoneRequestDTO {
|
||||
|
||||
/**
|
||||
* 原手机号
|
||||
* 兼容旧客户端的原手机号字段;服务端不使用该字段进行身份校验。
|
||||
*/
|
||||
private String oldPhone;
|
||||
|
||||
|
||||
+13
-8
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.auth.service.impl;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
@@ -52,6 +53,10 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
*/
|
||||
private final MessageHubClientService messageHubClientService;
|
||||
|
||||
private String phoneKey(String phone) {
|
||||
return PhoneCrypto.current().index(phone);
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Run business method `generateVerificationCode`.
|
||||
@@ -94,14 +99,14 @@ 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 codeKey = CODE_PREFIX + phoneKey(phone);
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phoneKey(phone);
|
||||
|
||||
messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code);
|
||||
redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES));
|
||||
redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()),
|
||||
Duration.ofSeconds(RESEND_INTERVAL_SECONDS));
|
||||
log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode);
|
||||
log.info("验证码已发送,手机号: {}, sceneCode: {}", PhoneCrypto.current().mask(phone), sceneCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -113,21 +118,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 + phoneKey(phone);
|
||||
String storedCode = redisTemplate.opsForValue().get(codeKey);
|
||||
|
||||
if (storedCode == null) {
|
||||
log.warn("验证码不存在或已过期,手机号: {}", phone);
|
||||
log.warn("验证码不存在或已过期,手机号: {}", PhoneCrypto.current().mask(phone));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!storedCode.equals(code)) {
|
||||
log.warn("验证码错误,手机号: {}", phone);
|
||||
log.warn("验证码错误,手机号: {}", PhoneCrypto.current().mask(phone));
|
||||
return false;
|
||||
}
|
||||
|
||||
redisTemplate.delete(codeKey);
|
||||
log.info("验证码验证成功,手机号: {}", phone);
|
||||
log.info("验证码验证成功,手机号: {}", PhoneCrypto.current().mask(phone));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -139,7 +144,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 + phoneKey(phone);
|
||||
String sendTime = redisTemplate.opsForValue().get(sendTimeKey);
|
||||
return sendTime == null;
|
||||
}
|
||||
|
||||
+3
@@ -71,4 +71,7 @@ public class CommentDO extends BaseEntity {
|
||||
*/
|
||||
@TableField("is_delete")
|
||||
private Integer isDelete;
|
||||
|
||||
@TableField("moderation_status")
|
||||
private String moderationStatus;
|
||||
}
|
||||
|
||||
+39
-4
@@ -14,6 +14,10 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.content.service.CommentService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.content.vo.CommentVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -57,6 +61,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
private final ProductMapper productMapper;
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
/**
|
||||
@@ -155,7 +161,9 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
}
|
||||
commentDO.setLikeCount(0);
|
||||
commentDO.setIsDelete(0);
|
||||
commentDO.setModerationStatus("PENDING");
|
||||
commentMapper.insert(commentDO);
|
||||
moderateComment(commentDO, currentUserId);
|
||||
return commentDO.getId();
|
||||
}
|
||||
|
||||
@@ -173,8 +181,11 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
return false;
|
||||
}
|
||||
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
|
||||
commentDO.setModerationStatus("PENDING");
|
||||
commentDO.setUpdateTime(LocalDateTime.now());
|
||||
return commentMapper.updateById(commentDO) > 0;
|
||||
boolean updated = commentMapper.updateById(commentDO) > 0;
|
||||
if (updated) moderateComment(commentDO, commentDO.getUserId());
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -216,8 +227,11 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
throw new RuntimeException("只能修改自己的评论");
|
||||
}
|
||||
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
|
||||
commentDO.setModerationStatus("PENDING");
|
||||
commentDO.setUpdateTime(LocalDateTime.now());
|
||||
return commentMapper.updateById(commentDO) > 0;
|
||||
boolean updated = commentMapper.updateById(commentDO) > 0;
|
||||
if (updated) moderateComment(commentDO, currentUserId);
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -230,7 +244,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
*/
|
||||
public boolean deleteComment(Long id, Long currentUserId) {
|
||||
CommentDO commentDO = commentMapper.selectById(id);
|
||||
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
|
||||
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete()) || !"APPROVED".equals(commentDO.getModerationStatus())) {
|
||||
return false;
|
||||
}
|
||||
if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) {
|
||||
@@ -315,6 +329,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getUserId, userId)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.orderByDesc(CommentDO::getCreateTime)
|
||||
);
|
||||
return commentDOs.stream()
|
||||
@@ -334,6 +349,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getShopId, shopId)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.orderByDesc(CommentDO::getCreateTime)
|
||||
);
|
||||
return commentDOs.stream()
|
||||
@@ -353,6 +369,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getProductId, productId)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.orderByDesc(CommentDO::getCreateTime)
|
||||
);
|
||||
/**
|
||||
@@ -376,6 +393,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getParentCommentId, parentCommentId)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.orderByAsc(CommentDO::getCreateTime)
|
||||
);
|
||||
return commentDOs.stream()
|
||||
@@ -397,6 +415,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
List<CommentDO> commentDOs = commentMapper.selectList(
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.eq(productId != null && productId > 0, CommentDO::getProductId, productId)
|
||||
.eq(userId != null && userId > 0, CommentDO::getUserId, userId)
|
||||
.eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId)
|
||||
@@ -569,7 +588,23 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
* @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> activeQuery() {
|
||||
return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0);
|
||||
return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED");
|
||||
}
|
||||
|
||||
private void moderateComment(CommentDO comment, Long userId) {
|
||||
try {
|
||||
ContentModerationResultVO result = contentModerationService.assess("COMMENT", comment.getId(), userId,
|
||||
comment.getCommentContent() + "\n" + String.valueOf(comment.getImageFileIds()),
|
||||
objectMapper.writeValueAsString(java.util.Map.of(
|
||||
"commentContent", comment.getCommentContent(),
|
||||
"imageFileIds", comment.getImageFileIds() == null ? "" : comment.getImageFileIds())));
|
||||
comment.setModerationStatus(result.getStatus());
|
||||
comment.setUpdateTime(LocalDateTime.now());
|
||||
commentMapper.updateById(comment);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new IllegalStateException("评论审核内容序列化失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+8
-1
@@ -1,14 +1,17 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.dto;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.dto.AgreementAwareRequest;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 微信小程序自动登录请求。
|
||||
*/
|
||||
@Data
|
||||
public class WechatMiniAutoLoginRequestDTO {
|
||||
public class WechatMiniAutoLoginRequestDTO implements AgreementAwareRequest {
|
||||
|
||||
@NotBlank(message = "微信登录凭证不能为空")
|
||||
/**
|
||||
@@ -20,4 +23,8 @@ public class WechatMiniAutoLoginRequestDTO {
|
||||
* Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long preferredShopId;
|
||||
|
||||
private Boolean agreementAccepted;
|
||||
private Map<String, String> agreementVersions;
|
||||
private String clientType;
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.xiaowang.jayucloud.salon.core.config.BrandProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.MessageHubPushConfigDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -138,7 +139,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
message.getMessageProperties().setHeader("X-MessageHub-Access-Token", requireAccessToken());
|
||||
rabbitTemplate.send(ingressExchange, ingressRoutingKey, message);
|
||||
log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, exchange: {}, sourceSystem: {}, templateCode: {}",
|
||||
sceneCode, phone, ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
|
||||
sceneCode, PhoneCrypto.current().mask(phone), ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
|
||||
} catch (Exception exception) {
|
||||
log.error("发送短信验证码失败", exception);
|
||||
throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception);
|
||||
|
||||
+10
-6
@@ -17,6 +17,7 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRe
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService;
|
||||
@@ -500,12 +501,15 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
if (!StringUtils.hasText(phone)) {
|
||||
return null;
|
||||
}
|
||||
return userMapper.selectOne(
|
||||
new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getPhone, phone)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO user = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getPhoneHash, PhoneCrypto.current().index(phone.trim()))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1"));
|
||||
if (user == null) {
|
||||
Long legacyId = userMapper.findLegacyIdByPhone(phone.trim());
|
||||
user = legacyId == null ? null : userMapper.selectById(legacyId);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+8
-1
@@ -123,7 +123,7 @@ public class WechatMiniLoginResultVO {
|
||||
resultVO.setMessage("手机号尚未绑定店铺,请先完成身份注册");
|
||||
resultVO.setRegistrationRequired(true);
|
||||
resultVO.setRegistrationTicket(loginResponse.getRegistrationTicket());
|
||||
resultVO.setPhone(loginResponse.getPhone());
|
||||
resultVO.setPhone(maskPhone(loginResponse.getPhone()));
|
||||
resultVO.setRegistrationReason(loginResponse.getRegistrationReason());
|
||||
resultVO.setRegistrationStatus(loginResponse.getRegistrationStatus());
|
||||
resultVO.setRegistrationRejectReason(loginResponse.getRegistrationRejectReason());
|
||||
@@ -131,6 +131,13 @@ public class WechatMiniLoginResultVO {
|
||||
return resultVO;
|
||||
}
|
||||
|
||||
private static String maskPhone(String phone) {
|
||||
if (phone == null || phone.length() != 11 || !phone.matches("1[3-9]\\d{9}")) {
|
||||
return phone;
|
||||
}
|
||||
return phone.substring(0, 3) + "****" + phone.substring(7);
|
||||
}
|
||||
|
||||
public static WechatMiniLoginResultVO selectShop(
|
||||
String message,
|
||||
String ticket,
|
||||
|
||||
+3
-1
@@ -15,6 +15,7 @@ import com.xiaowang.jayucloud.salon.core.modules.message.service.AnnouncementSer
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.vo.AnnouncementVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -83,6 +84,7 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -212,7 +214,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(phoneCrypto.mask(user.getAccount()));
|
||||
vo.setShopId(user.getShopId());
|
||||
vo.setShopName(shopNameMap.get(user.getShopId()));
|
||||
vo.setType(user.getType());
|
||||
|
||||
+3
-1
@@ -20,6 +20,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSu
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.vo.SystemMessageVO;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -97,6 +98,7 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
* Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
/**
|
||||
* Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
@@ -267,7 +269,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(phoneCrypto.mask(user.getAccount()));
|
||||
vo.setShopId(user.getShopId());
|
||||
vo.setShopName(shopNameMap.get(user.getShopId()));
|
||||
vo.setType(user.getType());
|
||||
|
||||
+7
-1
@@ -1,6 +1,9 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.order.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneEncryptionTypeHandler;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
@@ -8,7 +11,7 @@ import java.time.LocalDateTime;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
|
||||
@Data
|
||||
@TableName("t_order")
|
||||
@TableName(value = "t_order", autoResultMap = true)
|
||||
/**
|
||||
* OrderDO maps to a database table row. Mapper classes persist and query this object.
|
||||
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
|
||||
@@ -55,7 +58,10 @@ public class OrderDO extends BaseEntity {
|
||||
private String refundStatus;
|
||||
private String customerRemark;
|
||||
private String customerNameSnapshot;
|
||||
@TableField(typeHandler = PhoneEncryptionTypeHandler.class)
|
||||
private String customerPhoneSnapshot;
|
||||
@TableField(value = "customer_phone_snapshot_hash", fill = FieldFill.INSERT_UPDATE)
|
||||
private String customerPhoneSnapshotHash;
|
||||
private String quoteStatus;
|
||||
private String orderSource;
|
||||
private Integer quoteUserConfirmed;
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.service.PaymentService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.PaymentOrderVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/payment")
|
||||
@RequiredArgsConstructor
|
||||
public class PaymentController {
|
||||
|
||||
private final PaymentService paymentService;
|
||||
|
||||
@PostMapping("/order/{orderId}/prepare")
|
||||
public Result<PaymentOrderVO> prepareOrderPayment(HttpServletRequest request, @PathVariable Long orderId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(paymentService.prepareOrderPayment(userId, orderId));
|
||||
}
|
||||
|
||||
@PostMapping("/order/{orderId}/mock-success")
|
||||
public Result<PaymentOrderVO> mockSuccess(HttpServletRequest request, @PathVariable Long orderId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success"));
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ClosureSuccessorManagerVO;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin/privacy/account-closure")
|
||||
public class AdminAccountClosureController {
|
||||
private final AccountClosureService accountClosureService;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@GetMapping("/pending")
|
||||
public Result<List<AccountClosureRequestVO>> pending(HttpServletRequest request) {
|
||||
requirePlatformAdmin(request);
|
||||
return Result.success(accountClosureService.listPending());
|
||||
}
|
||||
|
||||
@GetMapping("/successor-managers")
|
||||
public Result<List<ClosureSuccessorManagerVO>> successorManagers(HttpServletRequest request) {
|
||||
requirePlatformAdmin(request);
|
||||
List<ClosureSuccessorManagerVO> managers = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getType, 2).eq(UserDO::getStatus, 1).eq(UserDO::getIsDelete, 0)
|
||||
.select(UserDO::getId, UserDO::getNickname, UserDO::getShopId)
|
||||
.orderByAsc(UserDO::getNickname))
|
||||
.stream().map(user -> new ClosureSuccessorManagerVO(user.getId(), user.getNickname(), user.getShopId()))
|
||||
.collect(Collectors.toList());
|
||||
return Result.success(managers);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/process")
|
||||
@OperationGuard(action = "admin-account-closure-process", ttlSeconds = 10, message = "申请处理中,请勿重复提交")
|
||||
public Result<Boolean> process(HttpServletRequest request, @PathVariable Long id,
|
||||
@RequestBody AccountClosureProcessDTO dto) {
|
||||
Long reviewerId = requirePlatformAdmin(request);
|
||||
return Result.success(accountClosureService.process(reviewerId, id, dto));
|
||||
}
|
||||
|
||||
private Long requirePlatformAdmin(HttpServletRequest request) {
|
||||
Object value = request.getAttribute("userId");
|
||||
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
|
||||
Long userId = (Long) value;
|
||||
UserDO actor = userMapper.selectById(userId);
|
||||
if (actor == null || !Integer.valueOf(4).equals(actor.getType())) throw new IllegalArgumentException("无权处理注销申请");
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.ContentModerationReviewDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
@RequestMapping("/admin/privacy/content-moderation")
|
||||
public class AdminContentModerationController {
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@GetMapping("/pending")
|
||||
public Result<List<ContentModerationRecordDO>> pending(HttpServletRequest request) {
|
||||
requirePlatformAdmin(request);
|
||||
return Result.success(contentModerationService.listPending());
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/review")
|
||||
@OperationGuard(action = "admin-content-moderation-review", ttlSeconds = 5, message = "复核处理中,请勿重复提交")
|
||||
public Result<Boolean> review(HttpServletRequest request, @PathVariable Long id,
|
||||
@Valid @RequestBody ContentModerationReviewDTO dto) {
|
||||
Long reviewerId = requirePlatformAdmin(request);
|
||||
if (dto.getApproved() == null) throw new IllegalArgumentException("请选择通过或拒绝");
|
||||
return Result.success(contentModerationService.review(reviewerId, id, dto.getApproved(), dto.getReason()));
|
||||
}
|
||||
|
||||
private Long requirePlatformAdmin(HttpServletRequest request) {
|
||||
Object value = request.getAttribute("userId");
|
||||
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
|
||||
Long userId = (Long) value;
|
||||
UserDO actor = userMapper.selectById(userId);
|
||||
if (actor == null || !Integer.valueOf(4).equals(actor.getType()) || !Integer.valueOf(1).equals(actor.getStatus())) {
|
||||
throw new IllegalArgumentException("无权处理内容复核");
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneBackfillReport;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneDataBackfillService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin/privacy/phone-backfill")
|
||||
public class AdminPhoneBackfillController {
|
||||
private final PhoneDataBackfillService backfillService;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@GetMapping("/report")
|
||||
public Result<PhoneBackfillReport> report(HttpServletRequest request) {
|
||||
requirePlatformAdmin(request);
|
||||
return Result.success(backfillService.backfill(true));
|
||||
}
|
||||
|
||||
@PostMapping("/run")
|
||||
public Result<PhoneBackfillReport> run(HttpServletRequest request) {
|
||||
requirePlatformAdmin(request);
|
||||
return Result.success(backfillService.backfill(false));
|
||||
}
|
||||
|
||||
private void requirePlatformAdmin(HttpServletRequest request) {
|
||||
Object value = request.getAttribute("userId");
|
||||
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
|
||||
UserDO actor = userMapper.selectById((Long) value);
|
||||
if (actor == null || !Integer.valueOf(4).equals(actor.getType()) || !Integer.valueOf(1).equals(actor.getStatus())) {
|
||||
throw new IllegalArgumentException("无权执行手机号数据处理");
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/user/account-closure")
|
||||
public class AccountClosureController {
|
||||
private final AccountClosureService accountClosureService;
|
||||
|
||||
@PostMapping
|
||||
@OperationGuard(action = "account-closure-request", ttlSeconds = 10, message = "注销申请处理中,请勿重复提交")
|
||||
public Result<AccountClosureRequestVO> request(HttpServletRequest request) {
|
||||
return Result.success(accountClosureService.request(userId(request)));
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public Result<AccountClosureRequestVO> getMine(HttpServletRequest request) {
|
||||
return Result.success(accountClosureService.getMine(userId(request)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/me")
|
||||
@OperationGuard(action = "account-closure-withdraw", ttlSeconds = 10, message = "撤回处理中,请勿重复操作")
|
||||
public Result<Boolean> withdraw(HttpServletRequest request) {
|
||||
return Result.success(accountClosureService.withdraw(userId(request)));
|
||||
}
|
||||
|
||||
private Long userId(HttpServletRequest request) {
|
||||
Object value = request.getAttribute("userId");
|
||||
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
|
||||
return (Long) value;
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AccountClosureProcessDTO {
|
||||
private String decision;
|
||||
private Long successorManagerId;
|
||||
private List<Long> archiveShopIds;
|
||||
private String note;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
@Data
|
||||
public class ContentModerationReviewDTO {
|
||||
private Boolean approved;
|
||||
@NotBlank
|
||||
private String reason;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@TableName("t_account_closure_request")
|
||||
public class AccountClosureRequestDO extends BaseEntity {
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String status;
|
||||
private LocalDateTime requestedAt;
|
||||
private LocalDateTime processedAt;
|
||||
private Long reviewerId;
|
||||
private String reviewerNote;
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@TableName("t_content_moderation_record")
|
||||
public class ContentModerationRecordDO extends BaseEntity {
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private String contentType;
|
||||
private Long businessId;
|
||||
private Long userId;
|
||||
private String status;
|
||||
private String provider;
|
||||
private String resultCode;
|
||||
private String reason;
|
||||
private String payloadJson;
|
||||
private Long reviewedBy;
|
||||
private LocalDateTime reviewedAt;
|
||||
private Integer attemptCount;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.AccountClosureRequestDO;
|
||||
|
||||
public interface AccountClosureRequestMapper extends BaseMapper<AccountClosureRequestDO> {
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
|
||||
|
||||
public interface ContentModerationRecordMapper extends BaseMapper<ContentModerationRecordDO> {
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
|
||||
|
||||
public interface ContentModerationProvider {
|
||||
String providerName();
|
||||
|
||||
ModerationOutcome review(String contentType, String content);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@ConditionalOnProperty(
|
||||
prefix = "jayucloud-salon.privacy.content-moderation",
|
||||
name = "provider",
|
||||
havingValue = "mock"
|
||||
)
|
||||
public class LocalMockContentModerationProvider implements ContentModerationProvider {
|
||||
@Override
|
||||
public String providerName() {
|
||||
return "LOCAL_MOCK";
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModerationOutcome review(String contentType, String content) {
|
||||
String value = content == null ? "" : content;
|
||||
if (value.contains("[[MOCK:FAIL]]")) throw new IllegalStateException("本地模拟审核故障");
|
||||
if (value.contains("[[MOCK:REJECT]]")) {
|
||||
return new ModerationOutcome(ModerationOutcome.Status.REJECTED, "MOCK_REJECT", "本地模拟命中拒绝场景");
|
||||
}
|
||||
if (value.contains("[[MOCK:PENDING]]")) {
|
||||
return new ModerationOutcome(ModerationOutcome.Status.PENDING, "MOCK_PENDING", "本地模拟进入人工复核");
|
||||
}
|
||||
if (value.contains("[[MOCK:APPROVE]]")) {
|
||||
return new ModerationOutcome(ModerationOutcome.Status.APPROVED, "MOCK_APPROVE", "本地模拟通过场景");
|
||||
}
|
||||
return new ModerationOutcome(ModerationOutcome.Status.PENDING, "MOCK_UNMATCHED", "未命中模拟场景,默认进入人工复核");
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
|
||||
|
||||
public record ModerationOutcome(Status status, String code, String reason) {
|
||||
public enum Status { APPROVED, PENDING, REJECTED, RETRY }
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@ConditionalOnProperty(
|
||||
prefix = "jayucloud-salon.privacy.content-moderation",
|
||||
name = "provider",
|
||||
havingValue = "disabled",
|
||||
matchIfMissing = true
|
||||
)
|
||||
public class UnconfiguredContentModerationProvider implements ContentModerationProvider {
|
||||
@Override
|
||||
public String providerName() {
|
||||
return "UNCONFIGURED";
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModerationOutcome review(String contentType, String content) {
|
||||
return new ModerationOutcome(
|
||||
ModerationOutcome.Status.RETRY,
|
||||
"PROVIDER_NOT_CONFIGURED",
|
||||
"内容审核平台尚未接入,内容已隔离等待人工复核"
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.service;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface AccountClosureService {
|
||||
AccountClosureRequestVO request(Long userId);
|
||||
AccountClosureRequestVO getMine(Long userId);
|
||||
boolean withdraw(Long userId);
|
||||
List<AccountClosureRequestVO> listPending();
|
||||
boolean process(Long reviewerId, Long requestId, AccountClosureProcessDTO dto);
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.service;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ContentModerationService {
|
||||
ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson);
|
||||
List<ContentModerationRecordDO> listPending();
|
||||
boolean review(Long reviewerId, Long recordId, boolean approved, String reason);
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
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.LambdaUpdateWrapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.AccountClosureRequestDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.AccountClosureRequestMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.entity.UserShopRoleDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.mapper.UserShopRoleMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.entity.UserShopBindingDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserRelationDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserRelationMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.mapper.SecurityAuditLogMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AccountClosureServiceImpl implements AccountClosureService {
|
||||
private static final String PENDING = "PENDING";
|
||||
private static final String WITHDRAWN = "WITHDRAWN";
|
||||
private static final String APPROVED = "APPROVED";
|
||||
private static final String REJECTED = "REJECTED";
|
||||
|
||||
private final AccountClosureRequestMapper requestMapper;
|
||||
private final UserMapper userMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final UserShopBindingMapper bindingMapper;
|
||||
private final UserShopRoleMapper shopRoleMapper;
|
||||
private final UserRelationMapper relationMapper;
|
||||
private final WechatMiniBindingMapper wechatBindingMapper;
|
||||
private final UserAgreementConsentMapper consentMapper;
|
||||
private final SecurityAuditLogMapper securityAuditLogMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final UserSessionService sessionService;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AccountClosureRequestVO request(Long userId) {
|
||||
UserDO user = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getId, userId).eq(UserDO::getIsDelete, 0).last("FOR UPDATE"));
|
||||
if (user == null) throw new IllegalStateException("账号不存在或已注销");
|
||||
if (Integer.valueOf(4).equals(user.getType())) throw new IllegalStateException("管理员账号不能申请注销");
|
||||
AccountClosureRequestDO pending = requestMapper.selectOne(new LambdaQueryWrapper<AccountClosureRequestDO>()
|
||||
.eq(AccountClosureRequestDO::getUserId, userId)
|
||||
.eq(AccountClosureRequestDO::getStatus, PENDING)
|
||||
.orderByDesc(AccountClosureRequestDO::getRequestedAt)
|
||||
.last("limit 1"));
|
||||
if (pending != null) return toVO(pending, user);
|
||||
|
||||
AccountClosureRequestDO request = new AccountClosureRequestDO();
|
||||
request.setUserId(userId);
|
||||
request.setStatus(PENDING);
|
||||
request.setRequestedAt(LocalDateTime.now());
|
||||
requestMapper.insert(request);
|
||||
return toVO(request, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccountClosureRequestVO getMine(Long userId) {
|
||||
AccountClosureRequestDO request = requestMapper.selectOne(new LambdaQueryWrapper<AccountClosureRequestDO>()
|
||||
.eq(AccountClosureRequestDO::getUserId, userId)
|
||||
.orderByDesc(AccountClosureRequestDO::getRequestedAt)
|
||||
.last("limit 1"));
|
||||
if (request == null) return null;
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
return toVO(request, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean withdraw(Long userId) {
|
||||
AccountClosureRequestDO request = requestMapper.selectOne(new LambdaQueryWrapper<AccountClosureRequestDO>()
|
||||
.eq(AccountClosureRequestDO::getUserId, userId)
|
||||
.eq(AccountClosureRequestDO::getStatus, PENDING)
|
||||
.orderByDesc(AccountClosureRequestDO::getRequestedAt)
|
||||
.last("limit 1"));
|
||||
if (request == null) return false;
|
||||
request.setStatus(WITHDRAWN);
|
||||
request.setProcessedAt(LocalDateTime.now());
|
||||
return requestMapper.updateById(request) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AccountClosureRequestVO> listPending() {
|
||||
return requestMapper.selectList(new LambdaQueryWrapper<AccountClosureRequestDO>()
|
||||
.eq(AccountClosureRequestDO::getStatus, PENDING)
|
||||
.orderByAsc(AccountClosureRequestDO::getRequestedAt))
|
||||
.stream()
|
||||
.map(request -> toVO(request, userMapper.selectById(request.getUserId())))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean process(Long reviewerId, Long requestId, AccountClosureProcessDTO dto) {
|
||||
if (dto == null || (!"APPROVE".equals(dto.getDecision()) && !"REJECT".equals(dto.getDecision()))) {
|
||||
throw new IllegalArgumentException("请选择批准或驳回");
|
||||
}
|
||||
AccountClosureRequestDO request = requestMapper.selectById(requestId);
|
||||
if (request == null || !PENDING.equals(request.getStatus())) throw new IllegalStateException("注销申请已处理或不存在");
|
||||
int claimed = requestMapper.update(null, new LambdaUpdateWrapper<AccountClosureRequestDO>()
|
||||
.eq(AccountClosureRequestDO::getId, requestId)
|
||||
.eq(AccountClosureRequestDO::getStatus, PENDING)
|
||||
.set(AccountClosureRequestDO::getStatus, "PROCESSING"));
|
||||
if (claimed != 1) throw new IllegalStateException("注销申请已处理或正在处理中");
|
||||
UserDO user = requireActiveUser(request.getUserId());
|
||||
if ("REJECT".equals(dto.getDecision())) {
|
||||
if (!StringUtils.hasText(dto.getNote())) throw new IllegalArgumentException("驳回原因不能为空");
|
||||
request.setStatus(REJECTED);
|
||||
request.setReviewerNote(dto.getNote().trim());
|
||||
} else {
|
||||
transferOrArchiveShops(user, dto);
|
||||
anonymizeUser(user);
|
||||
request.setStatus(APPROVED);
|
||||
request.setReviewerNote(StringUtils.hasText(dto.getNote()) ? dto.getNote().trim() : "已完成资料清理与会话撤销");
|
||||
}
|
||||
request.setReviewerId(reviewerId);
|
||||
request.setProcessedAt(LocalDateTime.now());
|
||||
return requestMapper.updateById(request) > 0;
|
||||
}
|
||||
|
||||
private void transferOrArchiveShops(UserDO user, AccountClosureProcessDTO dto) {
|
||||
List<UserShopBindingDO> bindings = bindingMapper.selectList(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, user.getId())
|
||||
.eq(UserShopBindingDO::getIsDelete, 0)
|
||||
.eq(UserShopBindingDO::getStatus, 1));
|
||||
if (bindings.isEmpty()) return;
|
||||
if (!Integer.valueOf(2).equals(user.getType())) {
|
||||
bindingMapper.update(null, new LambdaUpdateWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, user.getId()).eq(UserShopBindingDO::getIsDelete, 0)
|
||||
.set(UserShopBindingDO::getIsDelete, 1).set(UserShopBindingDO::getUpdateTime, LocalDateTime.now()));
|
||||
shopRoleMapper.update(null, new LambdaUpdateWrapper<UserShopRoleDO>()
|
||||
.eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0)
|
||||
.set(UserShopRoleDO::getIsDelete, 1).set(UserShopRoleDO::getUpdateTime, LocalDateTime.now()));
|
||||
return;
|
||||
}
|
||||
if (dto.getSuccessorManagerId() != null) {
|
||||
UserDO successor = requireActiveUser(dto.getSuccessorManagerId());
|
||||
if (!Integer.valueOf(2).equals(successor.getType()) || Objects.equals(successor.getId(), user.getId())) {
|
||||
throw new IllegalArgumentException("接手账号必须是其他已启用店长");
|
||||
}
|
||||
for (UserShopBindingDO binding : bindings) {
|
||||
UserShopBindingDO successorBinding = bindingMapper.selectOne(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, successor.getId())
|
||||
.eq(UserShopBindingDO::getShopId, binding.getShopId())
|
||||
.eq(UserShopBindingDO::getIsDelete, 0)
|
||||
.last("limit 1"));
|
||||
if (successorBinding == null) {
|
||||
bindingMapper.update(null, new LambdaUpdateWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getId, binding.getId())
|
||||
.set(UserShopBindingDO::getUserId, successor.getId())
|
||||
.set(UserShopBindingDO::getUpdateTime, LocalDateTime.now()));
|
||||
} else {
|
||||
bindingMapper.update(null, new LambdaUpdateWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getId, binding.getId())
|
||||
.set(UserShopBindingDO::getIsDelete, 1)
|
||||
.set(UserShopBindingDO::getUpdateTime, LocalDateTime.now()));
|
||||
}
|
||||
}
|
||||
List<UserShopRoleDO> roles = shopRoleMapper.selectList(new LambdaQueryWrapper<UserShopRoleDO>()
|
||||
.eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0));
|
||||
for (UserShopRoleDO role : roles) {
|
||||
UserShopRoleDO existing = shopRoleMapper.selectOne(new LambdaQueryWrapper<UserShopRoleDO>()
|
||||
.eq(UserShopRoleDO::getUserId, successor.getId())
|
||||
.eq(UserShopRoleDO::getShopId, role.getShopId())
|
||||
.eq(UserShopRoleDO::getRoleId, role.getRoleId())
|
||||
.eq(UserShopRoleDO::getIsDelete, 0)
|
||||
.last("limit 1"));
|
||||
if (existing == null) {
|
||||
shopRoleMapper.update(null, new LambdaUpdateWrapper<UserShopRoleDO>()
|
||||
.eq(UserShopRoleDO::getId, role.getId())
|
||||
.set(UserShopRoleDO::getUserId, successor.getId())
|
||||
.set(UserShopRoleDO::getUpdateTime, LocalDateTime.now()));
|
||||
} else {
|
||||
shopRoleMapper.update(null, new LambdaUpdateWrapper<UserShopRoleDO>()
|
||||
.eq(UserShopRoleDO::getId, role.getId())
|
||||
.set(UserShopRoleDO::getIsDelete, 1)
|
||||
.set(UserShopRoleDO::getUpdateTime, LocalDateTime.now()));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Set<Long> shopIds = bindings.stream().map(UserShopBindingDO::getShopId).collect(Collectors.toSet());
|
||||
if (dto.getArchiveShopIds() == null || !dto.getArchiveShopIds().containsAll(shopIds)) {
|
||||
throw new IllegalArgumentException("必须明确归档该账号关联的全部门店");
|
||||
}
|
||||
shopMapper.update(null, new LambdaUpdateWrapper<ShopDO>()
|
||||
.in(ShopDO::getId, shopIds)
|
||||
.set(ShopDO::getStatus, 0)
|
||||
.set(ShopDO::getUpdateTime, LocalDateTime.now()));
|
||||
bindingMapper.update(null, new LambdaUpdateWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, user.getId()).eq(UserShopBindingDO::getIsDelete, 0)
|
||||
.set(UserShopBindingDO::getIsDelete, 1).set(UserShopBindingDO::getUpdateTime, LocalDateTime.now()));
|
||||
shopRoleMapper.update(null, new LambdaUpdateWrapper<UserShopRoleDO>()
|
||||
.eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0)
|
||||
.set(UserShopRoleDO::getIsDelete, 1).set(UserShopRoleDO::getUpdateTime, LocalDateTime.now()));
|
||||
}
|
||||
|
||||
private void anonymizeUser(UserDO user) {
|
||||
Long userId = user.getId();
|
||||
sessionService.revokeAllUserSessions(userId);
|
||||
wechatBindingMapper.delete(new LambdaQueryWrapper<WechatMiniBindingDO>().eq(WechatMiniBindingDO::getUserId, userId));
|
||||
relationMapper.update(null, new LambdaUpdateWrapper<UserRelationDO>()
|
||||
.eq(UserRelationDO::getUserId, userId).eq(UserRelationDO::getIsDelete, 0)
|
||||
.set(UserRelationDO::getIsDelete, 1).set(UserRelationDO::getUpdateTime, LocalDateTime.now()));
|
||||
relationMapper.update(null, new LambdaUpdateWrapper<UserRelationDO>()
|
||||
.eq(UserRelationDO::getParentUserId, userId).eq(UserRelationDO::getIsDelete, 0)
|
||||
.set(UserRelationDO::getParentUserId, null).set(UserRelationDO::getUpdateTime, LocalDateTime.now()));
|
||||
orderMapper.update(null, new LambdaUpdateWrapper<OrderDO>()
|
||||
.eq(OrderDO::getUserId, userId)
|
||||
.set(OrderDO::getUserId, null)
|
||||
.set(OrderDO::getCustomerNameSnapshot, "已注销用户")
|
||||
.set(OrderDO::getCustomerPhoneSnapshot, null)
|
||||
.set(OrderDO::getCustomerPhoneSnapshotHash, null)
|
||||
.set(OrderDO::getUpdateTime, LocalDateTime.now()));
|
||||
consentMapper.update(null, new LambdaUpdateWrapper<com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO>()
|
||||
.eq(com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO::getUserId, userId)
|
||||
.set(com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO::getUserId, null));
|
||||
securityAuditLogMapper.update(null, new LambdaUpdateWrapper<com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO>()
|
||||
.eq(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getUserId, userId)
|
||||
.set(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getUserId, null)
|
||||
.set(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getAccount, "已注销用户"));
|
||||
user.setNickname("已注销用户");
|
||||
user.setAccount(null);
|
||||
user.setAccountHash(null);
|
||||
user.setPassword(null);
|
||||
user.setPhone(null);
|
||||
user.setPhoneHash(null);
|
||||
user.setContactPhone(null);
|
||||
user.setContactPhoneHash(null);
|
||||
user.setPhoneVerified(0);
|
||||
user.setEmail(null);
|
||||
user.setEmailVerified(0);
|
||||
user.setBirthday(null);
|
||||
user.setWechatId(null);
|
||||
user.setWechatQrCode(null);
|
||||
user.setAvatar(null);
|
||||
user.setSignature(null);
|
||||
user.setShopId(null);
|
||||
user.setStatus(0);
|
||||
user.setIsDelete(1);
|
||||
user.setUpdateTime(LocalDateTime.now());
|
||||
userMapper.updateById(user);
|
||||
}
|
||||
|
||||
private UserDO requireActiveUser(Long userId) {
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) throw new IllegalStateException("账号不存在或已注销");
|
||||
return user;
|
||||
}
|
||||
|
||||
private AccountClosureRequestVO toVO(AccountClosureRequestDO request, UserDO user) {
|
||||
AccountClosureRequestVO vo = new AccountClosureRequestVO();
|
||||
vo.setId(request.getId());
|
||||
vo.setUserId(request.getUserId());
|
||||
vo.setNickname(user == null ? "已注销用户" : user.getNickname());
|
||||
vo.setUserType(user == null ? null : user.getType());
|
||||
vo.setStatus(request.getStatus());
|
||||
vo.setRequestedAt(request.getRequestedAt());
|
||||
vo.setProcessingTargetText("目标:15个工作日内完成,具体时长视门店移交或归档流程而定。");
|
||||
if (user != null && Integer.valueOf(2).equals(user.getType())) {
|
||||
List<UserShopBindingDO> bindings = bindingMapper.selectList(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, user.getId())
|
||||
.eq(UserShopBindingDO::getIsDelete, 0)
|
||||
.eq(UserShopBindingDO::getStatus, 1));
|
||||
List<Long> shopIds = bindings.stream().map(UserShopBindingDO::getShopId).distinct().collect(Collectors.toList());
|
||||
vo.setShopIds(shopIds);
|
||||
vo.setShopNames(shopIds.isEmpty() ? List.of() : shopMapper.selectBatchIds(shopIds).stream().map(ShopDO::getShopName).collect(Collectors.toList()));
|
||||
}
|
||||
vo.setProcessedAt(request.getProcessedAt());
|
||||
vo.setReviewerNote(request.getReviewerNote());
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ContentModerationProvider;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ContentModerationServiceImpl implements ContentModerationService {
|
||||
private final ContentModerationProvider provider;
|
||||
private final ContentModerationRecordMapper recordMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final CommentMapper commentMapper;
|
||||
private final UserMapper userMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
|
||||
public ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson) {
|
||||
ModerationOutcome outcome;
|
||||
try {
|
||||
outcome = provider.review(contentType, content);
|
||||
} catch (RuntimeException exception) {
|
||||
outcome = new ModerationOutcome(ModerationOutcome.Status.RETRY, "PROVIDER_FAILURE", "内容审核服务暂不可用,内容已隔离等待重试");
|
||||
}
|
||||
ContentModerationRecordDO record = new ContentModerationRecordDO();
|
||||
record.setContentType(contentType);
|
||||
record.setBusinessId(businessId);
|
||||
record.setUserId(userId);
|
||||
record.setStatus(outcome.status().name());
|
||||
record.setProvider(provider.providerName());
|
||||
record.setResultCode(outcome.code());
|
||||
record.setReason(outcome.reason());
|
||||
record.setPayloadJson(outcome.status() == ModerationOutcome.Status.APPROVED ? null : payloadJson);
|
||||
record.setAttemptCount(1);
|
||||
recordMapper.insert(record);
|
||||
|
||||
ContentModerationResultVO result = new ContentModerationResultVO();
|
||||
result.setRecordId(record.getId());
|
||||
result.setStatus(outcome.status().name());
|
||||
result.setReason(outcome.reason());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ContentModerationRecordDO> listPending() {
|
||||
return recordMapper.selectList(new LambdaQueryWrapper<ContentModerationRecordDO>()
|
||||
.in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY")
|
||||
.orderByAsc(ContentModerationRecordDO::getCreateTime));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean review(Long reviewerId, Long recordId, boolean approved, String reason) {
|
||||
if (!StringUtils.hasText(reason)) throw new IllegalArgumentException("复核说明不能为空");
|
||||
ContentModerationRecordDO record = recordMapper.selectById(recordId);
|
||||
if (record == null || !("PENDING".equals(record.getStatus()) || "RETRY".equals(record.getStatus()))) {
|
||||
throw new IllegalStateException("该内容已复核或不存在");
|
||||
}
|
||||
if (approved) applyApprovedPayload(record);
|
||||
if ("COMMENT".equals(record.getContentType()) && record.getBusinessId() != null) {
|
||||
CommentDO comment = commentMapper.selectById(record.getBusinessId());
|
||||
if (comment != null && !Integer.valueOf(1).equals(comment.getIsDelete())) {
|
||||
comment.setModerationStatus(approved ? "APPROVED" : "REJECTED");
|
||||
comment.setUpdateTime(LocalDateTime.now());
|
||||
commentMapper.updateById(comment);
|
||||
}
|
||||
}
|
||||
record.setStatus(approved ? "APPROVED" : "REJECTED");
|
||||
record.setReviewedBy(reviewerId);
|
||||
record.setReviewedAt(LocalDateTime.now());
|
||||
record.setReason(reason.trim());
|
||||
record.setPayloadJson(null);
|
||||
return recordMapper.updateById(record) > 0;
|
||||
}
|
||||
|
||||
private void applyApprovedPayload(ContentModerationRecordDO record) {
|
||||
if (!StringUtils.hasText(record.getPayloadJson())) return;
|
||||
try {
|
||||
JsonNode payload = objectMapper.readTree(record.getPayloadJson());
|
||||
if ("PRODUCT".equals(record.getContentType()) && record.getBusinessId() != null) {
|
||||
ProductDO product = productMapper.selectById(record.getBusinessId());
|
||||
if (product != null && !Integer.valueOf(1).equals(product.getIsDelete())) {
|
||||
product.setFrontVisible(payload.path("frontVisible").asInt(1));
|
||||
product.setUpdateTime(LocalDateTime.now());
|
||||
productMapper.updateById(product);
|
||||
}
|
||||
} else if (("USER_PROFILE".equals(record.getContentType()) || "USER_AVATAR".equals(record.getContentType()))
|
||||
&& record.getUserId() != null) {
|
||||
UserDO user = userMapper.selectById(record.getUserId());
|
||||
if (user != null && !Integer.valueOf(1).equals(user.getIsDelete())) {
|
||||
if (payload.hasNonNull("nickname")) user.setNickname(payload.path("nickname").asText());
|
||||
if (payload.hasNonNull("signature")) user.setSignature(payload.path("signature").asText());
|
||||
if (payload.hasNonNull("avatar")) user.setAvatar(payload.path("avatar").asText());
|
||||
user.setUpdateTime(LocalDateTime.now());
|
||||
userMapper.updateById(user);
|
||||
}
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("隔离内容载荷无法解析,未应用复核结果", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AccountClosureRequestVO {
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String nickname;
|
||||
private Integer userType;
|
||||
private List<Long> shopIds;
|
||||
private List<String> shopNames;
|
||||
private String status;
|
||||
private LocalDateTime requestedAt;
|
||||
private String processingTargetText;
|
||||
private LocalDateTime processedAt;
|
||||
private String reviewerNote;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ClosureSuccessorManagerVO {
|
||||
private Long id;
|
||||
private String nickname;
|
||||
private Long shopId;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ContentModerationResultVO {
|
||||
private Long recordId;
|
||||
private String status;
|
||||
private String reason;
|
||||
}
|
||||
+35
-2
@@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.dto.ProductDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.entity.CouponDO;
|
||||
@@ -24,8 +26,11 @@ import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.vo.ProductVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.vo.TagInfo;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
@@ -113,6 +118,8 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
* Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AppCacheProperties appCacheProperties;
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
/**
|
||||
@@ -121,6 +128,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
* @param productDTO parameter `productDTO` supplied by the caller
|
||||
* @return Long result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Long createProduct(ProductDTO productDTO) {
|
||||
validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists());
|
||||
validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons());
|
||||
@@ -138,10 +146,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
productDO.setApproximateDuration(productDTO.getApproximateDuration());
|
||||
productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()));
|
||||
productDO.setAvailableCoupons(productDTO.getAvailableCoupons());
|
||||
productDO.setFrontVisible(resolveFrontVisible(productDTO.getFrontVisible()));
|
||||
Integer requestedFrontVisible = resolveFrontVisible(productDTO.getFrontVisible());
|
||||
productDO.setFrontVisible(0);
|
||||
productDO.setSourceType(resolveSourceType(productDTO.getSourceType()));
|
||||
productDO.setIsDelete(0);
|
||||
productMapper.insert(productDO);
|
||||
ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible);
|
||||
productDO.setFrontVisible("APPROVED".equals(moderation.getStatus()) ? requestedFrontVisible : 0);
|
||||
productMapper.updateById(productDO);
|
||||
evictPublicProductCaches(productDO.getId());
|
||||
return productDO.getId();
|
||||
}
|
||||
@@ -154,6 +166,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
* @param productDTO parameter `productDTO` supplied by the caller
|
||||
* @return boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateProduct(Long id, ProductDTO productDTO) {
|
||||
ProductDO productDO = productMapper.selectById(id);
|
||||
if (productDO == null) {
|
||||
@@ -178,10 +191,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
productDO.setApproximateDuration(productDTO.getApproximateDuration());
|
||||
productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()));
|
||||
productDO.setAvailableCoupons(productDTO.getAvailableCoupons());
|
||||
productDO.setFrontVisible(resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible()));
|
||||
Integer requestedFrontVisible = resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible());
|
||||
productDO.setFrontVisible(0);
|
||||
productDO.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType()));
|
||||
boolean updated = productMapper.updateById(productDO) > 0;
|
||||
if (updated) {
|
||||
ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible);
|
||||
productDO.setFrontVisible("APPROVED".equals(moderation.getStatus()) ? requestedFrontVisible : 0);
|
||||
productMapper.updateById(productDO);
|
||||
/**
|
||||
* Run business method `evictPublicProductCaches`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -193,6 +210,22 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
return updated;
|
||||
}
|
||||
|
||||
private ContentModerationResultVO assessProduct(ProductDO product, Integer requestedFrontVisible) {
|
||||
String content = String.join("\n", List.of(
|
||||
safe(product.getTitle()), safe(product.getDescription()), safe(product.getTargetAudience()),
|
||||
safe(product.getPrecautions()), safe(product.getTags()), safe(product.getImageFileIds())));
|
||||
try {
|
||||
String payload = objectMapper.writeValueAsString(java.util.Map.of("frontVisible", requestedFrontVisible == null ? 1 : requestedFrontVisible));
|
||||
return contentModerationService.assess("PRODUCT", product.getId(), null, content, payload);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new IllegalStateException("作品审核内容序列化失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String safe(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Delete, revoke, or logically remove a record.
|
||||
|
||||
+9
-1
@@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -38,7 +39,14 @@ public class WorkbenchRegistrationController {
|
||||
|
||||
@GetMapping("/register/status")
|
||||
public Result<WorkbenchRegistrationStatusVO> status(@RequestParam String phone) {
|
||||
UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getPhone, phone).eq(UserDO::getIsDelete, 0).last("limit 1"));
|
||||
String normalizedPhone = phone == null ? "" : phone.trim();
|
||||
UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhoneHash, PhoneCrypto.current().index(normalizedPhone))
|
||||
.eq(UserDO::getIsDelete, 0).last("limit 1"));
|
||||
if (user == null) {
|
||||
Long legacyId = userMapper.findLegacyIdByPhone(normalizedPhone);
|
||||
user = legacyId == null ? null : userMapper.selectById(legacyId);
|
||||
}
|
||||
if (user == null) {
|
||||
throw new IllegalArgumentException("未找到注册申请");
|
||||
}
|
||||
|
||||
-7
@@ -60,13 +60,6 @@ public class SecurityAuditLogDO extends BaseEntity {
|
||||
*/
|
||||
private String ipAddress;
|
||||
|
||||
@TableField("device_id")
|
||||
/**
|
||||
* Purpose: deviceId supports SecurityAuditLogDO.java by holding or executing the device id business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String deviceId;
|
||||
|
||||
@TableField("operate_time")
|
||||
/**
|
||||
* Purpose: operateTime supports SecurityAuditLogDO.java by holding or executing the operate time business role.
|
||||
|
||||
+9
-4
@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.mapper.SecurityAuditLogMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
||||
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.vo.SecurityAuditLogVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -38,12 +37,11 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
|
||||
try {
|
||||
SecurityAuditLogDO log = new SecurityAuditLogDO();
|
||||
log.setUserId(userId);
|
||||
log.setAccount(limit(account, 80));
|
||||
log.setAccount(maskPhoneAccount(account));
|
||||
log.setAction(limit(action, 80));
|
||||
log.setResult(limit(result, 20));
|
||||
log.setReason(limit(reason, 500));
|
||||
log.setIpAddress(limit(resolveClientIp(request), 80));
|
||||
log.setDeviceId(limit(request == null ? null : request.getHeader(RequestThrottleService.DEVICE_ID_HEADER), 120));
|
||||
log.setOperateTime(LocalDateTime.now());
|
||||
auditLogMapper.insert(log);
|
||||
} catch (Exception ignored) {
|
||||
@@ -101,7 +99,6 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
|
||||
vo.setResult(log.getResult());
|
||||
vo.setReason(log.getReason());
|
||||
vo.setIpAddress(log.getIpAddress());
|
||||
vo.setDeviceId(log.getDeviceId());
|
||||
vo.setOperateTime(log.getOperateTime());
|
||||
return vo;
|
||||
}
|
||||
@@ -132,4 +129,12 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
|
||||
}
|
||||
return value.substring(0, max);
|
||||
}
|
||||
|
||||
private String maskPhoneAccount(String value) {
|
||||
if (value == null) return null;
|
||||
String normalized = value.trim();
|
||||
return normalized.matches("1[3-9]\\d{9}")
|
||||
? normalized.substring(0, 3) + "****" + normalized.substring(7)
|
||||
: limit(normalized, 80);
|
||||
}
|
||||
}
|
||||
|
||||
-5
@@ -46,11 +46,6 @@ public class SecurityAuditLogVO {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String ipAddress;
|
||||
/**
|
||||
* Purpose: deviceId supports SecurityAuditLogVO.java by holding or executing the device id business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String deviceId;
|
||||
/**
|
||||
* Purpose: operateTime supports SecurityAuditLogVO.java by holding or executing the operate time business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
|
||||
+2
-4
@@ -201,8 +201,7 @@ public class LegalAgreementServiceImpl implements LegalAgreementService {
|
||||
version,
|
||||
entry,
|
||||
clientType,
|
||||
resolveClientIp(httpRequest),
|
||||
httpRequest == null ? null : httpRequest.getHeader(RequestThrottleService.DEVICE_ID_HEADER)
|
||||
resolveClientIp(httpRequest)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -225,7 +224,7 @@ public class LegalAgreementServiceImpl implements LegalAgreementService {
|
||||
* Purpose: upsertConsent supports LegalAgreementServiceImpl.java by holding or executing the upsert consent business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip, String deviceId) {
|
||||
private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip) {
|
||||
if (!StringUtils.hasText(version)) {
|
||||
return;
|
||||
}
|
||||
@@ -240,7 +239,6 @@ public class LegalAgreementServiceImpl implements LegalAgreementService {
|
||||
consent.setEntry(entry);
|
||||
consent.setClientType(clientType);
|
||||
consent.setIpAddress(ip);
|
||||
consent.setDeviceId(deviceId);
|
||||
consent.setConsentTime(LocalDateTime.now());
|
||||
if (existing == null) {
|
||||
consentMapper.insert(consent);
|
||||
|
||||
+77
-25
@@ -23,8 +23,10 @@ import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleServic
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService;
|
||||
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.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
||||
import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils;
|
||||
@@ -124,6 +126,7 @@ 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;
|
||||
private final AccountClosureService accountClosureService;
|
||||
/**
|
||||
* 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.
|
||||
@@ -343,10 +346,7 @@ public class UserController {
|
||||
*/
|
||||
public Result<AvailabilityVO> checkAccountAvailability(@PathVariable String account) {
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
);
|
||||
UserDO userDO = findUserByAccount(normalizedAccount);
|
||||
boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete());
|
||||
String message = available ? "账号可用" : "账号已被注册";
|
||||
return Result.success(new AvailabilityVO(available, message));
|
||||
@@ -361,12 +361,7 @@ public class UserController {
|
||||
*/
|
||||
public Result<LoginAccountAvailabilityVO> checkLoginAccountAvailability(@PathVariable String account) {
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO userDO = findUserByAccount(normalizedAccount);
|
||||
boolean exists = userDO != null;
|
||||
String nickname = exists ? userDO.getNickname() : null;
|
||||
String message = exists
|
||||
@@ -405,11 +400,14 @@ public class UserController {
|
||||
* @return Result<AvailabilityVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
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::getIsDelete, 0)
|
||||
);
|
||||
String normalizedPhone = phone == null ? "" : phone.trim();
|
||||
UserDO userDO = userMapper.selectOne(com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhoneHash, PhoneCrypto.current().index(normalizedPhone))
|
||||
.eq(UserDO::getIsDelete, 0));
|
||||
if (userDO == null) {
|
||||
Long legacyId = userMapper.findLegacyIdByPhone(normalizedPhone);
|
||||
userDO = legacyId == null ? null : userMapper.selectById(legacyId);
|
||||
}
|
||||
boolean available = userDO == null;
|
||||
String message = available ? "手机号可用" : "该手机号已被注册";
|
||||
return Result.success(new AvailabilityVO(available, message));
|
||||
@@ -473,13 +471,18 @@ public class UserController {
|
||||
* @param requestDTO parameter `requestDTO` supplied by the caller
|
||||
* @return Result<WechatMiniLoginResultVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<WechatMiniLoginResultVO> wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
|
||||
return Result.success(wechatMiniAuthService.autoLogin(requestDTO));
|
||||
public Result<WechatMiniLoginResultVO> wechatMiniAutoLogin(HttpServletRequest request,
|
||||
@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
|
||||
legalAgreementService.requireAccepted(requestDTO);
|
||||
WechatMiniLoginResultVO result = wechatMiniAuthService.autoLogin(requestDTO);
|
||||
recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_AUTO_LOGIN", request);
|
||||
return Result.success(result);
|
||||
}
|
||||
|
||||
@PostMapping("/wechat-mini/status")
|
||||
@OperationGuard(action = "wechat-mini-status", ttlSeconds = 2, message = "状态检测中,请稍后重试")
|
||||
public Result<WechatMiniLoginResultVO> wechatMiniStatus(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
|
||||
legalAgreementService.requireAccepted(requestDTO);
|
||||
return Result.success(wechatMiniAuthService.status(requestDTO));
|
||||
}
|
||||
|
||||
@@ -553,12 +556,7 @@ public class UserController {
|
||||
legalAgreementService.requireAccepted(registerRequestDTO);
|
||||
try {
|
||||
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::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO userDO = findUserByAccount(AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()));
|
||||
if (userDO != null) {
|
||||
legalAgreementService.recordConsent(userDO.getId(), registerRequestDTO, "USER_REGISTER", request);
|
||||
securityAuditLogService.record(userDO.getId(), userDO.getAccount(), "USER_REGISTER", "SUCCESS", null, request);
|
||||
@@ -616,6 +614,30 @@ public class UserController {
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
@PostMapping("/send-current-password-code")
|
||||
@OperationGuard(action = "send-current-password-code", ttlSeconds = 60, message = "验证码已发送,请勿重复操作")
|
||||
public Result<Boolean> sendCurrentPasswordVerificationCode(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
if (userId == null) {
|
||||
throw new RuntimeException("请登录后操作");
|
||||
}
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
if (user == null || Integer.valueOf(1).equals(user.getIsDelete())
|
||||
|| (user.getStatus() != null && !Integer.valueOf(1).equals(user.getStatus()))
|
||||
|| !org.springframework.util.StringUtils.hasText(user.getPhone())
|
||||
|| !Integer.valueOf(1).equals(user.getPhoneVerified())) {
|
||||
throw new RuntimeException("当前账号未绑定已验证手机号");
|
||||
}
|
||||
|
||||
String phone = user.getPhone();
|
||||
requestThrottleService.checkSendCode(request, phone);
|
||||
if (!verificationCodeService.canResend(phone)) {
|
||||
throw new RuntimeException("验证码发送过于频繁,请1分钟后再试");
|
||||
}
|
||||
verificationCodeService.sendVerificationCode(phone, "USER_CHANGE_PASSWORD_SMS_CODE");
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过手机号验证码重置密码
|
||||
*
|
||||
@@ -715,6 +737,20 @@ public class UserController {
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@PostMapping("/unbind-phone")
|
||||
@OperationGuard(action = "user-unbind-phone", ttlSeconds = 10, message = "手机号解绑处理中,请勿重复提交")
|
||||
public Result<Boolean> unbindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(userService.unbindPhone(userId, requestDTO == null ? null : requestDTO.getVerificationCode()));
|
||||
}
|
||||
|
||||
@PostMapping("/unbind-phone/send-code")
|
||||
@OperationGuard(action = "user-unbind-phone-send-code", ttlSeconds = 60, message = "验证码已发送,请勿重复操作")
|
||||
public Result<Boolean> sendUnbindPhoneCode(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(userService.sendUnbindPhoneCode(userId));
|
||||
}
|
||||
|
||||
@PostMapping("/wechat-mini/bind-phone")
|
||||
@OperationGuard(action = "wechat-mini-bind-phone", ttlSeconds = 10, message = "手机号绑定处理中,请勿重复提交")
|
||||
public Result<Boolean> bindWechatMiniPhone(HttpServletRequest request,
|
||||
@@ -981,8 +1017,8 @@ public class UserController {
|
||||
return Result.error("管理员账号无法注销");
|
||||
}
|
||||
|
||||
boolean success = userService.deleteUser(userId);
|
||||
return Result.success(success);
|
||||
accountClosureService.request(userId);
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1029,6 +1065,22 @@ public class UserController {
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
private UserDO findUserByAccount(String account) {
|
||||
String normalized = account == null ? "" : account.trim();
|
||||
boolean phoneAccount = PhoneCrypto.current().isMobilePhone(normalized);
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserDO> query =
|
||||
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1");
|
||||
query.eq(UserDO::getAccountHash, PhoneCrypto.current().index(normalized));
|
||||
UserDO user = userMapper.selectOne(query);
|
||||
if (user == null) {
|
||||
Long legacyId = userMapper.findLegacyIdByAccount(normalized);
|
||||
user = legacyId == null ? null : userMapper.selectById(legacyId);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
@Data
|
||||
/**
|
||||
* Purpose: PasswordDTO supports UserController.java by holding or executing the password dto business role.
|
||||
|
||||
-7
@@ -59,13 +59,6 @@ public class UserAgreementConsentDO extends BaseEntity {
|
||||
*/
|
||||
private String ipAddress;
|
||||
|
||||
@TableField("device_id")
|
||||
/**
|
||||
* Purpose: deviceId supports UserAgreementConsentDO.java by holding or executing the device id business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String deviceId;
|
||||
|
||||
@TableField("consent_time")
|
||||
/**
|
||||
* Purpose: consentTime supports UserAgreementConsentDO.java by holding or executing the consent time business role.
|
||||
|
||||
+16
-4
@@ -5,6 +5,9 @@ import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneEncryptionTypeHandler;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.AccountPhoneTypeHandler;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.EqualsAndHashCode;
|
||||
@@ -22,7 +25,7 @@ import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
|
||||
@Getter
|
||||
@Setter
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_user")
|
||||
@TableName(value = "t_user", autoResultMap = true)
|
||||
public class UserDO extends BaseEntity {
|
||||
|
||||
/**
|
||||
@@ -46,21 +49,30 @@ public class UserDO extends BaseEntity {
|
||||
/**
|
||||
* 用户账号(登录用)
|
||||
*/
|
||||
@TableField("account")
|
||||
@TableField(value = "account", typeHandler = AccountPhoneTypeHandler.class)
|
||||
private String account;
|
||||
|
||||
@TableField(value = "account_hash", fill = FieldFill.INSERT_UPDATE)
|
||||
private String accountHash;
|
||||
|
||||
/**
|
||||
* 手机号
|
||||
*/
|
||||
@TableField("phone")
|
||||
@TableField(value = "phone", typeHandler = PhoneEncryptionTypeHandler.class)
|
||||
private String phone;
|
||||
|
||||
@TableField(value = "phone_hash", fill = FieldFill.INSERT_UPDATE)
|
||||
private String phoneHash;
|
||||
|
||||
/**
|
||||
* 联系电话
|
||||
*/
|
||||
@TableField("contact_phone")
|
||||
@TableField(value = "contact_phone", typeHandler = PhoneEncryptionTypeHandler.class)
|
||||
private String contactPhone;
|
||||
|
||||
@TableField(value = "contact_phone_hash", fill = FieldFill.INSERT_UPDATE)
|
||||
private String contactPhoneHash;
|
||||
|
||||
/**
|
||||
* 生日
|
||||
*/
|
||||
|
||||
+16
@@ -2,6 +2,10 @@ package com.xiaowang.jayucloud.salon.core.modules.user.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统用户信息表 Mapper
|
||||
@@ -11,4 +15,16 @@ import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
public interface UserMapper extends BaseMapper<UserDO> {
|
||||
|
||||
@Select("SELECT id FROM t_user WHERE account = #{account} AND account_hash IS NULL AND is_delete = 0 LIMIT 1")
|
||||
Long findLegacyIdByAccount(@Param("account") String account);
|
||||
|
||||
@Select("SELECT id FROM t_user WHERE phone = #{phone} AND phone_hash IS NULL AND is_delete = 0 LIMIT 1")
|
||||
Long findLegacyIdByPhone(@Param("phone") String phone);
|
||||
|
||||
@Select("SELECT id FROM t_user WHERE contact_phone = #{phone} AND contact_phone_hash IS NULL AND is_delete = 0 LIMIT 1")
|
||||
Long findLegacyIdByContactPhone(@Param("phone") String phone);
|
||||
|
||||
@Select("SELECT id FROM t_user WHERE contact_phone = #{phone} AND contact_phone_hash IS NULL AND is_delete = 0")
|
||||
List<Long> findLegacyIdsByContactPhone(@Param("phone") String phone);
|
||||
}
|
||||
|
||||
+4
@@ -241,6 +241,10 @@ public interface UserService extends IService<UserDO> {
|
||||
*/
|
||||
boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO);
|
||||
|
||||
boolean unbindPhone(Long userId, String verificationCode);
|
||||
|
||||
boolean sendUnbindPhoneCode(Long userId);
|
||||
|
||||
/**
|
||||
* Run business method `bindEmail`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+161
-111
@@ -38,10 +38,15 @@ import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSu
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.PermissionCatalog;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService;
|
||||
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.security.support.PermissionPolicy;
|
||||
import com.xiaowang.jayucloud.salon.core.support.RequestShopContext;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.support.UserProfileFieldSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils;
|
||||
import com.xiaowang.jayucloud.salon.core.utils.JwtUtil;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO;
|
||||
@@ -134,6 +139,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final UserMapper userMapper;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
/**
|
||||
* Variable `jwtUtil`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
@@ -363,11 +371,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private Long createUserInternal(UserDTO userDTO, boolean allowMissingCustomerPhone) {
|
||||
String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount());
|
||||
// 检查账号是否已存在
|
||||
UserDO existingUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, validatedAccount)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
UserDO existingUser = findUserByAccount(validatedAccount);
|
||||
if (existingUser != null) {
|
||||
/**
|
||||
* Run business method `RuntimeException`.
|
||||
@@ -508,8 +512,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.eq(UserDO::getIsDelete, 0);
|
||||
if (StringUtils.hasText(phone)) {
|
||||
String normalizedPhone = phone.trim();
|
||||
wrapper.and(query -> query.eq(UserDO::getPhone, normalizedPhone)
|
||||
.or().eq(UserDO::getContactPhone, normalizedPhone));
|
||||
addPhoneMatch(wrapper, normalizedPhone);
|
||||
}
|
||||
if (shopId != null && shopId > 0) {
|
||||
List<Long> shopUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
|
||||
@@ -524,9 +527,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
UserVO customer = new UserVO();
|
||||
customer.setId(user.getId());
|
||||
customer.setNickname(user.getNickname());
|
||||
customer.setAccount(user.getAccount());
|
||||
customer.setPhone(user.getPhone());
|
||||
customer.setContactPhone(user.getContactPhone());
|
||||
customer.setAccount(phoneCrypto.mask(user.getAccount()));
|
||||
customer.setPhone(phoneCrypto.mask(user.getPhone()));
|
||||
customer.setContactPhone(phoneCrypto.mask(user.getContactPhone()));
|
||||
customer.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
|
||||
return customer;
|
||||
}).collect(Collectors.toList());
|
||||
@@ -594,11 +597,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
// 更新账号(如果提供且变更)
|
||||
String normalizedAccount = AccountValidationUtils.validateOptionalAccount(userDTO.getAccount());
|
||||
if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) {
|
||||
UserDO existingUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
UserDO existingUser = findUserByAccount(normalizedAccount);
|
||||
if (existingUser != null && Objects.equals(existingUser.getId(), id)) existingUser = null;
|
||||
if (existingUser != null) {
|
||||
/**
|
||||
* Run business method `RuntimeException`.
|
||||
@@ -721,7 +721,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.eq(UserDO::getId, id)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.set(UserDO::getAccount, buildDeletedAccount(userDO))
|
||||
.set(UserDO::getPhone, buildDeletedPhone(userDO))
|
||||
.set(UserDO::getPhone, null)
|
||||
.set(UserDO::getContactPhone, null)
|
||||
.set(UserDO::getPhoneHash, null)
|
||||
.set(UserDO::getContactPhoneHash, null)
|
||||
.set(UserDO::getAccountHash, null)
|
||||
.set(UserDO::getStatus, 0)
|
||||
.set(UserDO::getIsDelete, 1)
|
||||
.set(UserDO::getUpdateTime, now)
|
||||
@@ -809,11 +813,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
@Override
|
||||
public UserVO getUserByAccount(String account) {
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
UserDO userDO = findUserByAccount(normalizedAccount);
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
@@ -853,10 +853,10 @@ 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.setAccount(phoneCrypto.mask(userDO.getAccount()));
|
||||
userVO.setPhone(phoneCrypto.mask(userDO.getPhone()));
|
||||
userVO.setPhoneVerified(userDO.getPhoneVerified());
|
||||
userVO.setContactPhone(userDO.getContactPhone());
|
||||
userVO.setContactPhone(phoneCrypto.mask(userDO.getContactPhone()));
|
||||
userVO.setBirthday(userDO.getBirthday());
|
||||
userVO.setWechatId(userDO.getWechatId());
|
||||
userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode()));
|
||||
@@ -930,12 +930,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
AccountValidationUtils.ensureValidAccountFormat(normalizedAccount);
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO userDO = findUserByAccount(normalizedAccount);
|
||||
if (userDO == null) {
|
||||
return buildLoginShopSelection(List.of(), false, "该账号不存在");
|
||||
}
|
||||
@@ -980,12 +975,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺");
|
||||
}
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, normalizedPhone)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO userDO = findUserByPhone(normalizedPhone);
|
||||
if (userDO == null) {
|
||||
return buildLoginShopSelection(
|
||||
userShopBindingSupport.listAllActiveShopOptions(),
|
||||
@@ -1035,12 +1025,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
AccountValidationUtils.ensureValidAccountFormat(normalizedAccount);
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO userDO = findUserByAccount(normalizedAccount);
|
||||
if (userDO == null) {
|
||||
return buildLoginShopSelection(List.of(), false, "该账号不存在");
|
||||
}
|
||||
@@ -1083,10 +1068,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
public LoginResponseVO login(LoginRequestDTO loginRequestDTO) {
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount());
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
);
|
||||
UserDO userDO = findUserByAccount(normalizedAccount);
|
||||
|
||||
/**
|
||||
* Run business method `assertLoginAccountAvailable`.
|
||||
@@ -1157,11 +1139,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private LoginResponseVO phoneLoginByVerifiedPhone(String phone, Long shopId, boolean rememberMe) {
|
||||
String normalizedPhone = normalizeVerifiedPhone(phone);
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, normalizedPhone)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
UserDO userDO = findUserByPhone(normalizedPhone);
|
||||
|
||||
if (userDO == null) {
|
||||
return buildRegistrationRequiredResponse(normalizedPhone, null, "PHONE_NOT_REGISTERED");
|
||||
@@ -1218,12 +1196,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @return LoginResponseVO result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) {
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, phone)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO userDO = findUserByPhone(phone);
|
||||
|
||||
if (userDO == null) {
|
||||
if (shopId == null || shopId == 0) {
|
||||
@@ -1331,10 +1304,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
public LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO) {
|
||||
String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount());
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
);
|
||||
UserDO userDO = findUserByAccount(normalizedAccount);
|
||||
|
||||
/**
|
||||
* Run business method `assertLoginAccountAvailable`.
|
||||
@@ -1540,10 +1510,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
throw new RuntimeException("验证码错误或已过期");
|
||||
}
|
||||
|
||||
UserDO existingUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, validatedAccount)
|
||||
);
|
||||
UserDO existingUser = findUserByAccount(validatedAccount);
|
||||
|
||||
if (existingUser != null) {
|
||||
if (existingUser.getIsDelete() == 0) {
|
||||
@@ -1563,11 +1530,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
}
|
||||
|
||||
UserDO existingPhoneUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, registerRequestDTO.getPhone())
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
UserDO existingPhoneUser = findUserByPhone(registerRequestDTO.getPhone());
|
||||
|
||||
if (existingPhoneUser != null) {
|
||||
/**
|
||||
@@ -1633,12 +1596,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
throw new RuntimeException("店铺名称不能为空");
|
||||
}
|
||||
|
||||
UserDO existingUser = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, phone)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO existingUser = findUserByAccount(phone);
|
||||
if (existingUser != null) {
|
||||
throw new RuntimeException("该手机号已注册");
|
||||
}
|
||||
@@ -1782,6 +1740,19 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
assertUserAvailable(userDO);
|
||||
|
||||
if (userDTO.getNickname() != null || userDTO.getSignature() != null
|
||||
|| (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty())) {
|
||||
Map<String, String> content = new java.util.LinkedHashMap<>();
|
||||
content.put("nickname", userDTO.getNickname());
|
||||
content.put("signature", userDTO.getSignature());
|
||||
content.put("avatar", userDTO.getAvatar() == null || userDTO.getAvatar().isEmpty()
|
||||
? null : normalizeStoredAvatar(userDTO.getAvatar()));
|
||||
String serialized = serializeModerationPayload(content);
|
||||
ContentModerationResultVO moderation = contentModerationService.assess("USER_PROFILE", userId, userId,
|
||||
String.join("\n", content.values().stream().filter(Objects::nonNull).toList()), serialized);
|
||||
requireApprovedContent(moderation);
|
||||
}
|
||||
|
||||
if (userDTO.getNickname() != null) {
|
||||
userDO.setNickname(userDTO.getNickname());
|
||||
}
|
||||
@@ -1990,10 +1961,15 @@ 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));
|
||||
wrapper.and(w -> {
|
||||
w.like(UserDO::getAccount, keyword).or().like(UserDO::getNickname, keyword);
|
||||
if (phoneCrypto.isMobilePhone(keyword.trim())) {
|
||||
String hash = phoneCrypto.index(keyword.trim());
|
||||
w.or().eq(UserDO::getAccountHash, hash)
|
||||
.or().eq(UserDO::getPhoneHash, hash)
|
||||
.or().eq(UserDO::getContactPhoneHash, hash);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (shopId != null && shopId > 0) {
|
||||
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
|
||||
@@ -2035,10 +2011,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
wrapper.le(UserDO::getCreateTime, LocalDateTime.parse(createdTo));
|
||||
}
|
||||
if (Boolean.TRUE.equals(hasPhone)) {
|
||||
wrapper.isNotNull(UserDO::getPhone);
|
||||
wrapper.and(w -> w.isNotNull(UserDO::getPhone).or().isNotNull(UserDO::getPhoneHash));
|
||||
}
|
||||
if (Boolean.FALSE.equals(hasPhone)) {
|
||||
wrapper.isNull(UserDO::getPhone);
|
||||
wrapper.isNull(UserDO::getPhone).isNull(UserDO::getPhoneHash);
|
||||
}
|
||||
wrapper.orderByDesc(UserDO::getCreateTime);
|
||||
|
||||
@@ -2254,11 +2230,30 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
assertUserAvailable(userDO);
|
||||
userDO.setAvatar(avatarUrl);
|
||||
String storedAvatar = normalizeStoredAvatar(avatarUrl);
|
||||
ContentModerationResultVO moderation = contentModerationService.assess("USER_AVATAR", userId, userId,
|
||||
avatarUrl, serializeModerationPayload(java.util.Map.of("avatar", storedAvatar)));
|
||||
requireApprovedContent(moderation);
|
||||
userDO.setAvatar(storedAvatar);
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
}
|
||||
|
||||
private String serializeModerationPayload(Object payload) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(payload);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new IllegalStateException("无法保存待复核内容", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireApprovedContent(ContentModerationResultVO result) {
|
||||
if (result == null || !"APPROVED".equals(result.getStatus())) {
|
||||
String reason = result == null ? null : result.getReason();
|
||||
throw new IllegalStateException(StringUtils.hasText(reason) ? reason : "内容正在审核中,暂未更新");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Update an existing record.
|
||||
@@ -2305,8 +2300,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();
|
||||
String newPhone = updatePhoneDTO.getNewPhone();
|
||||
String newPhone = validateUserPhone(updatePhoneDTO.getNewPhone(), userId, true);
|
||||
String verificationCode = updatePhoneDTO.getVerificationCode();
|
||||
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
@@ -2325,15 +2319,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`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -2342,14 +2327,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
* @return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
validateVerificationCode(newPhone, verificationCode);
|
||||
/**
|
||||
* 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.
|
||||
* @param newPhone parameter `newPhone` supplied by the caller
|
||||
* @param userId parameter `userId` supplied by the caller
|
||||
* @return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
ensurePhoneNotUsed(newPhone, userId);
|
||||
|
||||
userDO.setPhone(newPhone);
|
||||
userDO.setPhoneVerified(1);
|
||||
@@ -2357,6 +2334,37 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean unbindPhone(Long userId, String verificationCode) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
String phone = userDO.getPhone();
|
||||
if (!StringUtils.hasText(phone) || !Integer.valueOf(1).equals(userDO.getPhoneVerified())) {
|
||||
throw new RuntimeException("当前账号未绑定已验证手机号");
|
||||
}
|
||||
validateVerificationCode(phone, verificationCode);
|
||||
userDO.setPhone(null);
|
||||
userDO.setPhoneHash(null);
|
||||
userDO.setPhoneVerified(0);
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendUnbindPhoneCode(Long userId) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
if (!StringUtils.hasText(userDO.getPhone()) || !Integer.valueOf(1).equals(userDO.getPhoneVerified())) {
|
||||
throw new RuntimeException("当前账号未绑定已验证手机号");
|
||||
}
|
||||
if (!verificationCodeService.canResend(userDO.getPhone())) {
|
||||
throw new RuntimeException("验证码发送过于频繁,请稍后重试");
|
||||
}
|
||||
verificationCodeService.sendVerificationCode(userDO.getPhone(), "USER_UNBIND_PHONE");
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Run business method `resetPasswordByPhone`.
|
||||
@@ -2379,10 +2387,7 @@ 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::getIsDelete, 0);
|
||||
UserDO userDO = userMapper.selectOne(wrapper);
|
||||
UserDO userDO = findUserByPhone(phone);
|
||||
|
||||
if (userDO == null) {
|
||||
/**
|
||||
@@ -2917,7 +2922,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
|
||||
userInfo.setId(userDO.getId());
|
||||
userInfo.setAccount(userDO.getAccount());
|
||||
// 登录响应只用于展示账号标识,手机号账号不得以明文返回。
|
||||
userInfo.setAccount(phoneCrypto.mask(userDO.getAccount()));
|
||||
userInfo.setNickname(userDO.getNickname());
|
||||
userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar()));
|
||||
userInfo.setType(userDO.getType());
|
||||
@@ -3104,12 +3110,17 @@ 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);
|
||||
}
|
||||
if (userMapper.selectOne(wrapper) != null) {
|
||||
UserDO existing = userMapper.selectOne(wrapper);
|
||||
if (existing == null) {
|
||||
Long legacyId = userMapper.findLegacyIdByPhone(phone);
|
||||
existing = legacyId == null || Objects.equals(legacyId, currentUserId) ? null : userMapper.selectById(legacyId);
|
||||
}
|
||||
if (existing != null) {
|
||||
/**
|
||||
* 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.
|
||||
@@ -3128,13 +3139,52 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.eq(UserDO::getType, 0)
|
||||
.eq(UserDO::getIsDelete, 0);
|
||||
if (StringUtils.hasText(phone)) {
|
||||
wrapper.and(query -> query.eq(UserDO::getPhone, phone)
|
||||
.or().eq(UserDO::getContactPhone, phone));
|
||||
addPhoneMatch(wrapper, phone);
|
||||
}
|
||||
if (userMapper.selectCount(wrapper) > 0) {
|
||||
throw new RuntimeException("客户已存在,请选择已有客户");
|
||||
}
|
||||
}
|
||||
|
||||
private void addPhoneMatch(LambdaQueryWrapper<UserDO> wrapper, String phone) {
|
||||
String hash = phoneCrypto.index(phone.trim());
|
||||
List<Long> legacyIds = new ArrayList<>();
|
||||
Long legacyPhoneId = userMapper.findLegacyIdByPhone(phone.trim());
|
||||
if (legacyPhoneId != null) legacyIds.add(legacyPhoneId);
|
||||
for (Long legacyContactId : userMapper.findLegacyIdsByContactPhone(phone.trim())) {
|
||||
if (!legacyIds.contains(legacyContactId)) legacyIds.add(legacyContactId);
|
||||
}
|
||||
wrapper.and(query -> {
|
||||
query.eq(UserDO::getPhoneHash, hash).or().eq(UserDO::getContactPhoneHash, hash);
|
||||
if (!legacyIds.isEmpty()) query.or().in(UserDO::getId, legacyIds);
|
||||
});
|
||||
}
|
||||
|
||||
private UserDO findUserByAccount(String account) {
|
||||
if (!StringUtils.hasText(account)) return null;
|
||||
LambdaQueryWrapper<UserDO> query = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getIsDelete, 0);
|
||||
query.eq(UserDO::getAccountHash, phoneCrypto.index(account.trim()));
|
||||
UserDO user = userMapper.selectOne(query.last("limit 1"));
|
||||
if (user == null) {
|
||||
Long legacyId = userMapper.findLegacyIdByAccount(account.trim());
|
||||
user = legacyId == null ? null : userMapper.selectById(legacyId);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
private UserDO findUserByPhone(String phone) {
|
||||
if (!StringUtils.hasText(phone)) return null;
|
||||
String normalized = phone.trim();
|
||||
UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhoneHash, phoneCrypto.index(normalized))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1"));
|
||||
if (user == null) {
|
||||
Long legacyId = userMapper.findLegacyIdByPhone(normalized);
|
||||
user = legacyId == null ? null : userMapper.selectById(legacyId);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
/**
|
||||
* Run business method `buildRelationVO`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.xiaowang.jayucloud.salon.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;
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.xiaowang.jayucloud.salon.core.support.privacy;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class PhoneBackfillReport {
|
||||
private boolean dryRun;
|
||||
private int userRowsToUpdate;
|
||||
private int userRowsUpdated;
|
||||
private int orderRowsToUpdate;
|
||||
private int orderRowsUpdated;
|
||||
private int accountConflictRows;
|
||||
private int phoneConflictRows;
|
||||
private List<Long> conflictingUserIds;
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.xiaowang.jayucloud.salon.core.support.privacy;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.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.Base64;
|
||||
|
||||
@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 (java.util.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 encryptAccount(String value) {
|
||||
return isMobilePhone(value) ? encrypt(value) : value;
|
||||
}
|
||||
|
||||
public String decryptAccount(String value) {
|
||||
return value != null && value.startsWith(CIPHER_PREFIX) ? decrypt(value) : value;
|
||||
}
|
||||
|
||||
public boolean isMobilePhone(String value) {
|
||||
return value != null && value.trim().matches("1[3-9]\\d{9}");
|
||||
}
|
||||
|
||||
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 = java.util.Arrays.copyOfRange(payload, 0, 12);
|
||||
byte[] encrypted = java.util.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);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEncrypted(String value) {
|
||||
return value != null && value.startsWith(CIPHER_PREFIX);
|
||||
}
|
||||
|
||||
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 java.util.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-salon.privacy." + name);
|
||||
try {
|
||||
return Base64.getDecoder().decode(value.trim());
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IllegalStateException("Nacos配置必须使用Base64编码: " + name, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package com.xiaowang.jayucloud.salon.core.support.privacy;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.xiaowang.jayucloud.salon.core.config.PhoneCryptoProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PhoneDataBackfillService {
|
||||
private final UserMapper userMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
private final PhoneCryptoProperties properties;
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public PhoneBackfillReport backfill(boolean dryRun) {
|
||||
if (!dryRun && !properties.isBackfillEnabled()) {
|
||||
throw new IllegalStateException("请先在 Salon Nacos secret.yaml 启用 phone-crypto.backfill-enabled");
|
||||
}
|
||||
|
||||
List<UserDO> users = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class));
|
||||
Map<String, List<Long>> accountGroups = groupValues(users, UserDO::getAccount);
|
||||
Map<String, List<Long>> phoneGroups = groupValues(users, UserDO::getPhone);
|
||||
Set<Long> accountConflicts = duplicateIds(accountGroups);
|
||||
Set<Long> phoneConflicts = duplicateIds(phoneGroups);
|
||||
Set<Long> conflictingIds = new HashSet<>(accountConflicts);
|
||||
conflictingIds.addAll(phoneConflicts);
|
||||
|
||||
List<UserDO> usersToUpdate = users.stream()
|
||||
.filter(user -> !conflictingIds.contains(user.getId()))
|
||||
.filter(this::hasPendingUserFields)
|
||||
.toList();
|
||||
List<OrderDO> ordersToUpdate = orderMapper.selectList(Wrappers.lambdaQuery(OrderDO.class)
|
||||
.isNotNull(OrderDO::getCustomerPhoneSnapshot)
|
||||
.isNull(OrderDO::getCustomerPhoneSnapshotHash))
|
||||
.stream()
|
||||
.filter(order -> StringUtils.hasText(order.getCustomerPhoneSnapshot()))
|
||||
.toList();
|
||||
|
||||
PhoneBackfillReport report = new PhoneBackfillReport();
|
||||
report.setDryRun(dryRun);
|
||||
report.setUserRowsToUpdate(usersToUpdate.size());
|
||||
report.setOrderRowsToUpdate(ordersToUpdate.size());
|
||||
report.setAccountConflictRows(accountConflicts.size());
|
||||
report.setPhoneConflictRows(phoneConflicts.size());
|
||||
report.setConflictingUserIds(conflictingIds.stream().sorted().toList());
|
||||
if (dryRun) return report;
|
||||
if (!conflictingIds.isEmpty()) {
|
||||
throw new IllegalStateException("检测到手机号或登录账号重复,已停止全部回填;请先处理冲突用户 ID:"
|
||||
+ report.getConflictingUserIds());
|
||||
}
|
||||
|
||||
int pageSize = Math.max(1, Math.min(properties.getBackfillPageSize(), 2000));
|
||||
for (int start = 0; start < usersToUpdate.size(); start += pageSize) {
|
||||
int end = Math.min(start + pageSize, usersToUpdate.size());
|
||||
List<UserDO> batch = usersToUpdate.subList(start, end);
|
||||
for (UserDO user : batch) {
|
||||
userMapper.updateById(user);
|
||||
report.setUserRowsUpdated(report.getUserRowsUpdated() + 1);
|
||||
}
|
||||
}
|
||||
for (int start = 0; start < ordersToUpdate.size(); start += pageSize) {
|
||||
int end = Math.min(start + pageSize, ordersToUpdate.size());
|
||||
List<OrderDO> batch = ordersToUpdate.subList(start, end);
|
||||
for (OrderDO order : batch) {
|
||||
orderMapper.updateById(order);
|
||||
report.setOrderRowsUpdated(report.getOrderRowsUpdated() + 1);
|
||||
}
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
private Map<String, List<Long>> groupValues(List<UserDO> users, Function<UserDO, String> valueGetter) {
|
||||
Map<String, List<Long>> groups = new HashMap<>();
|
||||
for (UserDO user : users) {
|
||||
String value = valueGetter.apply(user);
|
||||
if (StringUtils.hasText(value)) {
|
||||
groups.computeIfAbsent(phoneCrypto.index(value), ignored -> new ArrayList<>()).add(user.getId());
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
private Set<Long> duplicateIds(Map<String, List<Long>> groups) {
|
||||
return groups.values().stream()
|
||||
.filter(ids -> ids.size() > 1)
|
||||
.flatMap(List::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private boolean hasPendingUserFields(UserDO user) {
|
||||
return (StringUtils.hasText(user.getAccount()) && !StringUtils.hasText(user.getAccountHash()))
|
||||
|| (StringUtils.hasText(user.getPhone()) && !StringUtils.hasText(user.getPhoneHash()))
|
||||
|| (StringUtils.hasText(user.getContactPhone()) && !StringUtils.hasText(user.getContactPhoneHash()));
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.xiaowang.jayucloud.salon.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;
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.xiaowang.jayucloud.salon.core.support.privacy;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SensitivePhoneMetaObjectHandler implements MetaObjectHandler {
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
fillIndexes(metaObject);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
fillIndexes(metaObject);
|
||||
}
|
||||
|
||||
private void fillIndexes(MetaObject metaObject) {
|
||||
setAccountIndex(metaObject);
|
||||
setIndex(metaObject, "phone", "phoneHash");
|
||||
setIndex(metaObject, "contactPhone", "contactPhoneHash");
|
||||
setIndex(metaObject, "customerPhoneSnapshot", "customerPhoneSnapshotHash");
|
||||
}
|
||||
|
||||
private void setAccountIndex(MetaObject metaObject) {
|
||||
if (!metaObject.hasGetter("account") || !metaObject.hasSetter("accountHash")) return;
|
||||
Object value = metaObject.getValue("account");
|
||||
String account = value == null ? null : String.valueOf(value);
|
||||
metaObject.setValue("accountHash", account == null ? null : PhoneCrypto.current().index(account));
|
||||
}
|
||||
|
||||
private void setIndex(MetaObject metaObject, String source, String target) {
|
||||
if (!metaObject.hasGetter(source) || !metaObject.hasSetter(target)) return;
|
||||
Object value = metaObject.getValue(source);
|
||||
String hash = value == null ? null : PhoneCrypto.current().index(String.valueOf(value));
|
||||
metaObject.setValue(target, hash);
|
||||
}
|
||||
}
|
||||
+1
-9
@@ -129,8 +129,7 @@ public class OperationGuardService {
|
||||
"public",
|
||||
safeAction,
|
||||
subject,
|
||||
sanitize(resolveClientIp(request)),
|
||||
sanitize(resolveDeviceId(request))
|
||||
sanitize(resolveClientIp(request))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -304,13 +303,6 @@ public class OperationGuardService {
|
||||
* Purpose: resolveDeviceId supports OperationGuardService.java by holding or executing the resolve device id business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String resolveDeviceId(HttpServletRequest request) {
|
||||
if (request == null) {
|
||||
return "-";
|
||||
}
|
||||
return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: sanitize supports OperationGuardService.java by holding or executing the sanitize business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
|
||||
+1
-7
@@ -24,7 +24,6 @@ public class RequestThrottleService {
|
||||
* Purpose: DEVICE_ID_HEADER supports RequestThrottleService.java by holding or executing the device id header business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static final String DEVICE_ID_HEADER = "X-Device-Id";
|
||||
|
||||
/**
|
||||
* Purpose: stringRedisTemplate supports RequestThrottleService.java by holding or executing the string redis template business role.
|
||||
@@ -145,7 +144,6 @@ public class RequestThrottleService {
|
||||
String raw = String.join("|",
|
||||
category,
|
||||
sanitize(resolveClientIp(request)),
|
||||
sanitize(resolveDeviceId(request)),
|
||||
sanitize(subject)
|
||||
);
|
||||
String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8));
|
||||
@@ -190,7 +188,7 @@ public class RequestThrottleService {
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String buildLoginLockRaw(HttpServletRequest request, String account) {
|
||||
return String.join("|", sanitize(resolveClientIp(request)), sanitize(resolveDeviceId(request)), sanitize(account));
|
||||
return String.join("|", sanitize(resolveClientIp(request)), sanitize(account));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -216,10 +214,6 @@ public class RequestThrottleService {
|
||||
* Purpose: resolveDeviceId supports RequestThrottleService.java by holding or executing the resolve device id business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String resolveDeviceId(HttpServletRequest request) {
|
||||
return request == null ? null : request.getHeader(DEVICE_ID_HEADER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: sanitize supports RequestThrottleService.java by holding or executing the sanitize business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.user.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ChunkUploadService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService;
|
||||
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.modules.system.service.LegalAgreementService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class UserControllerPhonePrivacyTest {
|
||||
|
||||
@Test
|
||||
void sendsPasswordCodeToVerifiedPhoneFromCurrentAccount() {
|
||||
UserService userService = mock(UserService.class);
|
||||
UserAssetService userAssetService = mock(UserAssetService.class);
|
||||
PrimaryObjectStorageService primaryObjectStorageService = mock(PrimaryObjectStorageService.class);
|
||||
ChunkUploadService chunkUploadService = mock(ChunkUploadService.class);
|
||||
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
|
||||
UserMapper userMapper = mock(UserMapper.class);
|
||||
AdminScopeHelper adminScopeHelper = mock(AdminScopeHelper.class);
|
||||
ShopRoleService shopRoleService = mock(ShopRoleService.class);
|
||||
TimeOrderedSnowflakeIdGenerator idGenerator = mock(TimeOrderedSnowflakeIdGenerator.class);
|
||||
WechatMiniAuthService wechatMiniAuthService = mock(WechatMiniAuthService.class);
|
||||
ObjectStorageUrlSupport objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class);
|
||||
RequestThrottleService requestThrottleService = mock(RequestThrottleService.class);
|
||||
LegalAgreementService legalAgreementService = mock(LegalAgreementService.class);
|
||||
AccountClosureService accountClosureService = mock(AccountClosureService.class);
|
||||
SecurityAuditLogService securityAuditLogService = mock(SecurityAuditLogService.class);
|
||||
UserController controller = new UserController(userService, userAssetService, primaryObjectStorageService,
|
||||
chunkUploadService, verificationCodeService, userMapper, adminScopeHelper, shopRoleService,
|
||||
idGenerator, wechatMiniAuthService, objectStorageUrlSupport, requestThrottleService,
|
||||
legalAgreementService, accountClosureService, securityAuditLogService);
|
||||
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(request.getAttribute("userId")).thenReturn(27L);
|
||||
UserDO user = new UserDO();
|
||||
user.setId(27L);
|
||||
user.setPhone("13812345678");
|
||||
user.setPhoneVerified(1);
|
||||
user.setStatus(1);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(27L)).thenReturn(user);
|
||||
when(verificationCodeService.canResend(user.getPhone())).thenReturn(true);
|
||||
|
||||
Result<Boolean> result = controller.sendCurrentPasswordVerificationCode(request);
|
||||
|
||||
assertEquals(true, result.getData());
|
||||
verify(requestThrottleService).checkSendCode(request, user.getPhone());
|
||||
verify(verificationCodeService).sendVerificationCode(user.getPhone(), "USER_CHANGE_PASSWORD_SMS_CODE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsPasswordCodeRequestWithoutAuthenticatedUser() {
|
||||
UserController controller = new UserController(mock(UserService.class), mock(UserAssetService.class),
|
||||
mock(PrimaryObjectStorageService.class), mock(ChunkUploadService.class),
|
||||
mock(VerificationCodeService.class), mock(UserMapper.class), mock(AdminScopeHelper.class),
|
||||
mock(ShopRoleService.class), mock(TimeOrderedSnowflakeIdGenerator.class),
|
||||
mock(WechatMiniAuthService.class), mock(ObjectStorageUrlSupport.class),
|
||||
mock(RequestThrottleService.class), mock(LegalAgreementService.class),
|
||||
mock(AccountClosureService.class), mock(SecurityAuditLogService.class));
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> controller.sendCurrentPasswordVerificationCode(request));
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.user.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.UpdatePhoneRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class UserServicePhoneUpdateTest {
|
||||
|
||||
@Mock private UserMapper userMapper;
|
||||
@Mock private PhoneCrypto phoneCrypto;
|
||||
@Mock private VerificationCodeService verificationCodeService;
|
||||
@InjectMocks private UserServiceImpl userService;
|
||||
|
||||
@Test
|
||||
void updatesPhoneWithoutTrustingMaskedOldPhoneFromClient() {
|
||||
UserDO currentUser = new UserDO();
|
||||
currentUser.setId(27L);
|
||||
currentUser.setPhone("13812345678");
|
||||
currentUser.setPhoneVerified(1);
|
||||
currentUser.setStatus(1);
|
||||
currentUser.setIsDelete(0);
|
||||
when(userMapper.selectById(27L)).thenReturn(currentUser);
|
||||
when(phoneCrypto.index("13912345678")).thenReturn("new-phone-hash");
|
||||
when(userMapper.selectOne(any(Wrapper.class))).thenReturn(null);
|
||||
when(userMapper.findLegacyIdByPhone("13912345678")).thenReturn(null);
|
||||
when(verificationCodeService.verifyCode("13912345678", "123456")).thenReturn(true);
|
||||
when(userMapper.updateById(currentUser)).thenReturn(1);
|
||||
|
||||
UpdatePhoneRequestDTO request = new UpdatePhoneRequestDTO();
|
||||
request.setOldPhone("138****5678");
|
||||
request.setNewPhone("13912345678");
|
||||
request.setVerificationCode("123456");
|
||||
|
||||
assertTrue(userService.updatePhone(27L, request));
|
||||
verify(userMapper).updateById(currentUser);
|
||||
assertTrue("13912345678".equals(currentUser.getPhone()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user