feat: overnight-runner 入 SDD、dev-build 全栈编排,并落地 ACC-account

将 overnight-runner skill 无前缀并入套件;dev-build 编排自测/UI/代码评审;指南左侧导航;example 实现账号能力与 progress。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ning-inspire
2026-11-17 16:56:57 +08:00
parent 972a031654
commit fc7521d6f9
154 changed files with 6688 additions and 498 deletions

View File

@@ -0,0 +1,35 @@
package com.consultation.adapter.rest;
import com.consultation.adapter.rest.dto.AccountResponse;
import com.consultation.adapter.rest.dto.DisableAccountRequest;
import com.consultation.application.service.AdminAccountAppService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
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;
/**
* 管理端账号操作(需 ROLE_ADMIN)。
*/
@RestController
@RequestMapping("/api/v1/admin/accounts")
@RequiredArgsConstructor
public class AdminAccountController {
private final AdminAccountAppService adminAccountAppService;
@PostMapping("/{id}/disable")
public ResponseEntity<AccountResponse> disable(@PathVariable String id,
@Valid @RequestBody DisableAccountRequest request) {
return ResponseEntity.ok(adminAccountAppService.disable(id, request.getReason()));
}
@PostMapping("/{id}/enable")
public ResponseEntity<AccountResponse> enable(@PathVariable String id) {
return ResponseEntity.ok(adminAccountAppService.enable(id));
}
}

View File

@@ -0,0 +1,42 @@
package com.consultation.adapter.rest;
import com.consultation.adapter.rest.dto.AdminLoginRequest;
import com.consultation.adapter.rest.dto.AuthLoginResponse;
import com.consultation.adapter.rest.dto.SendSmsCodeRequest;
import com.consultation.adapter.rest.dto.SmsLoginRequest;
import com.consultation.application.service.AuthAppService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
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;
/**
* 鉴权入口:验证码发送 / 验证码登录注册 / 管理员登录。
*/
@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthAppService authAppService;
@PostMapping("/sms/send")
public ResponseEntity<Void> sendSmsCode(@Valid @RequestBody SendSmsCodeRequest request) {
authAppService.sendSmsCode(request.getPhone());
return ResponseEntity.noContent().build();
}
@PostMapping("/sms/login")
public ResponseEntity<AuthLoginResponse> smsLogin(@Valid @RequestBody SmsLoginRequest request) {
return ResponseEntity.ok(authAppService.loginOrRegister(
request.getPhone(), request.getCode(), request.getNickname()));
}
@PostMapping("/admin/login")
public ResponseEntity<AuthLoginResponse> adminLogin(@Valid @RequestBody AdminLoginRequest request) {
return ResponseEntity.ok(authAppService.adminLogin(request.getPhone(), request.getPassword()));
}
}

View File

@@ -0,0 +1,95 @@
package com.consultation.adapter.rest;
import com.consultation.adapter.rest.dto.AddFavoriteRequest;
import com.consultation.adapter.rest.dto.AgreementConsentRequest;
import com.consultation.adapter.rest.dto.AgreementConsentResponse;
import com.consultation.adapter.rest.dto.FavoriteResponse;
import com.consultation.adapter.rest.dto.MeResponse;
import com.consultation.adapter.rest.dto.ProfileResponse;
import com.consultation.adapter.rest.dto.UpdateProfileRequest;
import com.consultation.application.service.AgreementAppService;
import com.consultation.application.service.FavoriteAppService;
import com.consultation.application.service.ProfileAppService;
import com.consultation.infrastructure.security.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 「我的」相关接口:资料、收藏、协议同意。
*/
@RestController
@RequestMapping("/api/v1/me")
@RequiredArgsConstructor
public class MeController {
private final ProfileAppService profileAppService;
private final FavoriteAppService favoriteAppService;
private final AgreementAppService agreementAppService;
@GetMapping
public ResponseEntity<MeResponse> me() {
return ResponseEntity.ok(profileAppService.getMe(SecurityUtils.currentUserId()));
}
@PutMapping("/profile")
public ResponseEntity<ProfileResponse> updateProfile(@Valid @RequestBody UpdateProfileRequest request) {
return ResponseEntity.ok(profileAppService.updateProfile(
SecurityUtils.currentUserId(),
request.getNickname(),
request.getAvatarUrl(),
request.getEmail(),
request.getCityCode(),
request.getLocale()));
}
@GetMapping("/favorites")
public ResponseEntity<List<FavoriteResponse>> listFavorites() {
return ResponseEntity.ok(favoriteAppService.list(SecurityUtils.currentUserId()));
}
@PostMapping("/favorites")
public ResponseEntity<FavoriteResponse> addFavorite(@Valid @RequestBody AddFavoriteRequest request) {
return ResponseEntity.ok(favoriteAppService.add(SecurityUtils.currentUserId(), request.getConsultantId()));
}
@DeleteMapping("/favorites/{consultantId}")
public ResponseEntity<Void> removeFavorite(@PathVariable String consultantId) {
favoriteAppService.remove(SecurityUtils.currentUserId(), consultantId);
return ResponseEntity.noContent().build();
}
@GetMapping("/agreements")
public ResponseEntity<List<AgreementConsentResponse>> listAgreements() {
return ResponseEntity.ok(agreementAppService.list(SecurityUtils.currentUserId()));
}
@PostMapping("/agreements")
public ResponseEntity<AgreementConsentResponse> consent(@Valid @RequestBody AgreementConsentRequest request,
HttpServletRequest httpRequest) {
return ResponseEntity.ok(agreementAppService.consent(
SecurityUtils.currentUserId(),
request.getAgreementType(),
request.getAgreementVersion(),
resolveSourceIp(httpRequest)));
}
private String resolveSourceIp(HttpServletRequest request) {
String forwarded = request.getHeader("X-Forwarded-For");
if (forwarded != null && !forwarded.isBlank()) {
return forwarded.split(",")[0].trim();
}
return request.getRemoteAddr();
}
}

View File

@@ -0,0 +1,25 @@
package com.consultation.adapter.rest.dto;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
import java.util.List;
/**
* 账号对外视图。手机号仅本人查看时明文,其余场景脱敏(R-QUERY-002)。
*/
@Data
@Builder
public class AccountResponse {
private String id;
private List<String> roles;
private String status;
private String phone;
private Instant phoneVerifiedAt;
private Instant lastLoginAt;
private String disabledReason;
private Instant createdAt;
private Instant updatedAt;
}

View File

@@ -0,0 +1,11 @@
package com.consultation.adapter.rest.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class AddFavoriteRequest {
@NotBlank(message = "咨询师ID不能为空")
private String consultantId;
}

View File

@@ -0,0 +1,14 @@
package com.consultation.adapter.rest.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class AdminLoginRequest {
@NotBlank(message = "手机号不能为空")
private String phone;
@NotBlank(message = "密码不能为空")
private String password;
}

View File

@@ -0,0 +1,17 @@
package com.consultation.adapter.rest.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class AgreementConsentRequest {
/** service / privacy */
@NotBlank(message = "协议类型不能为空")
private String agreementType;
@NotBlank(message = "协议版本不能为空")
@Size(max = 20, message = "协议版本长度不能超过 20 个字符")
private String agreementVersion;
}

View File

@@ -0,0 +1,18 @@
package com.consultation.adapter.rest.dto;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
@Data
@Builder
public class AgreementConsentResponse {
private String id;
/** service / privacy */
private String agreementType;
private String agreementVersion;
private Instant consentedAt;
private String sourceIp;
}

View File

@@ -0,0 +1,13 @@
package com.consultation.adapter.rest.dto;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class AuthLoginResponse {
private String token;
private AccountResponse account;
private ProfileResponse profile;
}

View File

@@ -0,0 +1,13 @@
package com.consultation.adapter.rest.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class DisableAccountRequest {
@NotBlank(message = "禁用原因不能为空")
@Size(max = 200, message = "禁用原因长度不能超过 200 个字符")
private String reason;
}

View File

@@ -0,0 +1,15 @@
package com.consultation.adapter.rest.dto;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
@Data
@Builder
public class FavoriteResponse {
private String id;
private String consultantId;
private Instant createdAt;
}

View File

@@ -0,0 +1,12 @@
package com.consultation.adapter.rest.dto;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class MeResponse {
private AccountResponse account;
private ProfileResponse profile;
}

View File

@@ -0,0 +1,19 @@
package com.consultation.adapter.rest.dto;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
@Data
@Builder
public class ProfileResponse {
private String accountId;
private String nickname;
private String avatarUrl;
private String email;
private String cityCode;
private String locale;
private Instant updatedAt;
}

View File

@@ -0,0 +1,11 @@
package com.consultation.adapter.rest.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class SendSmsCodeRequest {
@NotBlank(message = "手机号不能为空")
private String phone;
}

View File

@@ -0,0 +1,17 @@
package com.consultation.adapter.rest.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class SmsLoginRequest {
@NotBlank(message = "手机号不能为空")
private String phone;
@NotBlank(message = "验证码不能为空")
private String code;
/** 新号注册时的昵称,缺省由系统生成。 */
private String nickname;
}

View File

@@ -0,0 +1,23 @@
package com.consultation.adapter.rest.dto;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class UpdateProfileRequest {
@Size(min = 2, max = 30, message = "昵称长度需为 2-30 个字符")
private String nickname;
@Size(max = 500, message = "头像地址长度不能超过 500 个字符")
private String avatarUrl;
@Size(max = 254, message = "邮箱长度不能超过 254 个字符")
private String email;
@Size(max = 20, message = "城市编码长度不能超过 20 个字符")
private String cityCode;
@Size(max = 16, message = "语言标识长度不能超过 16 个字符")
private String locale;
}

View File

@@ -0,0 +1,72 @@
package com.consultation.application.assembler;
import com.consultation.adapter.rest.dto.AccountResponse;
import com.consultation.domain.aggregate.Account;
import com.consultation.domain.service.PhoneCrypto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.Comparator;
import java.util.List;
@Component
@RequiredArgsConstructor
public class AccountAssembler {
private final PhoneCrypto phoneCrypto;
/**
* 本人视角:手机号明文。
*/
public AccountResponse toSelfResponse(Account account) {
return toResponse(account, true);
}
/**
* 非本人视角:手机号脱敏(R-QUERY-002)。
*/
public AccountResponse toMaskedResponse(Account account) {
return toResponse(account, false);
}
private AccountResponse toResponse(Account account, boolean revealPhone) {
if (account == null) {
return null;
}
return AccountResponse.builder()
.id(account.getId())
.roles(account.getRoles() == null ? List.of()
: account.getRoles().stream()
.map(Enum::name)
.sorted(Comparator.naturalOrder())
.toList())
.status(account.getStatus() == null ? null : account.getStatus().name())
.phone(resolvePhone(account, revealPhone))
.phoneVerifiedAt(account.getPhoneVerifiedAt())
.lastLoginAt(account.getLastLoginAt())
.disabledReason(account.getDisabledReason())
.createdAt(account.getCreatedAt())
.updatedAt(account.getUpdatedAt())
.build();
}
private String resolvePhone(Account account, boolean revealPhone) {
if (account.getPhoneCipher() == null || account.getPhoneCipher().isBlank()) {
return null;
}
String phone;
try {
phone = phoneCrypto.decrypt(account.getPhoneCipher());
} catch (RuntimeException e) {
return null;
}
return revealPhone ? phone : maskPhone(phone);
}
static String maskPhone(String phone) {
if (phone == null || phone.length() < 7) {
return "***";
}
return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
}
}

View File

@@ -0,0 +1,22 @@
package com.consultation.application.assembler;
import com.consultation.adapter.rest.dto.AgreementConsentResponse;
import com.consultation.domain.aggregate.AgreementConsent;
import org.springframework.stereotype.Component;
@Component
public class AgreementAssembler {
public AgreementConsentResponse toResponse(AgreementConsent consent) {
if (consent == null) {
return null;
}
return AgreementConsentResponse.builder()
.id(consent.getId())
.agreementType(consent.getAgreementType().getCode())
.agreementVersion(consent.getAgreementVersion())
.consentedAt(consent.getConsentedAt())
.sourceIp(consent.getSourceIp())
.build();
}
}

View File

@@ -0,0 +1,20 @@
package com.consultation.application.assembler;
import com.consultation.adapter.rest.dto.FavoriteResponse;
import com.consultation.domain.aggregate.FavoriteConsultant;
import org.springframework.stereotype.Component;
@Component
public class FavoriteAssembler {
public FavoriteResponse toResponse(FavoriteConsultant favorite) {
if (favorite == null) {
return null;
}
return FavoriteResponse.builder()
.id(favorite.getId())
.consultantId(favorite.getConsultantId())
.createdAt(favorite.getCreatedAt())
.build();
}
}

View File

@@ -0,0 +1,24 @@
package com.consultation.application.assembler;
import com.consultation.adapter.rest.dto.ProfileResponse;
import com.consultation.domain.aggregate.UserProfile;
import org.springframework.stereotype.Component;
@Component
public class ProfileAssembler {
public ProfileResponse toResponse(UserProfile profile) {
if (profile == null) {
return null;
}
return ProfileResponse.builder()
.accountId(profile.getAccountId())
.nickname(profile.getNickname())
.avatarUrl(profile.getAvatarUrl())
.email(profile.getEmail())
.cityCode(profile.getCityCode())
.locale(profile.getLocale())
.updatedAt(profile.getUpdatedAt())
.build();
}
}

View File

@@ -0,0 +1,60 @@
package com.consultation.application.service;
import com.consultation.adapter.rest.dto.AccountResponse;
import com.consultation.application.assembler.AccountAssembler;
import com.consultation.domain.aggregate.Account;
import com.consultation.domain.repository.AccountRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
/**
* 管理端账号操作(R-UPDATE-003:禁用必须填原因并使现有会话失效)。
*/
@Service
@RequiredArgsConstructor
public class AdminAccountAppService {
private final AccountRepository accountRepository;
private final AccountAssembler accountAssembler;
/**
* 禁用账号:抬升 tokenVersion,既有 JWT 立即失效。重复禁用幂等。
*/
@Transactional
public AccountResponse disable(String accountId, String reason) {
if (reason == null || reason.isBlank()) {
throw new IllegalArgumentException("禁用原因不能为空");
}
String trimmed = reason.trim();
if (trimmed.length() > 200) {
throw new IllegalArgumentException("禁用原因长度不能超过 200 个字符");
}
Account account = requireAccount(accountId);
Account disabled = account.disable(trimmed, Instant.now());
if (disabled != account) {
accountRepository.save(disabled);
}
return accountAssembler.toMaskedResponse(disabled);
}
/**
* 启用账号:同样抬升 tokenVersion,旧令牌不再可用。重复启用幂等。
*/
@Transactional
public AccountResponse enable(String accountId) {
Account account = requireAccount(accountId);
Account enabled = account.enable(Instant.now());
if (enabled != account) {
accountRepository.save(enabled);
}
return accountAssembler.toMaskedResponse(enabled);
}
private Account requireAccount(String accountId) {
return accountRepository.findById(accountId)
.orElseThrow(() -> new IllegalArgumentException("账号不存在"));
}
}

View File

@@ -0,0 +1,57 @@
package com.consultation.application.service;
import com.consultation.adapter.rest.dto.AgreementConsentResponse;
import com.consultation.application.assembler.AgreementAssembler;
import com.consultation.domain.aggregate.AgreementConsent;
import com.consultation.domain.repository.AgreementConsentRepository;
import com.consultation.domain.vo.AgreementType;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
/**
* 协议同意用例(R-CREATE-003:按类型 + 版本幂等,记录时间与来源 IP)。
*/
@Service
@RequiredArgsConstructor
public class AgreementAppService {
private final AgreementConsentRepository consentRepository;
private final AgreementAssembler agreementAssembler;
public List<AgreementConsentResponse> list(String accountId) {
return consentRepository.findByAccountId(accountId).stream()
.map(agreementAssembler::toResponse)
.toList();
}
@Transactional
public AgreementConsentResponse consent(String accountId, String agreementType, String agreementVersion,
String sourceIp) {
AgreementType type = AgreementType.fromCode(agreementType);
if (agreementVersion == null || agreementVersion.isBlank()) {
throw new IllegalArgumentException("协议版本不能为空");
}
String version = agreementVersion.trim();
if (version.length() > 20) {
throw new IllegalArgumentException("协议版本长度不能超过 20 个字符");
}
return consentRepository.findByAccountIdAndTypeAndVersion(accountId, type, version)
.map(agreementAssembler::toResponse)
.orElseGet(() -> {
AgreementConsent created = AgreementConsent.builder()
.id(UUID.randomUUID().toString())
.accountId(accountId)
.agreementType(type)
.agreementVersion(version)
.consentedAt(Instant.now())
.sourceIp(sourceIp == null || sourceIp.isBlank() ? "unknown" : sourceIp)
.build();
return agreementAssembler.toResponse(consentRepository.save(created));
});
}
}

View File

@@ -0,0 +1,131 @@
package com.consultation.application.service;
import com.consultation.adapter.rest.dto.AccountResponse;
import com.consultation.adapter.rest.dto.AuthLoginResponse;
import com.consultation.adapter.rest.dto.ProfileResponse;
import com.consultation.application.assembler.AccountAssembler;
import com.consultation.application.assembler.ProfileAssembler;
import com.consultation.domain.aggregate.Account;
import com.consultation.domain.aggregate.UserProfile;
import com.consultation.domain.repository.AccountRepository;
import com.consultation.domain.repository.UserProfileRepository;
import com.consultation.domain.service.PasswordService;
import com.consultation.domain.service.PhoneCrypto;
import com.consultation.domain.service.SmsCodeService;
import com.consultation.domain.service.TokenIssuer;
import com.consultation.domain.vo.AccountRole;
import com.consultation.domain.vo.PhoneNumber;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
/**
* 登录 / 注册用例编排。
*
* <p>手机号验证码登录与注册合一:已有手机号不重复建号(R-CREATE-001)。</p>
*/
@Service
@RequiredArgsConstructor
public class AuthAppService {
private static final SecureRandom RANDOM = new SecureRandom();
private final AccountRepository accountRepository;
private final UserProfileRepository userProfileRepository;
private final SmsCodeService smsCodeService;
private final PhoneCrypto phoneCrypto;
private final PasswordService passwordService;
private final TokenIssuer tokenIssuer;
private final AccountAssembler accountAssembler;
private final ProfileAssembler profileAssembler;
/**
* 发送登录 / 注册验证码。不区分手机号是否存在,防枚举。
*/
public void sendSmsCode(String phone) {
PhoneNumber phoneNumber = PhoneNumber.of(phone);
smsCodeService.issue(phoneNumber.value(), phoneCrypto.hash(phoneNumber.value()));
}
/**
* 验证码登录或注册(默认 USER 角色)。
*/
@Transactional
public AuthLoginResponse loginOrRegister(String phone, String code, String nickname) {
PhoneNumber phoneNumber = PhoneNumber.of(phone);
String phoneHash = phoneCrypto.hash(phoneNumber.value());
smsCodeService.verify(phoneHash, code);
Instant now = Instant.now();
Optional<Account> existing = accountRepository.findByPhoneHash(phoneHash);
Account account;
ProfileResponse profile;
if (existing.isPresent()) {
account = existing.get();
account.assertUsable();
account = account.touchLogin(now);
accountRepository.save(account);
profile = profileAssembler.toResponse(
userProfileRepository.findByAccountId(account.getId()).orElse(null));
} else {
account = Account.registerByPhone(
UUID.randomUUID().toString(), phoneHash, phoneCrypto.encrypt(phoneNumber.value()), now);
accountRepository.save(account);
UserProfile created = UserProfile.create(
account.getId(), resolveNickname(nickname), UserProfile.DEFAULT_LOCALE, now);
userProfileRepository.save(created);
profile = profileAssembler.toResponse(created);
}
return buildLoginResponse(account, profile);
}
/**
* 管理员密码登录(独立鉴权,R-COMMON-001:不开放自助注册 ADMIN)。
*/
@Transactional
public AuthLoginResponse adminLogin(String phone, String password) {
PhoneNumber phoneNumber = PhoneNumber.of(phone);
String phoneHash = phoneCrypto.hash(phoneNumber.value());
Account account = accountRepository.findByPhoneHash(phoneHash)
.orElseThrow(() -> new IllegalArgumentException("账号或密码不正确"));
if (!account.hasRole(AccountRole.ADMIN)) {
throw new IllegalArgumentException("账号或密码不正确");
}
if (account.getPasswordHash() == null || !passwordService.matches(password, account.getPasswordHash())) {
throw new IllegalArgumentException("账号或密码不正确");
}
account.assertUsable();
account = account.touchLogin(Instant.now());
accountRepository.save(account);
ProfileResponse profile = profileAssembler.toResponse(
userProfileRepository.findByAccountId(account.getId()).orElse(null));
return buildLoginResponse(account, profile);
}
private AuthLoginResponse buildLoginResponse(Account account, ProfileResponse profile) {
String token = tokenIssuer.issue(account.getId(), account.getRoles(), account.getTokenVersion());
return AuthLoginResponse.builder()
.token(token)
.account(accountAssembler.toSelfResponse(account))
.profile(profile)
.build();
}
private String resolveNickname(String nickname) {
if (nickname != null && !nickname.isBlank()) {
return nickname.trim();
}
return "用户" + String.format("%04d", RANDOM.nextInt(10_000));
}
/** 仅供后续 feature 复用:当前账号的对外视图。 */
public AccountResponse toSelfResponse(Account account) {
return accountAssembler.toSelfResponse(account);
}
}

View File

@@ -0,0 +1,68 @@
package com.consultation.application.service;
import com.consultation.adapter.rest.dto.FavoriteResponse;
import com.consultation.application.assembler.FavoriteAssembler;
import com.consultation.domain.aggregate.FavoriteConsultant;
import com.consultation.domain.repository.FavoriteConsultantRepository;
import com.consultation.domain.service.DisplayableConsultantPort;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
/**
* 收藏用例(R-CREATE-004 幂等收藏 / R-DELETE-001 仅收藏人可取消)。
*/
@Service
@RequiredArgsConstructor
public class FavoriteAppService {
private final FavoriteConsultantRepository favoriteRepository;
private final DisplayableConsultantPort displayableConsultantPort;
private final FavoriteAssembler favoriteAssembler;
public List<FavoriteResponse> list(String accountId) {
return favoriteRepository.findByAccountId(accountId).stream()
.map(favoriteAssembler::toResponse)
.toList();
}
/**
* 收藏咨询师(幂等):已收藏直接返回既有记录。
*/
@Transactional
public FavoriteResponse add(String accountId, String consultantId) {
if (consultantId == null || consultantId.isBlank()) {
throw new IllegalArgumentException("咨询师ID不能为空");
}
String trimmed = consultantId.trim();
if (!displayableConsultantPort.isDisplayable(trimmed)) {
throw new IllegalArgumentException("咨询师不存在或不可展示");
}
return favoriteRepository.findByAccountIdAndConsultantId(accountId, trimmed)
.map(favoriteAssembler::toResponse)
.orElseGet(() -> {
FavoriteConsultant created = FavoriteConsultant.builder()
.id(UUID.randomUUID().toString())
.accountId(accountId)
.consultantId(trimmed)
.createdAt(Instant.now())
.build();
return favoriteAssembler.toResponse(favoriteRepository.save(created));
});
}
/**
* 取消收藏(幂等):未收藏也按成功处理。
*/
@Transactional
public void remove(String accountId, String consultantId) {
if (consultantId == null || consultantId.isBlank()) {
throw new IllegalArgumentException("咨询师ID不能为空");
}
favoriteRepository.deleteByAccountIdAndConsultantId(accountId, consultantId.trim());
}
}

View File

@@ -0,0 +1,58 @@
package com.consultation.application.service;
import com.consultation.adapter.rest.dto.MeResponse;
import com.consultation.adapter.rest.dto.ProfileResponse;
import com.consultation.application.assembler.AccountAssembler;
import com.consultation.application.assembler.ProfileAssembler;
import com.consultation.domain.aggregate.Account;
import com.consultation.domain.aggregate.UserProfile;
import com.consultation.domain.repository.AccountRepository;
import com.consultation.domain.repository.UserProfileRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
/**
* 本人资料用例(R-UPDATE-001:仅本人可改)。
*/
@Service
@RequiredArgsConstructor
public class ProfileAppService {
private final AccountRepository accountRepository;
private final UserProfileRepository userProfileRepository;
private final AccountAssembler accountAssembler;
private final ProfileAssembler profileAssembler;
public MeResponse getMe(String accountId) {
Account account = requireAccount(accountId);
ProfileResponse profile = profileAssembler.toResponse(
userProfileRepository.findByAccountId(accountId).orElse(null));
return MeResponse.builder()
.account(accountAssembler.toSelfResponse(account))
.profile(profile)
.build();
}
@Transactional
public ProfileResponse updateProfile(String accountId, String nickname, String avatarUrl,
String email, String cityCode, String locale) {
requireAccount(accountId);
Instant now = Instant.now();
UserProfile profile = userProfileRepository.findByAccountId(accountId)
.map(existing -> existing.update(nickname, avatarUrl, email, cityCode, locale, now))
.orElseGet(() -> UserProfile.create(accountId,
nickname == null || nickname.isBlank() ? "用户" : nickname,
locale == null || locale.isBlank() ? UserProfile.DEFAULT_LOCALE : locale,
now));
userProfileRepository.save(profile);
return profileAssembler.toResponse(profile);
}
private Account requireAccount(String accountId) {
return accountRepository.findById(accountId)
.orElseThrow(() -> new IllegalArgumentException("账号不存在"));
}
}

View File

@@ -0,0 +1,149 @@
package com.consultation.domain.aggregate;
import com.consultation.domain.vo.AccountRole;
import com.consultation.domain.vo.AccountStatus;
import lombok.Builder;
import lombok.Getter;
import java.time.Instant;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* 账号聚合根:角色集合、状态机、tokenVersion、登录校验。
*
* <p>不可变对象,状态流转返回新实例({@code toBuilder})。</p>
*/
@Getter
@Builder(toBuilder = true)
public class Account {
private final String id;
/** 手机号摘要,唯一登录标识。 */
private final String phoneHash;
/** 手机号密文,仅本人可解密查看。 */
private final String phoneCipher;
private final Set<AccountRole> roles;
private final AccountStatus status;
private final Instant phoneVerifiedAt;
private final Instant lastLoginAt;
private final String disabledReason;
/** 抬升后旧 JWT 立即失效。 */
private final int tokenVersion;
/** 仅 ADMIN 账号使用。 */
private final String passwordHash;
private final Instant createdAt;
private final Instant updatedAt;
/**
* 手机号验证码注册(默认 USER 角色)。已有手机号不重复建号,由 AppService 判定。
*
* <p>注册成功即完成一次登录,因此同时记录最近登录时间。</p>
*/
public static Account registerByPhone(String id, String phoneHash, String phoneCipher, Instant now) {
Set<AccountRole> roles = new LinkedHashSet<>();
roles.add(AccountRole.USER);
return Account.builder()
.id(id)
.phoneHash(phoneHash)
.phoneCipher(phoneCipher)
.roles(roles)
.status(AccountStatus.ACTIVE)
.phoneVerifiedAt(now)
.lastLoginAt(now)
.tokenVersion(0)
.createdAt(now)
.updatedAt(now)
.build();
}
/**
* 平台分配的管理员账号(R-COMMON-001:不开放自助注册)。
*/
public static Account createAdmin(String id, String phoneHash, String phoneCipher,
String passwordHash, Instant now) {
Set<AccountRole> roles = new LinkedHashSet<>();
roles.add(AccountRole.ADMIN);
return Account.builder()
.id(id)
.phoneHash(phoneHash)
.phoneCipher(phoneCipher)
.roles(roles)
.status(AccountStatus.ACTIVE)
.phoneVerifiedAt(now)
.tokenVersion(0)
.passwordHash(passwordHash)
.createdAt(now)
.updatedAt(now)
.build();
}
/**
* 授予咨询师角色(幂等),供入驻审核通过后调用(R-UPDATE-002)。
*/
public Account grantConsultantRole(Instant now) {
if (roles.contains(AccountRole.CONSULTANT)) {
return this;
}
Set<AccountRole> next = new LinkedHashSet<>(roles);
next.add(AccountRole.CONSULTANT);
return toBuilder().roles(next).updatedAt(now).build();
}
/**
* 禁用账号:置 DISABLED、记录原因并抬升 tokenVersion 使既有会话失效。重复禁用幂等。
*/
public Account disable(String reason, Instant now) {
if (status == AccountStatus.DISABLED) {
return this;
}
return toBuilder()
.status(AccountStatus.DISABLED)
.disabledReason(reason)
.tokenVersion(tokenVersion + 1)
.updatedAt(now)
.build();
}
/**
* 启用账号:回 ACTIVE 并再次抬升 tokenVersion。重复启用幂等。
*/
public Account enable(Instant now) {
if (status == AccountStatus.ACTIVE) {
return this;
}
return toBuilder()
.status(AccountStatus.ACTIVE)
.disabledReason(null)
.tokenVersion(tokenVersion + 1)
.updatedAt(now)
.build();
}
public Account touchLogin(Instant now) {
return toBuilder().lastLoginAt(now).updatedAt(now).build();
}
public Account verifyPhone(Instant now) {
return toBuilder().phoneVerifiedAt(now).updatedAt(now).build();
}
/**
* 账号不可用时拒绝(EX-002 / AC-005)。
*/
public void assertUsable() {
if (status == AccountStatus.DISABLED) {
throw new IllegalStateException(disabledReason == null || disabledReason.isBlank()
? "账号不可用:已被禁用"
: "账号不可用:" + disabledReason);
}
}
public boolean hasRole(AccountRole role) {
return roles != null && roles.contains(role);
}
public boolean isDisabled() {
return status == AccountStatus.DISABLED;
}
}

View File

@@ -0,0 +1,22 @@
package com.consultation.domain.aggregate;
import com.consultation.domain.vo.AgreementType;
import lombok.Builder;
import lombok.Getter;
import java.time.Instant;
/**
* 协议同意记录:不可变、不可物理删除(DATA-001)。
*/
@Getter
@Builder
public class AgreementConsent {
private final String id;
private final String accountId;
private final AgreementType agreementType;
private final String agreementVersion;
private final Instant consentedAt;
private final String sourceIp;
}

View File

@@ -0,0 +1,19 @@
package com.consultation.domain.aggregate;
import lombok.Builder;
import lombok.Getter;
import java.time.Instant;
/**
* 收藏的咨询师。同一账号与咨询师只能有一条(R-CREATE-004)。
*/
@Getter
@Builder
public class FavoriteConsultant {
private final String id;
private final String accountId;
private final String consultantId;
private final Instant createdAt;
}

View File

@@ -0,0 +1,44 @@
package com.consultation.domain.aggregate;
import lombok.Builder;
import lombok.Getter;
import java.time.Instant;
/**
* 短信验证码:DB 存储,无 Redis 依赖。TTL + 连续失败次数控制(R-CREATE-002)。
*/
@Getter
@Builder(toBuilder = true)
public class SmsVerificationCode {
private final String id;
private final String phoneHash;
private final String codeHash;
private final Instant expiresAt;
private final int failCount;
/** 非空表示已使用或已作废。 */
private final Instant usedAt;
private final Instant createdAt;
public boolean isExpired(Instant now) {
return now.isAfter(expiresAt);
}
public boolean isUsed() {
return usedAt != null;
}
public boolean matches(String candidateHash) {
return codeHash.equals(candidateHash);
}
public SmsVerificationCode recordFailure() {
return toBuilder().failCount(failCount + 1).build();
}
/** 标记为已使用 / 已作废。 */
public SmsVerificationCode invalidate(Instant now) {
return toBuilder().usedAt(now).build();
}
}

View File

@@ -0,0 +1,100 @@
package com.consultation.domain.aggregate;
import lombok.Builder;
import lombok.Getter;
import java.time.Instant;
/**
* 用户资料:昵称、头像、邮箱、城市、语言。
*/
@Getter
@Builder(toBuilder = true)
public class UserProfile {
public static final int NICKNAME_MIN = 2;
public static final int NICKNAME_MAX = 30;
public static final int EMAIL_MAX = 254;
public static final int CITY_CODE_MAX = 20;
public static final int LOCALE_MAX = 16;
public static final String DEFAULT_LOCALE = "zh-CN";
private final String accountId;
private final String nickname;
private final String avatarUrl;
private final String email;
private final String cityCode;
private final String locale;
private final Instant updatedAt;
public static UserProfile create(String accountId, String nickname, String locale, Instant now) {
return UserProfile.builder()
.accountId(accountId)
.nickname(validateNickname(nickname))
.locale(validateLocale(locale))
.updatedAt(now)
.build();
}
/**
* 更新本人资料(R-UPDATE-001:仅昵称 / 头像 / 邮箱 / 城市 / 语言可改)。
*
* <p>PUT 语义:可选字段传空表示清空;昵称为空表示保持原值。</p>
*/
public UserProfile update(String nickname, String avatarUrl, String email,
String cityCode, String locale, Instant now) {
return toBuilder()
.nickname(nickname == null || nickname.isBlank() ? this.nickname : validateNickname(nickname))
.avatarUrl(trimToNull(avatarUrl))
.email(email == null || email.isBlank() ? null : validateEmail(email))
.cityCode(cityCode == null || cityCode.isBlank() ? null : validateCityCode(cityCode))
.locale(locale == null || locale.isBlank() ? this.locale : validateLocale(locale))
.updatedAt(now)
.build();
}
private static String validateNickname(String nickname) {
if (nickname == null || nickname.isBlank()) {
throw new IllegalArgumentException("昵称不能为空");
}
String trimmed = nickname.trim();
if (trimmed.length() < NICKNAME_MIN || trimmed.length() > NICKNAME_MAX) {
throw new IllegalArgumentException("昵称长度需为 2-30 个字符");
}
return trimmed;
}
private static String validateEmail(String email) {
String trimmed = email.trim();
if (trimmed.length() > EMAIL_MAX) {
throw new IllegalArgumentException("邮箱长度不能超过 254 个字符");
}
if (!trimmed.matches("^[\\w.%+-]+@[\\w.-]+\\.[A-Za-z]{2,}$")) {
throw new IllegalArgumentException("邮箱格式不正确");
}
return trimmed;
}
private static String validateLocale(String locale) {
String trimmed = locale.trim();
if (trimmed.length() > LOCALE_MAX) {
throw new IllegalArgumentException("语言标识长度不能超过 16 个字符");
}
return trimmed;
}
private static String validateCityCode(String cityCode) {
String trimmed = cityCode.trim();
if (trimmed.length() > CITY_CODE_MAX) {
throw new IllegalArgumentException("城市编码长度不能超过 20 个字符");
}
return trimmed;
}
private static String trimToNull(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
}

View File

@@ -0,0 +1,33 @@
package com.consultation.domain.datadictionary;
import com.consultation.domain.vo.AccountRole;
import com.consultation.domain.vo.AccountStatus;
import com.consultation.domain.vo.AgreementType;
/**
* ACC 账号域数据字典类型。
*/
public enum AccDataDictionaryType implements DataDictionaryType {
ACCOUNT_STATUS(AccountStatus.class, "账号状态"),
ACCOUNT_ROLE(AccountRole.class, "账号角色"),
AGREEMENT_TYPE(AgreementType.class, "协议类型");
private final Class<? extends Description> clazz;
private final String description;
AccDataDictionaryType(Class<? extends Description> clazz, String description) {
this.clazz = clazz;
this.description = description;
}
@Override
public Class<? extends Description> getClazz() {
return clazz;
}
@Override
public String getDescription() {
return description;
}
}

View File

@@ -0,0 +1,15 @@
package com.consultation.domain.repository;
import com.consultation.domain.aggregate.Account;
import java.util.Optional;
public interface AccountRepository {
Optional<Account> findById(String id);
Optional<Account> findByPhoneHash(String phoneHash);
/** 新增或更新(按 id 判定)。 */
Account save(Account account);
}

View File

@@ -0,0 +1,16 @@
package com.consultation.domain.repository;
import com.consultation.domain.aggregate.AgreementConsent;
import com.consultation.domain.vo.AgreementType;
import java.util.List;
import java.util.Optional;
public interface AgreementConsentRepository {
List<AgreementConsent> findByAccountId(String accountId);
Optional<AgreementConsent> findByAccountIdAndTypeAndVersion(String accountId, AgreementType type, String version);
AgreementConsent save(AgreementConsent consent);
}

View File

@@ -0,0 +1,18 @@
package com.consultation.domain.repository;
import com.consultation.domain.aggregate.FavoriteConsultant;
import java.util.List;
import java.util.Optional;
public interface FavoriteConsultantRepository {
List<FavoriteConsultant> findByAccountId(String accountId);
Optional<FavoriteConsultant> findByAccountIdAndConsultantId(String accountId, String consultantId);
FavoriteConsultant save(FavoriteConsultant favorite);
/** 取消收藏;记录不存在时静默成功(幂等)。 */
void deleteByAccountIdAndConsultantId(String accountId, String consultantId);
}

View File

@@ -0,0 +1,13 @@
package com.consultation.domain.repository;
import com.consultation.domain.aggregate.SmsVerificationCode;
import java.util.Optional;
public interface SmsVerificationCodeRepository {
/** 该手机号最近一条未失效的验证码(按创建时间倒序取第一条)。 */
Optional<SmsVerificationCode> findLatestByPhoneHash(String phoneHash);
SmsVerificationCode save(SmsVerificationCode code);
}

View File

@@ -0,0 +1,12 @@
package com.consultation.domain.repository;
import com.consultation.domain.aggregate.UserProfile;
import java.util.Optional;
public interface UserProfileRepository {
Optional<UserProfile> findByAccountId(String accountId);
UserProfile save(UserProfile profile);
}

View File

@@ -0,0 +1,9 @@
package com.consultation.domain.service;
/**
* 咨询师「可展示」判定端口。本期由 ACC 提供 Stub 实现,CDC/COB 落地后替换为真实实现。
*/
public interface DisplayableConsultantPort {
boolean isDisplayable(String consultantId);
}

View File

@@ -0,0 +1,16 @@
package com.consultation.domain.service;
/**
* 手机号加解密端口。实现位于 infrastructure(本期为 AES-GCM)。
*/
public interface PhoneCrypto {
/** 摘要(不可逆),用于唯一查询与等值比较。 */
String hash(String plaintext);
/** 加密(可逆),用于库内存储并仅向本人解密展示。 */
String encrypt(String plaintext);
/** 解密。 */
String decrypt(String ciphertext);
}

View File

@@ -0,0 +1,112 @@
package com.consultation.domain.service;
import com.consultation.domain.aggregate.SmsVerificationCode;
import com.consultation.domain.repository.SmsVerificationCodeRepository;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.UUID;
/**
* 短信验证码领域服务:签发、校验、TTL、连续失败作废、重发限流。
*
* <p>纯 Java(不依赖 Spring),由 infrastructure 配置类注册为 Bean。</p>
*/
public class SmsCodeService {
/** 验证码有效期。 */
public static final Duration DEFAULT_TTL = Duration.ofMinutes(5);
/** 同一手机号重发间隔。 */
public static final Duration DEFAULT_RESEND_INTERVAL = Duration.ofSeconds(60);
/** 连续失败上限,超过即作废(R-CREATE-002)。 */
public static final int DEFAULT_MAX_FAILURES = 5;
private static final SecureRandom RANDOM = new SecureRandom();
private static final int CODE_BOUND = 1_000_000;
private final SmsVerificationCodeRepository repository;
private final SmsSender smsSender;
private final PhoneCrypto phoneCrypto;
private final Duration ttl;
private final Duration resendInterval;
private final int maxFailures;
private final Clock clock;
public SmsCodeService(SmsVerificationCodeRepository repository, SmsSender smsSender, PhoneCrypto phoneCrypto) {
this(repository, smsSender, phoneCrypto, DEFAULT_TTL, DEFAULT_RESEND_INTERVAL, DEFAULT_MAX_FAILURES,
Clock.systemUTC());
}
public SmsCodeService(SmsVerificationCodeRepository repository, SmsSender smsSender, PhoneCrypto phoneCrypto,
Duration ttl, Duration resendInterval, int maxFailures, Clock clock) {
this.repository = repository;
this.smsSender = smsSender;
this.phoneCrypto = phoneCrypto;
this.ttl = ttl;
this.resendInterval = resendInterval;
this.maxFailures = maxFailures;
this.clock = clock;
}
/**
* 签发验证码并发送。
*
* @param phone 明文手机号(用于发送)
* @param phoneHash 手机号摘要(用于查询)
*/
public void issue(String phone, String phoneHash) {
Instant now = clock.instant();
repository.findLatestByPhoneHash(phoneHash).ifPresent(latest -> {
if (now.isBefore(latest.getCreatedAt().plus(resendInterval))) {
throw new IllegalStateException("验证码发送过于频繁,请稍后再试");
}
});
String code = randomCode();
String delivered = smsSender.send(phone, code);
SmsVerificationCode entity = SmsVerificationCode.builder()
.id(UUID.randomUUID().toString())
.phoneHash(phoneHash)
.codeHash(hashCode(phoneHash, delivered))
.expiresAt(now.plus(ttl))
.failCount(0)
.createdAt(now)
.build();
repository.save(entity);
}
/**
* 校验验证码;失败抛 IllegalArgumentException(400),连续失败超限后作废。
*/
public void verify(String phoneHash, String code) {
Instant now = clock.instant();
SmsVerificationCode entity = repository.findLatestByPhoneHash(phoneHash)
.orElseThrow(() -> new IllegalArgumentException("验证码不存在或已过期"));
if (entity.isUsed()) {
throw new IllegalArgumentException("验证码已使用,请重新获取");
}
if (entity.isExpired(now)) {
throw new IllegalArgumentException("验证码已过期,请重新获取");
}
if (!entity.matches(hashCode(phoneHash, code))) {
SmsVerificationCode failed = entity.recordFailure();
if (failed.getFailCount() >= maxFailures) {
repository.save(failed.invalidate(now));
throw new IllegalArgumentException("验证码连续错误次数过多,已作废");
}
repository.save(failed);
throw new IllegalArgumentException("验证码错误");
}
repository.save(entity.invalidate(now));
}
private String hashCode(String phoneHash, String code) {
return phoneCrypto.hash("sms:" + phoneHash + ":" + code);
}
private String randomCode() {
return String.format("%06d", RANDOM.nextInt(CODE_BOUND));
}
}

View File

@@ -0,0 +1,11 @@
package com.consultation.domain.service;
/**
* 短信发送端口。本期实现为本地 Mock,真短信通道归 PLT。
*
* <p>返回实际送达的验证码:Mock 固定码场景下返回固定值,调用方按返回值落摘要。</p>
*/
public interface SmsSender {
String send(String phone, String code);
}

View File

@@ -0,0 +1,13 @@
package com.consultation.domain.service;
import com.consultation.domain.vo.AccountRole;
import java.util.Set;
/**
* 令牌签发端口。实现位于 infrastructure(本期为 JWT HMAC-SHA256)。
*/
public interface TokenIssuer {
String issue(String accountId, Set<AccountRole> roles, int tokenVersion);
}

View File

@@ -0,0 +1,33 @@
package com.consultation.domain.vo;
import com.consultation.domain.datadictionary.Description;
/**
* 账号角色。JWT authority = {@code ROLE_<name>},与 Spring Security {@code hasRole} 对齐。
*/
public enum AccountRole implements Description {
USER("终端用户"),
CONSULTANT("咨询师"),
ADMIN("管理员");
private final String description;
AccountRole(String description) {
this.description = description;
}
@Override
public String getCode() {
return name();
}
@Override
public String getDescription() {
return description;
}
public String authority() {
return "ROLE_" + name();
}
}

View File

@@ -0,0 +1,28 @@
package com.consultation.domain.vo;
import com.consultation.domain.datadictionary.Description;
/**
* 账号状态。对外 JSON 与库内取值统一使用大写枚举名。
*/
public enum AccountStatus implements Description {
ACTIVE("正常"),
DISABLED("已禁用");
private final String description;
AccountStatus(String description) {
this.description = description;
}
@Override
public String getCode() {
return name();
}
@Override
public String getDescription() {
return description;
}
}

View File

@@ -0,0 +1,41 @@
package com.consultation.domain.vo;
import com.consultation.domain.datadictionary.Description;
/**
* 协议类型。领域枚举名大写,对外 API 码小写(service / privacy)。
*/
public enum AgreementType implements Description {
SERVICE("service", "服务协议"),
PRIVACY("privacy", "隐私政策");
private final String code;
private final String description;
AgreementType(String code, String description) {
this.code = code;
this.description = description;
}
@Override
public String getCode() {
return code;
}
@Override
public String getDescription() {
return description;
}
public static AgreementType fromCode(String code) {
if (code != null) {
for (AgreementType type : values()) {
if (type.code.equalsIgnoreCase(code.trim()) || type.name().equalsIgnoreCase(code.trim())) {
return type;
}
}
}
throw new IllegalArgumentException("协议类型不正确");
}
}

View File

@@ -0,0 +1,39 @@
package com.consultation.domain.vo;
/**
* 手机号值对象:规范化(去空格与横线)并校验格式。
*/
public final class PhoneNumber {
private static final String PATTERN = "^1[3-9]\\d{9}$";
private final String value;
private PhoneNumber(String value) {
this.value = value;
}
public static PhoneNumber of(String raw) {
if (raw == null) {
throw new IllegalArgumentException("手机号不能为空");
}
String normalized = raw.trim().replaceAll("[\\s\\-()]", "");
if (!normalized.matches(PATTERN)) {
throw new IllegalArgumentException("手机号格式不正确");
}
return new PhoneNumber(normalized);
}
public String value() {
return value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return value;
}
}

View File

@@ -0,0 +1,77 @@
package com.consultation.infrastructure.config;
import com.consultation.domain.aggregate.Account;
import com.consultation.domain.repository.AccountRepository;
import com.consultation.domain.service.PasswordService;
import com.consultation.domain.service.PhoneCrypto;
import com.consultation.domain.vo.PhoneNumber;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.UUID;
/**
* 平台管理员账号种子(R-COMMON-001:ADMIN 只由平台分配)。
*
* <p>运行时创建而非写死在 data.sql:管理员手机号需要用当前环境的加密密钥落密文。</p>
*/
@Slf4j
@Component
public class AccountSeedInitializer implements ApplicationRunner {
private final AccountRepository accountRepository;
private final PhoneCrypto phoneCrypto;
private final PasswordService passwordService;
private final boolean enabled;
private final String adminPhone;
private final String adminPassword;
public AccountSeedInitializer(AccountRepository accountRepository,
PhoneCrypto phoneCrypto,
PasswordService passwordService,
@Value("${seed.admin.enabled:true}") boolean enabled,
@Value("${seed.admin.phone:13900000000}") String adminPhone,
@Value("${seed.admin.password:Admin@12345}") String adminPassword) {
this.accountRepository = accountRepository;
this.phoneCrypto = phoneCrypto;
this.passwordService = passwordService;
this.enabled = enabled;
this.adminPhone = adminPhone;
this.adminPassword = adminPassword;
}
@Override
public void run(ApplicationArguments args) {
ensureAdminAccount();
}
/**
* 若管理员账号不存在则创建(幂等)。返回新建的账号,已存在时返回 null。
*/
@Transactional
public Account ensureAdminAccount() {
if (!enabled) {
return null;
}
String phone = PhoneNumber.of(adminPhone).value();
String phoneHash = phoneCrypto.hash(phone);
if (accountRepository.findByPhoneHash(phoneHash).isPresent()) {
return null;
}
Account admin = Account.createAdmin(
UUID.randomUUID().toString(),
phoneHash,
phoneCrypto.encrypt(phone),
passwordService.encode(adminPassword),
Instant.now());
accountRepository.save(admin);
log.info("已创建平台管理员账号:{}", adminPhone);
return admin;
}
}

View File

@@ -0,0 +1,31 @@
package com.consultation.infrastructure.config;
import com.consultation.domain.repository.SmsVerificationCodeRepository;
import com.consultation.domain.service.PhoneCrypto;
import com.consultation.domain.service.SmsCodeService;
import com.consultation.domain.service.SmsSender;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Clock;
import java.time.Duration;
/**
* 领域服务的 Bean 注册(领域层保持纯 Java,不依赖 Spring)。
*/
@Configuration
public class DomainServiceConfig {
@Bean
public SmsCodeService smsCodeService(SmsVerificationCodeRepository repository,
SmsSender smsSender,
PhoneCrypto phoneCrypto,
@Value("${sms.code.ttl-seconds:300}") long ttlSeconds,
@Value("${sms.code.resend-interval-seconds:60}") long resendIntervalSeconds,
@Value("${sms.code.max-failures:5}") int maxFailures) {
return new SmsCodeService(repository, smsSender, phoneCrypto,
Duration.ofSeconds(ttlSeconds), Duration.ofSeconds(resendIntervalSeconds), maxFailures,
Clock.systemUTC());
}
}

View File

@@ -1,5 +1,6 @@
package com.consultation.infrastructure.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@@ -13,6 +14,8 @@ public class JacksonConfig {
ObjectMapper m = new ObjectMapper();
m.registerModule(new JavaTimeModule());
m.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 与 Spring Boot 默认行为一致:忽略请求体中的未知字段,避免 500
m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
return m;
}
}

View File

@@ -1,9 +1,12 @@
package com.consultation.infrastructure.config;
import com.consultation.infrastructure.security.JwtAuthenticationFilter;
import com.consultation.infrastructure.security.RestAccessDeniedHandler;
import com.consultation.infrastructure.security.RestAuthenticationEntryPoint;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@@ -18,13 +21,21 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
public class SecurityConfig {
private final JwtAuthenticationFilter jwtFilter;
private final RestAuthenticationEntryPoint authenticationEntryPoint;
private final RestAccessDeniedHandler accessDeniedHandler;
@Bean
public SecurityFilterChain chain(HttpSecurity http) throws Exception {
http.csrf(c -> c.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(e -> e
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler)
)
.authorizeHttpRequests(a -> a
.requestMatchers("/api/v1/health").permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/auth/**").permitAll()
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);

View File

@@ -0,0 +1,35 @@
package com.consultation.infrastructure.consultant;
import com.consultation.domain.service.DisplayableConsultantPort;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* 「可展示咨询师」Stub 实现:白名单 ID 视为可展示。
*
* <p>CDC / COB 落地后由真实实现替换(consultant.displayable-ids 配置项)。</p>
*/
@Component
public class StubDisplayableConsultantPort implements DisplayableConsultantPort {
private final Set<String> displayableIds = new LinkedHashSet<>();
public StubDisplayableConsultantPort(@Value("${consultant.displayable-ids:}") String csv) {
if (csv != null && !csv.isBlank()) {
for (String id : csv.split(",")) {
String trimmed = id.trim();
if (!trimmed.isEmpty()) {
displayableIds.add(trimmed);
}
}
}
}
@Override
public boolean isDisplayable(String consultantId) {
return consultantId != null && displayableIds.contains(consultantId.trim());
}
}

View File

@@ -0,0 +1,101 @@
package com.consultation.infrastructure.crypto;
import com.consultation.domain.service.PhoneCrypto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
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.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
/**
* 手机号加密实现:摘要用 HMAC-SHA256(带密钥,防暴力枚举),密文用 AES-256-GCM。
*
* <p>密钥来自配置 {@code phone.crypto.key},生产环境必须通过环境变量注入,禁止写入仓库。</p>
*/
@Component
public class AesPhoneCrypto implements PhoneCrypto {
private static final String HMAC_ALGORITHM = "HmacSHA256";
private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_BITS = 128;
private final byte[] key;
private final SecureRandom random = new SecureRandom();
public AesPhoneCrypto(@Value("${phone.crypto.key}") String configuredKey) {
if (configuredKey == null || configuredKey.isBlank()) {
throw new IllegalStateException("phone.crypto.key 未配置,无法启动");
}
this.key = sha256(configuredKey.getBytes(StandardCharsets.UTF_8));
}
@Override
public String hash(String plaintext) {
try {
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(new SecretKeySpec(key, HMAC_ALGORITHM));
return HexFormat.of().formatHex(mac.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
throw new IllegalStateException("手机号摘要计算失败");
}
}
@Override
public String encrypt(String plaintext) {
try {
byte[] iv = new byte[GCM_IV_LENGTH];
random.nextBytes(iv);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
new GCMParameterSpec(GCM_TAG_BITS, iv));
byte[] encrypted = cipher.doFinal(plaintext.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 Base64.getEncoder().encodeToString(payload);
} catch (Exception e) {
throw new IllegalStateException("手机号加密失败");
}
}
@Override
public String decrypt(String ciphertext) {
if (ciphertext == null || ciphertext.isBlank()) {
throw new IllegalArgumentException("手机号密文不存在");
}
try {
byte[] payload = Base64.getDecoder().decode(ciphertext);
if (payload.length <= GCM_IV_LENGTH) {
throw new IllegalArgumentException("手机号密文不合法");
}
byte[] iv = new byte[GCM_IV_LENGTH];
System.arraycopy(payload, 0, iv, 0, GCM_IV_LENGTH);
byte[] encrypted = new byte[payload.length - GCM_IV_LENGTH];
System.arraycopy(payload, GCM_IV_LENGTH, encrypted, 0, encrypted.length);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
new GCMParameterSpec(GCM_TAG_BITS, iv));
return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("手机号解密失败");
}
}
private byte[] sha256(byte[] input) {
try {
return MessageDigest.getInstance("SHA-256").digest(input);
} catch (Exception e) {
throw new IllegalStateException("密钥派生失败");
}
}
}

View File

@@ -0,0 +1,90 @@
package com.consultation.infrastructure.persistence.converter;
import com.consultation.domain.aggregate.Account;
import com.consultation.domain.vo.AccountRole;
import com.consultation.domain.vo.AccountStatus;
import com.consultation.infrastructure.persistence.po.AccountPO;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@Component
@RequiredArgsConstructor
public class AccountConverter {
private final ObjectMapper objectMapper;
public Account toDomain(AccountPO po) {
if (po == null) {
return null;
}
Instant phoneVerifiedAt = TimeConverter.toInstant(po.getPhoneVerifiedAt());
return Account.builder()
.id(po.getId())
.phoneHash(po.getPhoneHash())
.phoneCipher(po.getPhoneCipher())
.roles(toRoles(po.getRolesJson()))
.status(po.getStatus() == null ? AccountStatus.ACTIVE : AccountStatus.valueOf(po.getStatus()))
.phoneVerifiedAt(phoneVerifiedAt)
.lastLoginAt(TimeConverter.toInstant(po.getLastLoginAt()))
.disabledReason(po.getDisabledReason())
.tokenVersion(po.getTokenVersion() == null ? 0 : po.getTokenVersion())
.passwordHash(po.getPasswordHash())
.createdAt(TimeConverter.toInstant(po.getCreatedAt()))
.updatedAt(TimeConverter.toInstant(po.getUpdatedAt()))
.build();
}
public AccountPO toPO(Account account) {
if (account == null) {
return null;
}
AccountPO po = new AccountPO();
po.setId(account.getId());
po.setPhoneHash(account.getPhoneHash());
po.setPhoneCipher(account.getPhoneCipher());
po.setRolesJson(toRolesJson(account.getRoles()));
po.setStatus(account.getStatus().name());
po.setPhoneVerifiedAt(TimeConverter.toLocalDateTime(account.getPhoneVerifiedAt()));
po.setLastLoginAt(TimeConverter.toLocalDateTime(account.getLastLoginAt()));
po.setDisabledReason(account.getDisabledReason());
po.setTokenVersion(account.getTokenVersion());
po.setPasswordHash(account.getPasswordHash());
po.setCreatedAt(TimeConverter.toLocalDateTime(account.getCreatedAt()));
po.setUpdatedAt(TimeConverter.toLocalDateTime(account.getUpdatedAt()));
return po;
}
private Set<AccountRole> toRoles(String rolesJson) {
Set<AccountRole> roles = new LinkedHashSet<>();
if (rolesJson == null || rolesJson.isBlank()) {
return roles;
}
try {
List<String> names = objectMapper.readValue(rolesJson, new TypeReference<List<String>>() {
});
for (String name : names) {
roles.add(AccountRole.valueOf(name));
}
} catch (Exception e) {
throw new IllegalStateException("账号角色数据损坏:" + rolesJson);
}
return roles;
}
private String toRolesJson(Set<AccountRole> roles) {
List<String> names = roles == null ? List.of()
: roles.stream().map(Enum::name).sorted().toList();
try {
return objectMapper.writeValueAsString(names);
} catch (Exception e) {
throw new IllegalStateException("账号角色序列化失败");
}
}
}

View File

@@ -0,0 +1,38 @@
package com.consultation.infrastructure.persistence.converter;
import com.consultation.domain.aggregate.AgreementConsent;
import com.consultation.domain.vo.AgreementType;
import com.consultation.infrastructure.persistence.po.AgreementConsentPO;
import org.springframework.stereotype.Component;
@Component
public class AgreementConsentConverter {
public AgreementConsent toDomain(AgreementConsentPO po) {
if (po == null) {
return null;
}
return AgreementConsent.builder()
.id(po.getId())
.accountId(po.getAccountId())
.agreementType(AgreementType.valueOf(po.getAgreementType()))
.agreementVersion(po.getAgreementVersion())
.consentedAt(TimeConverter.toInstant(po.getConsentedAt()))
.sourceIp(po.getSourceIp())
.build();
}
public AgreementConsentPO toPO(AgreementConsent consent) {
if (consent == null) {
return null;
}
AgreementConsentPO po = new AgreementConsentPO();
po.setId(consent.getId());
po.setAccountId(consent.getAccountId());
po.setAgreementType(consent.getAgreementType().name());
po.setAgreementVersion(consent.getAgreementVersion());
po.setConsentedAt(TimeConverter.toLocalDateTime(consent.getConsentedAt()));
po.setSourceIp(consent.getSourceIp());
return po;
}
}

View File

@@ -0,0 +1,33 @@
package com.consultation.infrastructure.persistence.converter;
import com.consultation.domain.aggregate.FavoriteConsultant;
import com.consultation.infrastructure.persistence.po.FavoriteConsultantPO;
import org.springframework.stereotype.Component;
@Component
public class FavoriteConsultantConverter {
public FavoriteConsultant toDomain(FavoriteConsultantPO po) {
if (po == null) {
return null;
}
return FavoriteConsultant.builder()
.id(po.getId())
.accountId(po.getAccountId())
.consultantId(po.getConsultantId())
.createdAt(TimeConverter.toInstant(po.getCreatedAt()))
.build();
}
public FavoriteConsultantPO toPO(FavoriteConsultant favorite) {
if (favorite == null) {
return null;
}
FavoriteConsultantPO po = new FavoriteConsultantPO();
po.setId(favorite.getId());
po.setAccountId(favorite.getAccountId());
po.setConsultantId(favorite.getConsultantId());
po.setCreatedAt(TimeConverter.toLocalDateTime(favorite.getCreatedAt()));
return po;
}
}

View File

@@ -0,0 +1,39 @@
package com.consultation.infrastructure.persistence.converter;
import com.consultation.domain.aggregate.SmsVerificationCode;
import com.consultation.infrastructure.persistence.po.SmsVerificationCodePO;
import org.springframework.stereotype.Component;
@Component
public class SmsVerificationCodeConverter {
public SmsVerificationCode toDomain(SmsVerificationCodePO po) {
if (po == null) {
return null;
}
return SmsVerificationCode.builder()
.id(po.getId())
.phoneHash(po.getPhoneHash())
.codeHash(po.getCodeHash())
.expiresAt(TimeConverter.toInstant(po.getExpiresAt()))
.failCount(po.getFailCount() == null ? 0 : po.getFailCount())
.usedAt(TimeConverter.toInstant(po.getUsedAt()))
.createdAt(TimeConverter.toInstant(po.getCreatedAt()))
.build();
}
public SmsVerificationCodePO toPO(SmsVerificationCode code) {
if (code == null) {
return null;
}
SmsVerificationCodePO po = new SmsVerificationCodePO();
po.setId(code.getId());
po.setPhoneHash(code.getPhoneHash());
po.setCodeHash(code.getCodeHash());
po.setExpiresAt(TimeConverter.toLocalDateTime(code.getExpiresAt()));
po.setFailCount(code.getFailCount());
po.setUsedAt(TimeConverter.toLocalDateTime(code.getUsedAt()));
po.setCreatedAt(TimeConverter.toLocalDateTime(code.getCreatedAt()));
return po;
}
}

View File

@@ -0,0 +1,24 @@
package com.consultation.infrastructure.persistence.converter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
/**
* 领域时间(Instant,UTC 语义)与库内时间(DATETIME,Asia/Shanghai)互转。
*/
public final class TimeConverter {
public static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private TimeConverter() {
}
public static LocalDateTime toLocalDateTime(Instant instant) {
return instant == null ? null : LocalDateTime.ofInstant(instant, ZONE);
}
public static Instant toInstant(LocalDateTime localDateTime) {
return localDateTime == null ? null : localDateTime.atZone(ZONE).toInstant();
}
}

View File

@@ -0,0 +1,39 @@
package com.consultation.infrastructure.persistence.converter;
import com.consultation.domain.aggregate.UserProfile;
import com.consultation.infrastructure.persistence.po.UserProfilePO;
import org.springframework.stereotype.Component;
@Component
public class UserProfileConverter {
public UserProfile toDomain(UserProfilePO po) {
if (po == null) {
return null;
}
return UserProfile.builder()
.accountId(po.getAccountId())
.nickname(po.getNickname())
.avatarUrl(po.getAvatarUrl())
.email(po.getEmail())
.cityCode(po.getCityCode())
.locale(po.getLocale())
.updatedAt(TimeConverter.toInstant(po.getUpdatedAt()))
.build();
}
public UserProfilePO toPO(UserProfile profile) {
if (profile == null) {
return null;
}
UserProfilePO po = new UserProfilePO();
po.setAccountId(profile.getAccountId());
po.setNickname(profile.getNickname());
po.setAvatarUrl(profile.getAvatarUrl());
po.setEmail(profile.getEmail());
po.setCityCode(profile.getCityCode());
po.setLocale(profile.getLocale());
po.setUpdatedAt(TimeConverter.toLocalDateTime(profile.getUpdatedAt()));
return po;
}
}

View File

@@ -0,0 +1,9 @@
package com.consultation.infrastructure.persistence.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.consultation.infrastructure.persistence.po.AccountPO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AccountMapper extends BaseMapper<AccountPO> {
}

View File

@@ -0,0 +1,9 @@
package com.consultation.infrastructure.persistence.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.consultation.infrastructure.persistence.po.AgreementConsentPO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AgreementConsentMapper extends BaseMapper<AgreementConsentPO> {
}

View File

@@ -0,0 +1,9 @@
package com.consultation.infrastructure.persistence.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.consultation.infrastructure.persistence.po.FavoriteConsultantPO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface FavoriteConsultantMapper extends BaseMapper<FavoriteConsultantPO> {
}

View File

@@ -0,0 +1,9 @@
package com.consultation.infrastructure.persistence.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.consultation.infrastructure.persistence.po.SmsVerificationCodePO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SmsVerificationCodeMapper extends BaseMapper<SmsVerificationCodePO> {
}

View File

@@ -0,0 +1,9 @@
package com.consultation.infrastructure.persistence.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.consultation.infrastructure.persistence.po.UserProfilePO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserProfileMapper extends BaseMapper<UserProfilePO> {
}

View File

@@ -0,0 +1,27 @@
package com.consultation.infrastructure.persistence.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("account")
public class AccountPO {
@TableId(type = IdType.INPUT)
private String id;
private String phoneHash;
private String phoneCipher;
private String rolesJson;
private String status;
private LocalDateTime phoneVerifiedAt;
private LocalDateTime lastLoginAt;
private String disabledReason;
private Integer tokenVersion;
private String passwordHash;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}

View File

@@ -0,0 +1,21 @@
package com.consultation.infrastructure.persistence.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("agreement_consent")
public class AgreementConsentPO {
@TableId(type = IdType.INPUT)
private String id;
private String accountId;
private String agreementType;
private String agreementVersion;
private LocalDateTime consentedAt;
private String sourceIp;
}

View File

@@ -0,0 +1,19 @@
package com.consultation.infrastructure.persistence.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("favorite_consultant")
public class FavoriteConsultantPO {
@TableId(type = IdType.INPUT)
private String id;
private String accountId;
private String consultantId;
private LocalDateTime createdAt;
}

View File

@@ -0,0 +1,22 @@
package com.consultation.infrastructure.persistence.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("sms_verification_code")
public class SmsVerificationCodePO {
@TableId(type = IdType.INPUT)
private String id;
private String phoneHash;
private String codeHash;
private LocalDateTime expiresAt;
private Integer failCount;
private LocalDateTime usedAt;
private LocalDateTime createdAt;
}

View File

@@ -0,0 +1,22 @@
package com.consultation.infrastructure.persistence.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("user_profile")
public class UserProfilePO {
@TableId(type = IdType.INPUT)
private String accountId;
private String nickname;
private String avatarUrl;
private String email;
private String cityCode;
private String locale;
private LocalDateTime updatedAt;
}

View File

@@ -0,0 +1,44 @@
package com.consultation.infrastructure.repositoryimpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.consultation.domain.aggregate.Account;
import com.consultation.domain.repository.AccountRepository;
import com.consultation.infrastructure.persistence.converter.AccountConverter;
import com.consultation.infrastructure.persistence.mapper.AccountMapper;
import com.consultation.infrastructure.persistence.po.AccountPO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
@RequiredArgsConstructor
public class AccountRepositoryImpl implements AccountRepository {
private final AccountMapper mapper;
private final AccountConverter converter;
@Override
public Optional<Account> findById(String id) {
return Optional.ofNullable(converter.toDomain(mapper.selectById(id)));
}
@Override
public Optional<Account> findByPhoneHash(String phoneHash) {
AccountPO po = mapper.selectOne(new LambdaQueryWrapper<AccountPO>()
.eq(AccountPO::getPhoneHash, phoneHash)
.last("LIMIT 1"));
return Optional.ofNullable(converter.toDomain(po));
}
@Override
public Account save(Account account) {
AccountPO po = converter.toPO(account);
if (mapper.selectById(po.getId()) == null) {
mapper.insert(po);
} else {
mapper.updateById(po);
}
return account;
}
}

View File

@@ -0,0 +1,47 @@
package com.consultation.infrastructure.repositoryimpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.consultation.domain.aggregate.AgreementConsent;
import com.consultation.domain.repository.AgreementConsentRepository;
import com.consultation.domain.vo.AgreementType;
import com.consultation.infrastructure.persistence.converter.AgreementConsentConverter;
import com.consultation.infrastructure.persistence.mapper.AgreementConsentMapper;
import com.consultation.infrastructure.persistence.po.AgreementConsentPO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
@RequiredArgsConstructor
public class AgreementConsentRepositoryImpl implements AgreementConsentRepository {
private final AgreementConsentMapper mapper;
private final AgreementConsentConverter converter;
@Override
public List<AgreementConsent> findByAccountId(String accountId) {
return mapper.selectList(new LambdaQueryWrapper<AgreementConsentPO>()
.eq(AgreementConsentPO::getAccountId, accountId)
.orderByDesc(AgreementConsentPO::getConsentedAt))
.stream().map(converter::toDomain).toList();
}
@Override
public Optional<AgreementConsent> findByAccountIdAndTypeAndVersion(String accountId, AgreementType type,
String version) {
AgreementConsentPO po = mapper.selectOne(new LambdaQueryWrapper<AgreementConsentPO>()
.eq(AgreementConsentPO::getAccountId, accountId)
.eq(AgreementConsentPO::getAgreementType, type.name())
.eq(AgreementConsentPO::getAgreementVersion, version)
.last("LIMIT 1"));
return Optional.ofNullable(converter.toDomain(po));
}
@Override
public AgreementConsent save(AgreementConsent consent) {
mapper.insert(converter.toPO(consent));
return consent;
}
}

View File

@@ -0,0 +1,51 @@
package com.consultation.infrastructure.repositoryimpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.consultation.domain.aggregate.FavoriteConsultant;
import com.consultation.domain.repository.FavoriteConsultantRepository;
import com.consultation.infrastructure.persistence.converter.FavoriteConsultantConverter;
import com.consultation.infrastructure.persistence.mapper.FavoriteConsultantMapper;
import com.consultation.infrastructure.persistence.po.FavoriteConsultantPO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
@RequiredArgsConstructor
public class FavoriteConsultantRepositoryImpl implements FavoriteConsultantRepository {
private final FavoriteConsultantMapper mapper;
private final FavoriteConsultantConverter converter;
@Override
public List<FavoriteConsultant> findByAccountId(String accountId) {
return mapper.selectList(new LambdaQueryWrapper<FavoriteConsultantPO>()
.eq(FavoriteConsultantPO::getAccountId, accountId)
.orderByDesc(FavoriteConsultantPO::getCreatedAt))
.stream().map(converter::toDomain).toList();
}
@Override
public Optional<FavoriteConsultant> findByAccountIdAndConsultantId(String accountId, String consultantId) {
FavoriteConsultantPO po = mapper.selectOne(new LambdaQueryWrapper<FavoriteConsultantPO>()
.eq(FavoriteConsultantPO::getAccountId, accountId)
.eq(FavoriteConsultantPO::getConsultantId, consultantId)
.last("LIMIT 1"));
return Optional.ofNullable(converter.toDomain(po));
}
@Override
public FavoriteConsultant save(FavoriteConsultant favorite) {
mapper.insert(converter.toPO(favorite));
return favorite;
}
@Override
public void deleteByAccountIdAndConsultantId(String accountId, String consultantId) {
mapper.delete(new LambdaQueryWrapper<FavoriteConsultantPO>()
.eq(FavoriteConsultantPO::getAccountId, accountId)
.eq(FavoriteConsultantPO::getConsultantId, consultantId));
}
}

View File

@@ -0,0 +1,40 @@
package com.consultation.infrastructure.repositoryimpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.consultation.domain.aggregate.SmsVerificationCode;
import com.consultation.domain.repository.SmsVerificationCodeRepository;
import com.consultation.infrastructure.persistence.converter.SmsVerificationCodeConverter;
import com.consultation.infrastructure.persistence.mapper.SmsVerificationCodeMapper;
import com.consultation.infrastructure.persistence.po.SmsVerificationCodePO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
@RequiredArgsConstructor
public class SmsVerificationCodeRepositoryImpl implements SmsVerificationCodeRepository {
private final SmsVerificationCodeMapper mapper;
private final SmsVerificationCodeConverter converter;
@Override
public Optional<SmsVerificationCode> findLatestByPhoneHash(String phoneHash) {
SmsVerificationCodePO po = mapper.selectOne(new LambdaQueryWrapper<SmsVerificationCodePO>()
.eq(SmsVerificationCodePO::getPhoneHash, phoneHash)
.orderByDesc(SmsVerificationCodePO::getCreatedAt)
.last("LIMIT 1"));
return Optional.ofNullable(converter.toDomain(po));
}
@Override
public SmsVerificationCode save(SmsVerificationCode code) {
SmsVerificationCodePO po = converter.toPO(code);
if (mapper.selectById(po.getId()) == null) {
mapper.insert(po);
} else {
mapper.updateById(po);
}
return code;
}
}

View File

@@ -0,0 +1,35 @@
package com.consultation.infrastructure.repositoryimpl;
import com.consultation.domain.aggregate.UserProfile;
import com.consultation.domain.repository.UserProfileRepository;
import com.consultation.infrastructure.persistence.converter.UserProfileConverter;
import com.consultation.infrastructure.persistence.mapper.UserProfileMapper;
import com.consultation.infrastructure.persistence.po.UserProfilePO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
@RequiredArgsConstructor
public class UserProfileRepositoryImpl implements UserProfileRepository {
private final UserProfileMapper mapper;
private final UserProfileConverter converter;
@Override
public Optional<UserProfile> findByAccountId(String accountId) {
return Optional.ofNullable(converter.toDomain(mapper.selectById(accountId)));
}
@Override
public UserProfile save(UserProfile profile) {
UserProfilePO po = converter.toPO(profile);
if (mapper.selectById(po.getAccountId()) == null) {
mapper.insert(po);
} else {
mapper.updateById(po);
}
return profile;
}
}

View File

@@ -0,0 +1,12 @@
package com.consultation.infrastructure.security;
/**
* 鉴权失败提示在请求属性中的键名。
*/
public final class AuthErrorMessage {
public static final String ATTRIBUTE = "com.consultation.authErrorMessage";
private AuthErrorMessage() {
}
}

View File

@@ -1,5 +1,9 @@
package com.consultation.infrastructure.security;
import com.consultation.domain.aggregate.Account;
import com.consultation.domain.repository.AccountRepository;
import com.consultation.domain.vo.AccountRole;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
@@ -13,37 +17,85 @@ import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* JWT 鉴权过滤器:验签 → 校验账号状态与 tokenVersion → 写入用户上下文。
*
* <p>账号被禁用或 tokenVersion 不一致(被禁用抬升)时不予放行,由认证入口点返回 401。</p>
*/
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider tokenProvider;
private final AccountRepository accountRepository;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String bearer = request.getHeader("Authorization");
if (StringUtils.hasText(bearer) && bearer.startsWith("Bearer ")) {
String token = bearer.substring(7);
if (tokenProvider.validate(token)) {
var claims = tokenProvider.parse(token);
String role = claims.get("role", String.class);
UserContextHolder.set(UserContext.builder()
.userId(claims.getSubject())
.email(claims.get("email", String.class))
.role(role)
.build());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
claims.getSubject(), null,
role != null ? Collections.singletonList(new SimpleGrantedAuthority(role))
: Collections.emptyList()
)
);
}
authenticate(bearer.substring(7), request);
}
try { chain.doFilter(request, response); } finally { UserContextHolder.clear(); SecurityContextHolder.clearContext(); }
try {
chain.doFilter(request, response);
} finally {
UserContextHolder.clear();
SecurityContextHolder.clearContext();
}
}
private void authenticate(String token, HttpServletRequest request) {
if (!tokenProvider.validate(token)) {
request.setAttribute(AuthErrorMessage.ATTRIBUTE, "登录状态无效或已过期");
return;
}
Claims claims = tokenProvider.parse(token);
String accountId = claims.getSubject();
Integer tokenVersion = claims.get(JwtTokenProvider.CLAIM_TOKEN_VERSION, Integer.class);
Optional<Account> found = accountId == null ? Optional.empty() : accountRepository.findById(accountId);
if (found.isEmpty()) {
request.setAttribute(AuthErrorMessage.ATTRIBUTE, "登录状态已失效,请重新登录");
return;
}
Account account = found.get();
if (account.isDisabled()) {
request.setAttribute(AuthErrorMessage.ATTRIBUTE, account.getDisabledReason() == null
? "账号不可用:已被禁用"
: "账号不可用:" + account.getDisabledReason());
return;
}
if (tokenVersion == null || tokenVersion.intValue() != account.getTokenVersion()) {
request.setAttribute(AuthErrorMessage.ATTRIBUTE, "登录状态已失效,请重新登录");
return;
}
Set<String> authorities = new LinkedHashSet<>();
for (AccountRole role : account.getRoles()) {
authorities.add(role.authority());
}
UserContextHolder.set(UserContext.builder()
.userId(account.getId())
.roles(authorities)
.build());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
account.getId(), null,
authorities.stream().map(SimpleGrantedAuthority::new).toList()
)
);
}
/** 读取令牌中的角色声明(调试用)。 */
static List<String> rolesOf(Claims claims) {
Object raw = claims.get(JwtTokenProvider.CLAIM_ROLES);
if (raw instanceof List<?> list) {
return list.stream().map(String::valueOf).toList();
}
return List.of();
}
}

View File

@@ -1,5 +1,8 @@
package com.consultation.infrastructure.security;
import com.consultation.domain.service.TokenIssuer;
import com.consultation.domain.vo.AccountRole;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
@@ -8,9 +11,19 @@ import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* JWT 签发与校验(HMAC-SHA256)。
*
* <p>Claims:{@code sub}=账号 ID、{@code roles}=角色数组、{@code tokenVersion}=会话版本。</p>
*/
@Component
public class JwtTokenProvider {
public class JwtTokenProvider implements TokenIssuer {
public static final String CLAIM_ROLES = "roles";
public static final String CLAIM_TOKEN_VERSION = "tokenVersion";
private final SecretKey key;
private final long expiration;
@@ -20,17 +33,31 @@ public class JwtTokenProvider {
this.expiration = exp;
}
public String generate(String userId, String email, String role) {
@Override
public String issue(String accountId, Set<AccountRole> roles, int tokenVersion) {
Date now = new Date();
return Jwts.builder().subject(userId).claim("email", email).claim("role", role)
.issuedAt(now).expiration(new Date(now.getTime() + expiration)).signWith(key).compact();
List<String> roleNames = roles == null ? List.of()
: roles.stream().map(Enum::name).sorted().toList();
return Jwts.builder()
.subject(accountId)
.claim(CLAIM_ROLES, roleNames)
.claim(CLAIM_TOKEN_VERSION, tokenVersion)
.issuedAt(now)
.expiration(new Date(now.getTime() + expiration))
.signWith(key)
.compact();
}
public io.jsonwebtoken.Claims parse(String token) {
public Claims parse(String token) {
return Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload();
}
public boolean validate(String token) {
try { parse(token); return true; } catch (Exception e) { return false; }
try {
parse(token);
return true;
} catch (Exception e) {
return false;
}
}
}

View File

@@ -0,0 +1,34 @@
package com.consultation.infrastructure.security;
import com.consultation.infrastructure.config.GlobalExceptionHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* 无权限(403)响应。
*/
@Component
@RequiredArgsConstructor
public class RestAccessDeniedHandler implements AccessDeniedHandler {
private final ObjectMapper objectMapper;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
objectMapper.writeValue(response.getWriter(),
new GlobalExceptionHandler.ErrorResponse("FORBIDDEN", "无权访问该资源", null));
}
}

View File

@@ -0,0 +1,37 @@
package com.consultation.infrastructure.security;
import com.consultation.infrastructure.config.GlobalExceptionHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* 未认证(401)响应。鉴权失败不走 GlobalExceptionHandler,由 Spring Security 直接返回,
* 但沿用统一响应体结构,便于前端统一提示。
*/
@Component
@RequiredArgsConstructor
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final ObjectMapper objectMapper;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
Object message = request.getAttribute(AuthErrorMessage.ATTRIBUTE);
String errorMessage = message == null ? "未登录或登录已过期" : String.valueOf(message);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
objectMapper.writeValue(response.getWriter(),
new GlobalExceptionHandler.ErrorResponse("UNAUTHORIZED", errorMessage, null));
}
}

View File

@@ -1,14 +1,31 @@
package com.consultation.infrastructure.security;
public class SecurityUtils {
private SecurityUtils() {
}
public static UserContext currentUser() {
UserContext c = UserContextHolder.get();
if (c == null) throw new IllegalStateException("未登录");
if (c == null) {
throw new IllegalStateException("未登录");
}
return c;
}
public static String currentUserId() { return currentUser().getUserId(); }
public static boolean isAdmin() {
public static String currentUserId() {
return currentUser().getUserId();
}
/**
* 是否具备指定角色。参数可写 "CONSULTANT" 或 "ROLE_CONSULTANT"。
*/
public static boolean hasRole(String role) {
UserContext c = UserContextHolder.get();
return c != null && "ROLE_ADMIN".equals(c.getRole());
return c != null && c.hasRole(role);
}
public static boolean isAdmin() {
return hasRole("ADMIN");
}
}

View File

@@ -4,9 +4,24 @@ import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data @Builder @AllArgsConstructor
import java.util.Set;
/**
* 当前请求的用户上下文。roles 为 Spring Security authority 集合(ROLE_USER 等)。
*/
@Data
@Builder
@AllArgsConstructor
public class UserContext {
private String userId;
private String email;
private String role;
private Set<String> roles;
public boolean hasRole(String role) {
if (role == null || roles == null) {
return false;
}
String authority = role.startsWith("ROLE_") ? role : "ROLE_" + role;
return roles.contains(authority);
}
}

View File

@@ -0,0 +1,55 @@
package com.consultation.infrastructure.sms;
import com.consultation.domain.service.SmsSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicReference;
/**
* 本地 Mock 短信通道:真短信供应商接入前使用(归 PLT)。
*
* <p>固定验证码 {@code sms.mock.fixed-code} 供本地联调与 E2E 使用;生产环境必须留空。</p>
*/
@Slf4j
@Component
public class MockSmsSender implements SmsSender {
private final AtomicReference<String> lastCode = new AtomicReference<>();
private final String fixedCode;
private final boolean exposeCode;
public MockSmsSender(@Value("${sms.mock.fixed-code:}") String fixedCode,
@Value("${sms.mock.expose-code:true}") boolean exposeCode) {
this.fixedCode = fixedCode == null ? "" : fixedCode.trim();
this.exposeCode = exposeCode;
}
@Override
public String send(String phone, String code) {
String delivered = fixedCode.isEmpty() ? code : fixedCode;
if (exposeCode) {
lastCode.set(delivered);
}
log.debug("[MockSmsSender] phone={} code={}", mask(phone), delivered);
return delivered;
}
/** 最近一次发送的验证码(仅本地联调 / 测试使用)。 */
public String lastCode() {
return lastCode.get();
}
/** 固定验证码(为空表示随机生成)。 */
public String fixedCode() {
return fixedCode;
}
private String mask(String phone) {
if (phone == null || phone.length() < 7) {
return "***";
}
return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
}
}

View File

@@ -24,6 +24,27 @@ mybatis-plus:
jwt:
secret: <your-jwt-secret>
expiration: 86400000
# 手机号加密密钥(生产必须注入,禁止入仓)
phone:
crypto:
key: <your-phone-crypto-key>
sms:
mock:
# 固定验证码仅用于本地联调 / E2E;生产留空
fixed-code: ${SMS_MOCK_FIXED_CODE:}
expose-code: true
code:
ttl-seconds: 300
resend-interval-seconds: 60
max-failures: 5
consultant:
displayable-ids: ${CONSULTANT_DISPLAYABLE_IDS:}
seed:
admin:
enabled: true
phone: ${SEED_ADMIN_PHONE:13900000000}
password: ${SEED_ADMIN_PASSWORD:<your-admin-password>}
business-rules:
public-endpoints:
- /api/v1/health
- /api/v1/auth/**

View File

@@ -0,0 +1,63 @@
-- ACC · 账号与个人中心(iteration1)
-- 依据:docs/features/iteration1/ACC-account/plan.md §3
-- 回滚脚本:db/rollback/V20261117__acc_account_rollback.sql
CREATE TABLE account (
id VARCHAR(64) NOT NULL PRIMARY KEY,
phone_hash VARCHAR(64) NOT NULL,
phone_cipher VARCHAR(512) NOT NULL,
roles_json VARCHAR(128) NOT NULL COMMENT 'JSON array e.g. ["USER"]',
status VARCHAR(32) NOT NULL,
phone_verified_at DATETIME(3) NOT NULL,
last_login_at DATETIME(3) NULL,
disabled_reason VARCHAR(200) NULL,
token_version INT NOT NULL DEFAULT 0,
password_hash VARCHAR(255) NULL COMMENT 'ADMIN only',
created_at DATETIME(3) NOT NULL,
updated_at DATETIME(3) NOT NULL,
UNIQUE KEY uk_account_phone_hash (phone_hash)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;
CREATE TABLE user_profile (
account_id VARCHAR(64) NOT NULL PRIMARY KEY,
nickname VARCHAR(30) NOT NULL,
avatar_url VARCHAR(500) NULL,
email VARCHAR(254) NULL,
city_code VARCHAR(20) NULL,
locale VARCHAR(16) NOT NULL DEFAULT 'zh-CN',
updated_at DATETIME(3) NOT NULL,
CONSTRAINT fk_profile_account FOREIGN KEY (account_id) REFERENCES account(id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;
CREATE TABLE favorite_consultant (
id VARCHAR(64) NOT NULL PRIMARY KEY,
account_id VARCHAR(64) NOT NULL,
consultant_id VARCHAR(64) NOT NULL,
created_at DATETIME(3) NOT NULL,
UNIQUE KEY uk_fav_account_consultant (account_id, consultant_id),
KEY idx_fav_account (account_id),
CONSTRAINT fk_fav_account FOREIGN KEY (account_id) REFERENCES account(id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;
CREATE TABLE agreement_consent (
id VARCHAR(64) NOT NULL PRIMARY KEY,
account_id VARCHAR(64) NOT NULL,
agreement_type VARCHAR(32) NOT NULL,
agreement_version VARCHAR(20) NOT NULL,
consented_at DATETIME(3) NOT NULL,
source_ip VARCHAR(45) NOT NULL,
KEY idx_consent_account (account_id),
UNIQUE KEY uk_consent_account_type_ver (account_id, agreement_type, agreement_version),
CONSTRAINT fk_consent_account FOREIGN KEY (account_id) REFERENCES account(id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;
CREATE TABLE sms_verification_code (
id VARCHAR(64) NOT NULL PRIMARY KEY,
phone_hash VARCHAR(64) NOT NULL,
code_hash VARCHAR(64) NOT NULL,
expires_at DATETIME(3) NOT NULL,
fail_count INT NOT NULL DEFAULT 0,
used_at DATETIME(3) NULL,
created_at DATETIME(3) NOT NULL,
KEY idx_sms_phone_created (phone_hash, created_at)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;

View File

@@ -0,0 +1,10 @@
-- 回滚脚本:撤销 V20261117__acc_account.sql
-- 用法:mysql -u<user> -p<pass> <db> < V20261117__acc_account_rollback.sql
-- 说明:ACC 为首个业务迁移,无历史业务数据;回滚即删表。
-- 顺序:先删子表(外键依赖),再删主表。
DROP TABLE IF EXISTS sms_verification_code;
DROP TABLE IF EXISTS agreement_consent;
DROP TABLE IF EXISTS favorite_consultant;
DROP TABLE IF EXISTS user_profile;
DROP TABLE IF EXISTS account;

View File

@@ -1,25 +1,74 @@
package com.consultation;
import com.consultation.config.ResetDbService;
import com.consultation.infrastructure.sms.MockSmsSender;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import java.util.Map;
import static io.restassured.RestAssured.given;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class TestBase {
/** 平台种子管理员(与 src/test/resources/application.yml 的 seed.admin.* 一致)。 */
protected static final String ADMIN_PHONE = "13900000000";
protected static final String ADMIN_PASSWORD = "Admin@12345";
@LocalServerPort
int port;
@Autowired
ResetDbService resetDbService;
@Autowired
MockSmsSender mockSmsSender;
@BeforeEach
void setUp() {
RestAssured.port = port;
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
resetDbService.resetAll();
}
/** 发送验证码并返回 Mock 通道实际送达的验证码。 */
protected String requestSmsCode(String phone) {
given().contentType(ContentType.JSON)
.body(Map.of("phone", phone))
.post("/api/v1/auth/sms/send")
.then().statusCode(204);
return mockSmsSender.lastCode();
}
/** 验证码登录 / 注册,返回 token。 */
protected String loginBySms(String phone) {
String code = requestSmsCode(phone);
return given().contentType(ContentType.JSON)
.body(Map.of("phone", phone, "code", code))
.post("/api/v1/auth/sms/login")
.then().statusCode(200)
.extract().path("token");
}
/** 管理员密码登录,返回 token。 */
protected String loginAdmin() {
return given().contentType(ContentType.JSON)
.body(Map.of("phone", ADMIN_PHONE, "password", ADMIN_PASSWORD))
.post("/api/v1/auth/admin/login")
.then().statusCode(200)
.extract().path("token");
}
/** 当前登录账号的 ID。 */
protected String currentAccountId(String token) {
return given().header("Authorization", "Bearer " + token)
.get("/api/v1/me")
.then().statusCode(200)
.extract().path("account.id");
}
}

View File

@@ -0,0 +1,127 @@
package com.consultation.adapter.rest;
import com.consultation.TestBase;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
class AdminAccountControllerTest extends TestBase {
private static final String PHONE = "13800138000";
@Test
void should_disable_account_and_invalidate_existing_session() {
String userToken = loginBySms(PHONE);
String accountId = currentAccountId(userToken);
String adminToken = loginAdmin();
given().header("Authorization", "Bearer " + adminToken)
.contentType(ContentType.JSON)
.body(Map.of("reason", "违规内容"))
.post("/api/v1/admin/accounts/" + accountId + "/disable")
.then().statusCode(200)
.body("status", equalTo("DISABLED"))
.body("disabledReason", equalTo("违规内容"))
.body("phone", equalTo("138****8000"));
given().header("Authorization", "Bearer " + userToken)
.get("/api/v1/me")
.then().statusCode(401)
.body("errorCode", equalTo("UNAUTHORIZED"));
}
@Test
void should_reject_login_for_disabled_account() {
String userToken = loginBySms(PHONE);
String accountId = currentAccountId(userToken);
String adminToken = loginAdmin();
given().header("Authorization", "Bearer " + adminToken)
.contentType(ContentType.JSON)
.body(Map.of("reason", "违规内容"))
.post("/api/v1/admin/accounts/" + accountId + "/disable")
.then().statusCode(200);
String code = requestSmsCode(PHONE);
given().contentType(ContentType.JSON)
.body(Map.of("phone", PHONE, "code", code))
.post("/api/v1/auth/sms/login")
.then().statusCode(409)
.body("errorCode", equalTo("BUSINESS_CONFLICT"))
.body("errorMessage", startsWith("账号不可用"));
}
@Test
void should_enable_account_again() {
String userToken = loginBySms(PHONE);
String accountId = currentAccountId(userToken);
String adminToken = loginAdmin();
given().header("Authorization", "Bearer " + adminToken)
.contentType(ContentType.JSON)
.body(Map.of("reason", "违规内容"))
.post("/api/v1/admin/accounts/" + accountId + "/disable")
.then().statusCode(200);
given().header("Authorization", "Bearer " + adminToken)
.post("/api/v1/admin/accounts/" + accountId + "/enable")
.then().statusCode(200)
.body("status", equalTo("ACTIVE"));
String newToken = loginBySms(PHONE);
given().header("Authorization", "Bearer " + newToken)
.get("/api/v1/me")
.then().statusCode(200)
.body("account.id", notNullValue());
}
@Test
void should_return_403_when_non_admin_tries_to_disable_account() {
String userToken = loginBySms(PHONE);
String accountId = currentAccountId(userToken);
given().header("Authorization", "Bearer " + userToken)
.contentType(ContentType.JSON)
.body(Map.of("reason", "违规内容"))
.post("/api/v1/admin/accounts/" + accountId + "/disable")
.then().statusCode(403);
}
@Test
void should_return_401_when_admin_endpoint_called_without_token() {
given().contentType(ContentType.JSON)
.body(Map.of("reason", "违规内容"))
.post("/api/v1/admin/accounts/any-id/disable")
.then().statusCode(401);
}
@Test
void should_return_400_when_disable_reason_is_missing() {
String adminToken = loginAdmin();
given().header("Authorization", "Bearer " + adminToken)
.contentType(ContentType.JSON)
.body(Map.of())
.post("/api/v1/admin/accounts/any-id/disable")
.then().statusCode(400)
.body("errorCode", equalTo("VALIDATION_ERROR"));
}
@Test
void should_return_400_when_account_does_not_exist() {
String adminToken = loginAdmin();
given().header("Authorization", "Bearer " + adminToken)
.contentType(ContentType.JSON)
.body(Map.of("reason", "违规内容"))
.post("/api/v1/admin/accounts/not-exist-id/disable")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"));
}
}

View File

@@ -0,0 +1,139 @@
package com.consultation.adapter.rest;
import com.consultation.TestBase;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AuthControllerTest extends TestBase {
private static final String PHONE = "13800138000";
@Test
void should_return_204_when_send_sms_code() {
given().contentType(ContentType.JSON)
.body(Map.of("phone", PHONE))
.post("/api/v1/auth/sms/send")
.then().statusCode(204);
}
@Test
void should_register_new_account_with_user_role_when_sms_login() {
String code = requestSmsCode(PHONE);
given().contentType(ContentType.JSON)
.body(Map.of("phone", PHONE, "code", code, "nickname", "阿宁"))
.post("/api/v1/auth/sms/login")
.then().statusCode(200)
.body("token", notNullValue())
.body("account.id", notNullValue())
.body("account.status", equalTo("ACTIVE"))
.body("account.roles", contains("USER"))
.body("profile.nickname", equalTo("阿宁"));
}
@Test
void should_not_create_duplicate_account_when_login_again() {
String firstToken = loginBySms(PHONE);
String firstAccountId = currentAccountId(firstToken);
String secondToken = loginBySms(PHONE);
assertEquals(firstAccountId, currentAccountId(secondToken));
given().contentType(ContentType.JSON)
.body(Map.of("phone", PHONE))
.post("/api/v1/auth/sms/send")
.then().statusCode(204);
}
@Test
void should_return_400_when_verification_code_is_wrong() {
requestSmsCode(PHONE);
given().contentType(ContentType.JSON)
.body(Map.of("phone", PHONE, "code", "000000"))
.post("/api/v1/auth/sms/login")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"))
.body("errorMessage", startsWith("验证码"));
}
@Test
void should_return_400_when_phone_format_is_invalid() {
given().contentType(ContentType.JSON)
.body(Map.of("phone", "12345", "code", "123456"))
.post("/api/v1/auth/sms/login")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"));
}
@Test
void should_return_400_when_send_sms_code_with_invalid_phone() {
given().contentType(ContentType.JSON)
.body(Map.of("phone", "12345"))
.post("/api/v1/auth/sms/send")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"));
}
@Test
void should_return_400_when_verification_code_is_missing() {
given().contentType(ContentType.JSON)
.body(Map.of("phone", PHONE))
.post("/api/v1/auth/sms/login")
.then().statusCode(400)
.body("errorCode", equalTo("VALIDATION_ERROR"));
}
@Test
void should_login_admin_with_password() {
given().contentType(ContentType.JSON)
.body(Map.of("phone", ADMIN_PHONE, "password", ADMIN_PASSWORD))
.post("/api/v1/auth/admin/login")
.then().statusCode(200)
.body("token", notNullValue())
.body("account.roles", contains("ADMIN"));
}
@Test
void should_return_400_when_admin_password_is_wrong() {
given().contentType(ContentType.JSON)
.body(Map.of("phone", ADMIN_PHONE, "password", "wrong-password"))
.post("/api/v1/auth/admin/login")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"));
}
@Test
void should_return_400_when_admin_account_does_not_exist() {
Map<String, String> body = new HashMap<>();
body.put("phone", "13700137000");
body.put("password", ADMIN_PASSWORD);
given().contentType(ContentType.JSON)
.body(body)
.post("/api/v1/auth/admin/login")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"));
}
@Test
void should_reject_sms_login_for_non_admin_account() {
loginBySms(PHONE);
given().contentType(ContentType.JSON)
.body(Map.of("phone", PHONE, "password", ADMIN_PASSWORD))
.post("/api/v1/auth/admin/login")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"));
}
}

View File

@@ -0,0 +1,197 @@
package com.consultation.adapter.rest;
import com.consultation.TestBase;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
class MeControllerTest extends TestBase {
private static final String PHONE = "13800138000";
private static final String CONSULTANT_ID = "stub-consultant-001";
@Test
void should_return_current_account_and_profile_when_get_me() {
String token = loginBySms(PHONE);
given().header("Authorization", "Bearer " + token)
.get("/api/v1/me")
.then().statusCode(200)
.body("account.id", notNullValue())
.body("account.status", equalTo("ACTIVE"))
.body("account.phone", equalTo(PHONE))
.body("profile.accountId", notNullValue());
}
@Test
void should_return_401_when_get_me_without_token() {
given().get("/api/v1/me")
.then().statusCode(401);
}
@Test
void should_return_401_when_update_profile_without_token() {
given().contentType(ContentType.JSON)
.body(Map.of("nickname", "阿宁"))
.put("/api/v1/me/profile")
.then().statusCode(401);
}
@Test
void should_update_own_profile_and_read_it_back() {
String token = loginBySms(PHONE);
Map<String, String> body = new HashMap<>();
body.put("nickname", "新昵称");
body.put("email", "ning@example.com");
body.put("cityCode", "310000");
body.put("locale", "zh-CN");
given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(body)
.put("/api/v1/me/profile")
.then().statusCode(200)
.body("nickname", equalTo("新昵称"))
.body("email", equalTo("ning@example.com"))
.body("cityCode", equalTo("310000"));
given().header("Authorization", "Bearer " + token)
.get("/api/v1/me")
.then().statusCode(200)
.body("profile.nickname", equalTo("新昵称"))
.body("profile.email", equalTo("ning@example.com"));
}
@Test
void should_return_400_when_nickname_is_too_short() {
String token = loginBySms(PHONE);
given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(Map.of("nickname", "a"))
.put("/api/v1/me/profile")
.then().statusCode(400)
.body("errorCode", equalTo("VALIDATION_ERROR"));
}
@Test
void should_favorite_and_unfavorite_idempotently() {
String token = loginBySms(PHONE);
String favoriteId = given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(Map.of("consultantId", CONSULTANT_ID))
.post("/api/v1/me/favorites")
.then().statusCode(200)
.body("consultantId", equalTo(CONSULTANT_ID))
.extract().path("id");
given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(Map.of("consultantId", CONSULTANT_ID))
.post("/api/v1/me/favorites")
.then().statusCode(200)
.body("id", equalTo(favoriteId));
given().header("Authorization", "Bearer " + token)
.get("/api/v1/me/favorites")
.then().statusCode(200)
.body("$", hasSize(1));
given().header("Authorization", "Bearer " + token)
.delete("/api/v1/me/favorites/" + CONSULTANT_ID)
.then().statusCode(204);
given().header("Authorization", "Bearer " + token)
.get("/api/v1/me/favorites")
.then().statusCode(200)
.body("$", hasSize(0));
given().header("Authorization", "Bearer " + token)
.delete("/api/v1/me/favorites/" + CONSULTANT_ID)
.then().statusCode(204);
}
@Test
void should_return_400_when_favorite_unknown_consultant() {
String token = loginBySms(PHONE);
given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(Map.of("consultantId", "not-displayable"))
.post("/api/v1/me/favorites")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"));
}
@Test
void should_record_agreement_consent_idempotently() {
String token = loginBySms(PHONE);
String consentId = given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(Map.of("agreementType", "service", "agreementVersion", "v1"))
.post("/api/v1/me/agreements")
.then().statusCode(200)
.body("agreementType", equalTo("service"))
.body("agreementVersion", equalTo("v1"))
.body("consentedAt", notNullValue())
.body("sourceIp", notNullValue())
.extract().path("id");
given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(Map.of("agreementType", "privacy", "agreementVersion", "v1"))
.post("/api/v1/me/agreements")
.then().statusCode(200)
.body("agreementType", equalTo("privacy"));
given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(Map.of("agreementType", "service", "agreementVersion", "v1"))
.post("/api/v1/me/agreements")
.then().statusCode(200)
.body("id", equalTo(consentId));
given().header("Authorization", "Bearer " + token)
.get("/api/v1/me/agreements")
.then().statusCode(200)
.body("$", hasSize(2));
}
@Test
void should_return_400_when_agreement_type_is_invalid() {
String token = loginBySms(PHONE);
given().header("Authorization", "Bearer " + token)
.contentType(ContentType.JSON)
.body(Map.of("agreementType", "unknown", "agreementVersion", "v1"))
.post("/api/v1/me/agreements")
.then().statusCode(400)
.body("errorCode", equalTo("PARAM_ERROR"));
}
@Test
void should_keep_favorites_private_between_accounts() {
String firstToken = loginBySms(PHONE);
given().header("Authorization", "Bearer " + firstToken)
.contentType(ContentType.JSON)
.body(Map.of("consultantId", CONSULTANT_ID))
.post("/api/v1/me/favorites")
.then().statusCode(200);
String secondToken = loginBySms("13900139000");
given().header("Authorization", "Bearer " + secondToken)
.get("/api/v1/me/favorites")
.then().statusCode(200)
.body("$", hasSize(0));
}
}

View File

@@ -1,5 +1,6 @@
package com.consultation.config;
import com.consultation.infrastructure.config.AccountSeedInitializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -13,13 +14,15 @@ public class ResetDbService {
private final JdbcTemplate jdbc;
private final DataSource dataSource;
private final AccountSeedInitializer accountSeedInitializer;
@Value("classpath:data.sql")
private Resource dataScript;
public ResetDbService(JdbcTemplate jdbc, DataSource dataSource) {
public ResetDbService(JdbcTemplate jdbc, DataSource dataSource, AccountSeedInitializer accountSeedInitializer) {
this.jdbc = jdbc;
this.dataSource = dataSource;
this.accountSeedInitializer = accountSeedInitializer;
}
public void resetAll() {
@@ -33,6 +36,8 @@ public class ResetDbService {
}
jdbc.execute("SET FOREIGN_KEY_CHECKS = 1");
reSeed();
// 管理员账号含环境相关密文,清库后需重建
accountSeedInitializer.ensureAdminAccount();
}
private void reSeed() {

View File

@@ -0,0 +1,106 @@
package com.consultation.domain.aggregate;
import com.consultation.domain.vo.AccountRole;
import com.consultation.domain.vo.AccountStatus;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class AccountTest {
private static final Instant NOW = Instant.parse("2026-11-17T10:00:00Z");
private Account activeAccount() {
return Account.registerByPhone("acc-1", "hash", "cipher", NOW);
}
@Test
void should_register_account_with_user_role_and_active_status() {
Account account = activeAccount();
assertEquals(AccountStatus.ACTIVE, account.getStatus());
assertEquals(Set.of(AccountRole.USER), account.getRoles());
assertEquals(0, account.getTokenVersion());
assertTrue(account.hasRole(AccountRole.USER));
}
@Test
void should_disable_account_and_bump_token_version() {
Account disabled = activeAccount().disable("违规内容", NOW);
assertEquals(AccountStatus.DISABLED, disabled.getStatus());
assertEquals("违规内容", disabled.getDisabledReason());
assertEquals(1, disabled.getTokenVersion());
}
@Test
void should_keep_disable_idempotent_without_bumping_token_version() {
Account once = activeAccount().disable("违规内容", NOW);
Account twice = once.disable("违规内容", NOW);
assertEquals(once, twice);
assertEquals(1, twice.getTokenVersion());
}
@Test
void should_enable_account_and_bump_token_version() {
Account disabled = activeAccount().disable("违规内容", NOW);
Account enabled = disabled.enable(NOW);
assertEquals(AccountStatus.ACTIVE, enabled.getStatus());
assertEquals(null, enabled.getDisabledReason());
assertEquals(2, enabled.getTokenVersion());
}
@Test
void should_keep_enable_idempotent_when_already_active() {
Account enabled = activeAccount().enable(NOW);
assertEquals(AccountStatus.ACTIVE, enabled.getStatus());
assertEquals(0, enabled.getTokenVersion());
}
@Test
void should_grant_consultant_role_idempotently() {
Account granted = activeAccount().grantConsultantRole(NOW);
Account grantedAgain = granted.grantConsultantRole(NOW);
assertTrue(granted.hasRole(AccountRole.CONSULTANT));
assertTrue(granted.hasRole(AccountRole.USER));
assertEquals(granted, grantedAgain);
}
@Test
void should_reject_disabled_account_when_assert_usable() {
Account disabled = activeAccount().disable("违规内容", NOW);
IllegalStateException error = assertThrows(IllegalStateException.class, disabled::assertUsable);
assertTrue(error.getMessage().contains("账号不可用"));
assertTrue(error.getMessage().contains("违规内容"));
}
@Test
void should_touch_login_time() {
Instant later = NOW.plusSeconds(60);
Account touched = activeAccount().touchLogin(later);
assertEquals(later, touched.getLastLoginAt());
assertNotEquals(activeAccount().getLastLoginAt(), touched.getLastLoginAt());
}
@Test
void should_create_admin_account_without_user_role() {
Account admin = Account.createAdmin("acc-admin", "hash", "cipher", "pwd", NOW);
assertTrue(admin.hasRole(AccountRole.ADMIN));
assertFalse(admin.hasRole(AccountRole.USER));
assertEquals("pwd", admin.getPasswordHash());
}
}

View File

@@ -0,0 +1,26 @@
package com.consultation.domain.service;
import com.consultation.domain.aggregate.SmsVerificationCode;
import com.consultation.domain.repository.SmsVerificationCodeRepository;
import java.util.Optional;
class FakeSmsVerificationCodeRepository implements SmsVerificationCodeRepository {
private SmsVerificationCode latest;
@Override
public Optional<SmsVerificationCode> findLatestByPhoneHash(String phoneHash) {
return Optional.ofNullable(latest);
}
@Override
public SmsVerificationCode save(SmsVerificationCode code) {
this.latest = code;
return code;
}
SmsVerificationCode latest() {
return latest;
}
}

View File

@@ -0,0 +1,160 @@
package com.consultation.domain.service;
import com.consultation.domain.aggregate.SmsVerificationCode;
import com.consultation.domain.service.PhoneCrypto;
import com.consultation.domain.service.SmsSender;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SmsCodeServiceTest {
private static final Instant NOW = Instant.parse("2026-11-17T10:00:00Z");
private static final String PHONE = "13800138000";
private static final String PHONE_HASH = "phone-hash";
private final FakeSmsVerificationCodeRepository repository = new FakeSmsVerificationCodeRepository();
private final CapturingSmsSender sender = new CapturingSmsSender();
private final PhoneCrypto phoneCrypto = new PlainHashCrypto();
private SmsCodeService service(Duration ttl, Duration resendInterval) {
return new SmsCodeService(repository, sender, phoneCrypto, ttl, resendInterval, 5,
Clock.fixed(NOW, ZoneOffset.UTC));
}
@Test
void should_issue_code_and_store_hashed_value() {
service(Duration.ofMinutes(5), Duration.ofSeconds(60)).issue(PHONE, PHONE_HASH);
assertNotNull(sender.sentCode());
assertNotNull(repository.latest());
assertTrue(repository.latest().getCodeHash().contains(sender.sentCode()));
assertEquals(0, repository.latest().getFailCount());
assertEquals(NOW.plus(Duration.ofMinutes(5)), repository.latest().getExpiresAt());
}
@Test
void should_reject_resend_within_interval() {
SmsCodeService service = service(Duration.ofMinutes(5), Duration.ofSeconds(60));
service.issue(PHONE, PHONE_HASH);
IllegalStateException error = assertThrows(IllegalStateException.class,
() -> service.issue(PHONE, PHONE_HASH));
assertTrue(error.getMessage().contains("频繁"));
}
@Test
void should_allow_resend_after_interval() {
SmsCodeService service = service(Duration.ofMinutes(5), Duration.ZERO);
service.issue(PHONE, PHONE_HASH);
service.issue(PHONE, PHONE_HASH);
assertEquals(2, sender.sendCount);
}
@Test
void should_verify_code_with_correct_value() {
SmsCodeService service = service(Duration.ofMinutes(5), Duration.ZERO);
service.issue(PHONE, PHONE_HASH);
service.verify(PHONE_HASH, sender.sentCode());
}
@Test
void should_invalidate_code_after_five_failures() {
SmsCodeService service = service(Duration.ofMinutes(5), Duration.ZERO);
service.issue(PHONE, PHONE_HASH);
for (int i = 0; i < 4; i++) {
IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
() -> service.verify(PHONE_HASH, "000000"));
assertTrue(error.getMessage().contains("验证码错误"));
}
IllegalArgumentException last = assertThrows(IllegalArgumentException.class,
() -> service.verify(PHONE_HASH, "000000"));
assertTrue(last.getMessage().contains("作废"));
assertEquals(5, repository.latest().getFailCount());
assertNotNull(repository.latest().getUsedAt());
}
@Test
void should_reject_expired_code() {
SmsCodeService service = service(Duration.ofMinutes(5), Duration.ZERO);
service.issue(PHONE, PHONE_HASH);
SmsVerificationCode expired = repository.latest().toBuilder()
.expiresAt(NOW.minusSeconds(1))
.build();
repository.save(expired);
IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
() -> service.verify(PHONE_HASH, sender.sentCode()));
assertTrue(error.getMessage().contains("过期"));
}
@Test
void should_reject_code_that_does_not_exist() {
SmsCodeService service = service(Duration.ofMinutes(5), Duration.ZERO);
IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
() -> service.verify(PHONE_HASH, "123456"));
assertTrue(error.getMessage().contains("不存在"));
}
@Test
void should_reject_used_code() {
SmsCodeService service = service(Duration.ofMinutes(5), Duration.ZERO);
service.issue(PHONE, PHONE_HASH);
service.verify(PHONE_HASH, sender.sentCode());
IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
() -> service.verify(PHONE_HASH, sender.sentCode()));
assertTrue(error.getMessage().contains("已使用"));
}
/**
* 记录发送内容的短信通道桩。
*/
static class CapturingSmsSender implements SmsSender {
private String sentCode;
private int sendCount;
@Override
public String send(String phone, String code) {
this.sentCode = code;
this.sendCount++;
return code;
}
String sentCode() {
return sentCode;
}
}
/**
* 明文摘要桩:便于断言。
*/
static class PlainHashCrypto implements PhoneCrypto {
@Override
public String hash(String plaintext) {
return plaintext;
}
@Override
public String encrypt(String plaintext) {
return plaintext;
}
@Override
public String decrypt(String ciphertext) {
return ciphertext;
}
}
}

View File

@@ -0,0 +1,27 @@
package com.consultation.domain.vo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PhoneNumberTest {
@Test
void should_normalize_phone_with_spaces_and_dashes() {
assertEquals("13800138000", PhoneNumber.of(" 138-0013 8000 ").value());
}
@Test
void should_reject_invalid_phone_format() {
assertThrows(IllegalArgumentException.class, () -> PhoneNumber.of("12345"));
assertThrows(IllegalArgumentException.class, () -> PhoneNumber.of("23800138000"));
assertThrows(IllegalArgumentException.class, () -> PhoneNumber.of(""));
assertThrows(IllegalArgumentException.class, () -> PhoneNumber.of(null));
}
@Test
void should_keep_same_value_after_normalization() {
assertEquals(PhoneNumber.of("13800138000").value(), PhoneNumber.of("138 0013 8000").value());
}
}

View File

@@ -14,6 +14,26 @@ spring:
jwt:
secret: test-secret-key-for-mysql-tests-only
expiration: 86400000
phone:
crypto:
key: test-phone-crypto-key-for-local-tests
sms:
mock:
fixed-code: "123456"
expose-code: true
code:
ttl-seconds: 300
# 测试环境放开重发间隔限制,便于连续发码
resend-interval-seconds: 0
max-failures: 5
consultant:
displayable-ids: stub-consultant-001
seed:
admin:
enabled: true
phone: "13900000000"
password: "Admin@12345"
business-rules:
public-endpoints:
- /api/v1/health
- /api/v1/auth/**

View File

@@ -1 +1,10 @@
-- Skeleton: no seed data.
-- 测试种子数据
-- 平台管理员账号(手机号 13900000000 / 密码 Admin@12345)由
-- com.consultation.infrastructure.config.AccountSeedInitializer 在运行时创建:
-- 管理员手机号需要用当前环境的加密密钥落密文,无法固化为静态 SQL。
-- 每个用例前由 ResetDbService 清库并重建该管理员。
--
-- 「可展示咨询师」白名单(stub-consultant-001)配置在 application.yml 的
-- consultant.displayable-ids,无需数据库行。
SELECT 1;

View File

@@ -1 +1,62 @@
-- Skeleton: no business tables. Recreate via Flyway when implementing iteration1 features.
-- 测试用库表结构(与 Flyway V20261117__acc_account.sql 保持一致)
-- Flyway 在测试中禁用,改用本脚本初始化。
CREATE TABLE IF NOT EXISTS account (
id VARCHAR(64) NOT NULL PRIMARY KEY,
phone_hash VARCHAR(64) NOT NULL,
phone_cipher VARCHAR(512) NOT NULL,
roles_json VARCHAR(128) NOT NULL COMMENT 'JSON array e.g. ["USER"]',
status VARCHAR(32) NOT NULL,
phone_verified_at DATETIME(3) NOT NULL,
last_login_at DATETIME(3) NULL,
disabled_reason VARCHAR(200) NULL,
token_version INT NOT NULL DEFAULT 0,
password_hash VARCHAR(255) NULL COMMENT 'ADMIN only',
created_at DATETIME(3) NOT NULL,
updated_at DATETIME(3) NOT NULL,
UNIQUE KEY uk_account_phone_hash (phone_hash)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;
CREATE TABLE IF NOT EXISTS user_profile (
account_id VARCHAR(64) NOT NULL PRIMARY KEY,
nickname VARCHAR(30) NOT NULL,
avatar_url VARCHAR(500) NULL,
email VARCHAR(254) NULL,
city_code VARCHAR(20) NULL,
locale VARCHAR(16) NOT NULL DEFAULT 'zh-CN',
updated_at DATETIME(3) NOT NULL,
CONSTRAINT fk_profile_account FOREIGN KEY (account_id) REFERENCES account(id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;
CREATE TABLE IF NOT EXISTS favorite_consultant (
id VARCHAR(64) NOT NULL PRIMARY KEY,
account_id VARCHAR(64) NOT NULL,
consultant_id VARCHAR(64) NOT NULL,
created_at DATETIME(3) NOT NULL,
UNIQUE KEY uk_fav_account_consultant (account_id, consultant_id),
KEY idx_fav_account (account_id),
CONSTRAINT fk_fav_account FOREIGN KEY (account_id) REFERENCES account(id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;
CREATE TABLE IF NOT EXISTS agreement_consent (
id VARCHAR(64) NOT NULL PRIMARY KEY,
account_id VARCHAR(64) NOT NULL,
agreement_type VARCHAR(32) NOT NULL,
agreement_version VARCHAR(20) NOT NULL,
consented_at DATETIME(3) NOT NULL,
source_ip VARCHAR(45) NOT NULL,
KEY idx_consent_account (account_id),
UNIQUE KEY uk_consent_account_type_ver (account_id, agreement_type, agreement_version),
CONSTRAINT fk_consent_account FOREIGN KEY (account_id) REFERENCES account(id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;
CREATE TABLE IF NOT EXISTS sms_verification_code (
id VARCHAR(64) NOT NULL PRIMARY KEY,
phone_hash VARCHAR(64) NOT NULL,
code_hash VARCHAR(64) NOT NULL,
expires_at DATETIME(3) NOT NULL,
fail_count INT NOT NULL DEFAULT 0,
used_at DATETIME(3) NULL,
created_at DATETIME(3) NOT NULL,
KEY idx_sms_phone_created (phone_hash, created_at)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin;

View File

@@ -0,0 +1,13 @@
/**
* 当前生效的协议版本。
* 协议中心(PLT)上线后改为后端下发。
*/
export const AGREEMENT_VERSIONS: Record<string, string> = {
service: 'v1',
privacy: 'v1',
}
export const AGREEMENT_LABELS: Record<string, string> = {
service: '服务协议',
privacy: '隐私政策',
}

View File

@@ -0,0 +1,82 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
const auth = useAuthStore()
const router = useRouter()
const displayName = computed(() => auth.profile?.nickname || auth.user?.phone || '未登录')
function handleLogout() {
auth.logout()
router.push('/user/login')
}
</script>
<template>
<div class="layout">
<header class="layout__header">
<div class="layout__brand">咨询预约平台</div>
<nav class="layout__nav">
<router-link to="/">首页</router-link>
<router-link to="/user/profile">个人中心</router-link>
</nav>
<div class="layout__user">
<template v-if="auth.isLoggedIn">
<span class="layout__name">{{ displayName }}</span>
<el-button link type="primary" @click="handleLogout">退出</el-button>
</template>
<router-link v-else to="/user/login">登录 / 注册</router-link>
</div>
</header>
<main class="layout__main">
<slot />
</main>
</div>
</template>
<style scoped>
.layout {
min-height: 100vh;
background: #f5f7fa;
}
.layout__header {
display: flex;
align-items: center;
gap: 24px;
padding: 0 24px;
height: 56px;
background: #fff;
border-bottom: 1px solid #ebeef5;
}
.layout__brand {
font-weight: 600;
font-size: 18px;
}
.layout__nav {
display: flex;
gap: 16px;
flex: 1;
}
.layout__nav a {
color: #606266;
text-decoration: none;
}
.layout__nav a.router-link-active {
color: #409eff;
}
.layout__user {
display: flex;
align-items: center;
gap: 8px;
}
.layout__name {
color: #606266;
}
.layout__main {
max-width: 1080px;
margin: 0 auto;
padding: 24px;
}
</style>

View File

@@ -1,6 +1,7 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'
@@ -9,5 +10,6 @@ import './assets/main.css'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(ElementPlus)
// 统一中文语言包(弹窗按钮等文案随 locale 走 zh-cn)
app.use(ElementPlus, { locale: zhCn })
app.mount('#app')

View File

@@ -4,7 +4,25 @@ const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', name: 'home', component: () => import('@/views/home/HomePage.vue') },
{
path: '/user/login',
name: 'user-login',
component: () => import('@/views/auth/Login.vue'),
},
{
path: '/user/profile',
name: 'user-profile',
component: () => import('@/views/user/Profile.vue'),
meta: { requiresAuth: true },
},
],
})
router.beforeEach(to => {
const token = localStorage.getItem('token')
if (to.meta.requiresAuth && !token) {
return { path: '/user/login' }
}
})
export default router

View File

@@ -0,0 +1,11 @@
import http, { unwrap } from '@/utils/request'
import type { AgreementConsent } from '@/types'
/** 协议同意相关接口(ACC)。 */
export const agreementService = {
list: () => unwrap(http.get<AgreementConsent[]>('/me/agreements')),
/** 记录协议同意(按类型 + 版本幂等) */
consent: (agreementType: string, agreementVersion: string) =>
unwrap(http.post<AgreementConsent>('/me/agreements', { agreementType, agreementVersion })),
}

Some files were not shown because too many files have changed in this diff Show More