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:
@@ -1,11 +1,28 @@
|
||||
---
|
||||
name: dev-build
|
||||
description: 遵循四层 DDD 架构实现功能,并维护与 plan 同目录的细化进度文件。当为 example-project 编写后端或前端代码时使用。
|
||||
description: 全栈实现编排:按 Plan 写前后端、维护细化进度,并依次调用自测、界面评审、代码评审;失败则修 bug 回环。当 Plan 已确认、进入实现时使用。
|
||||
---
|
||||
|
||||
# 开发:构建实现
|
||||
# 开发:构建实现(全栈编排)
|
||||
|
||||
按照 `AGENTS.md` 中的架构约定编写代码。Plan 已确认后方可动手。
|
||||
`dev-build` 是 **全栈实现编排器**,不是「只写代码」。Plan 已确认后方可动手。
|
||||
|
||||
按 `AGENTS.md` 架构约定实现,并 **依次执行** 下列依赖 skill(读其已安装正文并照做,不要跳步):
|
||||
|
||||
```
|
||||
① 实现(本 skill)→ ② dev-self-test → ③ dev-ui-review(有 UI 时)→ ④ dev-code-review
|
||||
↑____________ 失败 / 评审问题:修 bug 后从对应步骤重跑 _____________↓
|
||||
```
|
||||
|
||||
| 阶段 | 调用 | 目的 |
|
||||
|---|---|---|
|
||||
| 实现 | 本 skill | 前后端按 Plan + progress 落地 |
|
||||
| 自测 | `dev-self-test` | 单元/集成/构建/E2E 自测;失败则改实现再测 |
|
||||
| 界面 | `dev-ui-review` | chrome-devtools-mcp 实机看结构/视觉/交互/控制台/网络 |
|
||||
| 评审 | `dev-code-review` | 对照 `AGENTS` / standards / facts 自查 diff |
|
||||
| 调试(按需) | `dev-debug` | 自测或 UI 卡住时用 chrome-mcp 查根因,再回到自测/实现 |
|
||||
|
||||
**硬性**:未跑通自测不得宣称 build 完成;有前端改动时不得跳过 `dev-ui-review`;`dev-code-review` 通过前不得进入 `dev-create-mr`。
|
||||
|
||||
## 进度文件(硬性)
|
||||
|
||||
@@ -19,14 +36,18 @@ description: 遵循四层 DDD 架构实现功能,并维护与 plan 同目录
|
||||
### 开工前
|
||||
|
||||
1. 读 plan 的 **「实施步骤(粗)」**(约 5~10 条)
|
||||
2. 对照 §11 修改清单、§13 验证步骤、§15 事实/design 更新,把 **每条粗步骤细化为可勾选细项**(文件/模块/测试级)
|
||||
3. 创建或重置对应 `*-progress.md`(总状态:进行中)
|
||||
2. 对照修改清单、验证步骤、事实/design 更新,把粗步骤 **细化** 为可勾选细项
|
||||
3. 在 checklist **末尾追加编排阶段**(若尚无):
|
||||
|
||||
细项示例(粗步骤「领域与持久化」):
|
||||
```markdown
|
||||
### 编排
|
||||
- [ ] 实现(前后端)
|
||||
- [ ] dev-self-test
|
||||
- [ ] dev-ui-review(无 UI 改动可注明跳过)
|
||||
- [ ] dev-code-review
|
||||
```
|
||||
|
||||
- 聚合 / 实体
|
||||
- 仓储接口与实现
|
||||
- 迁移 / DDL
|
||||
4. 创建或重置对应 `*-progress.md`(总状态:进行中)
|
||||
|
||||
**不要**把细项回写进 plan(plan 定稿不改)。
|
||||
|
||||
@@ -45,8 +66,11 @@ description: 遵循四层 DDD 架构实现功能,并维护与 plan 同目录
|
||||
- [x] 细项 A
|
||||
- [ ] 细项 B ← 进行中
|
||||
|
||||
### 2. …
|
||||
- [ ] …
|
||||
### 编排
|
||||
- [ ] 实现(前后端)
|
||||
- [ ] dev-self-test
|
||||
- [ ] dev-ui-review
|
||||
- [ ] dev-code-review
|
||||
|
||||
## 备注
|
||||
|
||||
@@ -55,47 +79,76 @@ description: 遵循四层 DDD 架构实现功能,并维护与 plan 同目录
|
||||
|
||||
### 执行中
|
||||
|
||||
- 每完成一个细项:**立刻**勾选并刷新「更新」时间
|
||||
- 当前细项可标 `← 进行中`
|
||||
- 受阻:总状态改为「受阻」,原因写入备注
|
||||
- 全部完成后:总状态改为「已完成」
|
||||
- 每完成一个细项或编排阶段:**立刻**勾选并刷新「更新」时间
|
||||
- 当前项可标 `← 进行中`;受阻写备注并改总状态
|
||||
- 全部完成后(含编排四步):总状态「已完成」
|
||||
|
||||
## 后端
|
||||
## ① 实现
|
||||
|
||||
### 后端
|
||||
|
||||
- `containers/backend/adapter/rest/` — Controller:仅做协议转换,不含业务逻辑
|
||||
- `containers/backend/application/service/` — AppService:用例编排,`@Transactional`
|
||||
- `containers/backend/domain/` — 聚合、值对象、领域服务:业务不变量
|
||||
- `containers/backend/infrastructure/` — 持久化、安全、配置
|
||||
|
||||
层依赖关系:adapter → application → domain ← infrastructure
|
||||
层依赖:adapter → application → domain ← infrastructure
|
||||
|
||||
## 前端
|
||||
### 前端
|
||||
|
||||
- Vue 3 Composition API + `<script setup>`
|
||||
- Pinia store 管理认证状态,位于 `containers/frontend/src/stores/auth.ts`
|
||||
- 视图位于 `containers/frontend/src/views/user/` 或 `containers/frontend/src/views/admin/`
|
||||
- Axios 拦截器处理 JWT 和 401 跳转
|
||||
|
||||
## 验证
|
||||
实现细项勾完后,进入 ②。
|
||||
|
||||
## ② 自测 — 调用 `dev-self-test`
|
||||
|
||||
完整按已安装的 `dev-self-test` skill 执行(由快到慢:后端单测 → 集成 → 前端构建/单测 → E2E 自测)。
|
||||
|
||||
- 失败:按该 skill 的失败分类改 **实现**(或测试隔离),**禁止**改断言迁就实现、删用例、改 QA 用例
|
||||
- 环境/浏览器深层问题:可切 `dev-debug`(chrome-devtools-mcp),修好后回到 `dev-self-test`
|
||||
- 自测绿:勾选 progress「dev-self-test」,进入 ③
|
||||
|
||||
快速命令(细节以 `dev-self-test` 为准):
|
||||
|
||||
```bash
|
||||
cd containers/backend && mvn test
|
||||
cd containers/frontend && npm run build
|
||||
```
|
||||
|
||||
## ③ 界面评审 — 调用 `dev-ui-review`(有 UI 时)
|
||||
|
||||
本次若改了前端页面 / 交互:完整按 `dev-ui-review`(chrome-devtools-mcp:结构 → 视觉 → 控制台/网络 → 交互)。
|
||||
|
||||
- 无 UI 改动:在 progress 注明跳过原因并勾选
|
||||
- 发现问题:修代码 → ② 自测 → 再 ③
|
||||
- 通过:勾选「dev-ui-review」
|
||||
|
||||
## ④ 代码评审 — 调用 `dev-code-review`
|
||||
|
||||
完整按 `dev-code-review`(先读 `AGENTS.md` / `docs/standards` / `docs/facts`,再看 diff)。
|
||||
|
||||
- 有必须修的问题:改代码 → ②(必要时 ③)→ 再 ④
|
||||
- 通过:勾选「dev-code-review」
|
||||
|
||||
## 文档同步
|
||||
|
||||
实现完成后检查是否需要更新:
|
||||
编排通过后检查是否需要更新:
|
||||
|
||||
- `docs/facts/api.yaml` — API 变更
|
||||
- `docs/facts/db-schema.md` — 数据库变更
|
||||
- `docs/facts/tech-topic/businessrule.md` — 业务规则变更
|
||||
- `docs/facts/tech-topic/data-dict.md` — 数据字典变更
|
||||
|
||||
事实校准可用 `ba-gen-facts`(不阻塞 build 闭环,但合并前应处理)。
|
||||
|
||||
## 自检清单
|
||||
|
||||
- [ ] 已按 plan 文件名写好同目录 `*-progress.md`,粗步骤已细化
|
||||
- [ ] 执行过程中进度文件持续更新,结束时总状态正确
|
||||
- [ ] 代码符合四层依赖,未在 adapter 写业务逻辑
|
||||
- [ ] 相关测试已跑过(或已记入 progress 备注说明为何跳过)
|
||||
- [ ] progress 已写,粗步骤已细化,编排四步已勾选(或注明合法跳过)
|
||||
- [ ] `dev-self-test` 已按 skill 跑通
|
||||
- [ ] 有 UI 时 `dev-ui-review` 已按 skill 跑通;否则已注明跳过
|
||||
- [ ] `dev-code-review` 已按 skill 自查通过
|
||||
- [ ] 代码符合四层依赖;未在 adapter 写业务逻辑
|
||||
- [ ] 需要的事实文档已同步或已列入后续任务
|
||||
|
||||
@@ -5,6 +5,8 @@ description: 按项目规范做代码评审。当提交前自查、或评审别
|
||||
|
||||
# Dev:代码评审
|
||||
|
||||
通常由 **`dev-build` 编排调用**做提交前自查;也可单独用来评审别人的 PR/MR。
|
||||
|
||||
评审的标准来自项目自己的规范,不来自评审者的口味。
|
||||
|
||||
## 先读规范,再看代码
|
||||
|
||||
@@ -5,6 +5,8 @@ description: 运行并修复开发自测(后端单元/集成测试、前端构
|
||||
|
||||
# Dev:开发自测
|
||||
|
||||
通常由 **`dev-build` 编排调用**;也可在实现后单独触发。
|
||||
|
||||
**自测**验证"代码按 Plan 的设计工作"。它 **不是** QA 测试,不能替代验收 —— 详见项目 `AGENTS.md` §10。
|
||||
|
||||
| | 开发自测 | QA 测试 |
|
||||
|
||||
@@ -5,6 +5,8 @@ description: 用 chrome-devtools-mcp 做界面与交互评审。当前端界面
|
||||
|
||||
# Dev:界面评审
|
||||
|
||||
通常由 **`dev-build` 编排调用**(有前端改动时);也可单独触发。
|
||||
|
||||
界面评审 **必须实机看**,不能只读代码。工具:chrome-devtools-mcp(配置在 `.mcp.json`)。
|
||||
|
||||
## 准备
|
||||
|
||||
106
example-project/.agents/skills/overnight-runner/SKILL.md
Normal file
106
example-project/.agents/skills/overnight-runner/SKILL.md
Normal file
@@ -0,0 +1,106 @@
|
||||
---
|
||||
name: overnight-runner
|
||||
description: 启动 overnight-runner 分屏面板,把队列里的 plan 交给 coding agent 跑(多队列、看门狗重试、有人值守决策窗口 / 无人值守默认决策)。当用户说"跑一晚上"、"夜间跑这些 plan"、"启动 overnight runner"、"无人值守跑任务"、"跑一条新队列"时使用。
|
||||
---
|
||||
|
||||
# overnight-runner
|
||||
|
||||
把一串 **已确认的 plan** 交给 coding agent 无人值守地跑:左边任务队列,右边 agent 实时输出。
|
||||
|
||||
**硬性**:只跑已人工确认的 plan;本 skill **不做** Plan / HLD 闸门本身。
|
||||
|
||||
## 前置
|
||||
|
||||
1. 项目里已有 `.overnight-runner/`(含启动脚本与配置)。没有则先安装:
|
||||
|
||||
```bash
|
||||
../overnight-runner/scripts/install.sh .
|
||||
```
|
||||
|
||||
2. Plan 路径相对项目根,通常在 `docs/features/<迭代>/<CODE>-<slug>/plan.md` 或 `docs/features/_chores/plan-{slug}.md`。
|
||||
|
||||
## 常用命令
|
||||
|
||||
```bash
|
||||
OR=.overnight-runner/overnight-runner
|
||||
|
||||
$OR init
|
||||
$OR add docs/features/<迭代>/<CODE>-<slug>/plan.md
|
||||
$OR add docs/features/<迭代>/<CODE>-<slug>/plan.md --role DEV --priority 10
|
||||
$OR list
|
||||
$OR status
|
||||
$OR queues
|
||||
$OR run # 分屏面板
|
||||
$OR run --headless # 无 TTY / CI(强制 unattended)
|
||||
$OR run --mode unattended # 临时无人值守
|
||||
$OR run --headless --retry-failed
|
||||
$OR decisions
|
||||
```
|
||||
|
||||
多队列(`--queue <名>`,默认 `default`):
|
||||
|
||||
```bash
|
||||
$OR --queue alice add docs/features/<迭代>/<CODE>-<slug>/plan.md
|
||||
$OR --queue alice run
|
||||
```
|
||||
|
||||
同一队列不能并行两个 runner(`.lock`,冲突时退出码 2)。
|
||||
|
||||
## 决策模式
|
||||
|
||||
| | `attended` | `unattended` |
|
||||
|---|---|---|
|
||||
| agent 提问 | 打断,TUI 决策窗口 | 不打断,规则/兜底 |
|
||||
| 记录 source | `human` / `timeout` | `rule` / `fallback` |
|
||||
|
||||
配置:`.overnight-runner/overnight-runner.yaml` → `runner.decision.mode`。
|
||||
`--headless` **强制** unattended。
|
||||
|
||||
## 面板按键
|
||||
|
||||
| 键 | 作用 |
|
||||
|---|---|
|
||||
| `↑` `↓` | 选任务 |
|
||||
| `a` | 追加 plan |
|
||||
| `r` | 重置为待跑 |
|
||||
| `p` | 暂停 / 恢复 |
|
||||
| `d` | 移除 |
|
||||
| `Enter` | 看完整日志 |
|
||||
| `Esc` | 回实时输出 |
|
||||
| `q` | 退出 |
|
||||
|
||||
决策窗口:`Enter` 提交 · `Esc` 兜底 · `Ctrl-C` 退出。
|
||||
|
||||
## 配置要点
|
||||
|
||||
- 队列:`.overnight-runner/queue/<名>/queue.yaml`(`plan` 用相对项目根路径)
|
||||
- 运行:`.overnight-runner/overnight-runner.yaml`(agent 命令、看门狗、决策超时)
|
||||
- 项目决策:`.overnight-runner/project.yaml`(`decisions` 规则 + `onUnknownDecision`)
|
||||
- 决策记录:`.overnight-runner/queue/<名>/decisions.jsonl`(回溯用)
|
||||
|
||||
提交:`queue.yaml` / `project.yaml` / `overnight-runner.yaml` / `decisions.jsonl`。
|
||||
不提交:`state.json`、`logs/`、`.lock`。
|
||||
|
||||
## agent 契约(stdout)
|
||||
|
||||
| 输出 | 含义 |
|
||||
|---|---|
|
||||
| `DECISION: <问题> → <决策>` | 记录决策 |
|
||||
| `QUESTION: <问题>` | 待决(规则或人答) |
|
||||
| `DONE: <总结>` | 完成 |
|
||||
| `BLOCKED: <原因>` | 阻塞 |
|
||||
|
||||
## 怎么做(本 skill)
|
||||
|
||||
1. 确认目标 plan 已人工确认,路径相对 `.`
|
||||
2. 若缺 `.overnight-runner/`,先跑安装命令
|
||||
3. `add` 进合适队列(或改 `queue.yaml`)
|
||||
4. 按场景选 `run` / `run --mode unattended` / `run --headless`
|
||||
5. 结束后用 `decisions` / `decisions.jsonl` 回溯替你做的决定
|
||||
|
||||
## 自检
|
||||
|
||||
- [ ] 只加入了已确认的 plan
|
||||
- [ ] 队列 / 模式选择正确(白天 attended,夜里或 CI 用 unattended / headless)
|
||||
- [ ] 需要的决策规则已在 `project.yaml`
|
||||
- [ ] 运行后看过决策记录或失败任务状态
|
||||
@@ -4,3 +4,14 @@
|
||||
{"at": "2026-11-06T16:41:40+08:00", "task_id": "20261106-20261106-businessrule-datadictionary-api-tests", "question": "flaky-test(测试偶发失败)", "answer": "未观察到偶发失败:新用例连续 3 轮 10/10 全绿,全量 28/28 全绿;根因排查集中在配置装载一次性完成(@PostConstruct 缓存),无并发写入,不存在竞态,无需修复", "source": "agent", "rule_id": ""}
|
||||
{"at": "2026-11-06T16:41:40+08:00", "task_id": "20261106-20261106-businessrule-datadictionary-api-tests", "question": "scope-creep(是否扩大改动范围)", "answer": "不扩大,记录 3 项发现不修:① AGENTS.md §7 示例 JSON 写 message/timestamp,与代码实际 ErrorResponse(errorCode/errorMessage/data) 不符(Plan §6.4 已记录,建议单独开一轮);② config.auth.publicEndpoints 因 Map<String,Object> 绑定被序列化为 {\"0\":...} 而非数组(属既有 Map 绑定设计的固有结果,非本轮引入);③ docs/designs/topic/businessrule.md 的\"配置路径\"列指向 application.yml→jwt.expiration / SecurityConfig(hardcoded),与现在对外暴露的 config.auth.* 来源(business-rules/auth.yml)不完全一致", "source": "agent", "rule_id": ""}
|
||||
{"at": "2026-11-06T16:41:40+08:00", "task_id": "20261106-20261106-businessrule-datadictionary-api-tests", "question": "文档同步检查", "answer": "已更新:docs/standards/business-rule.md 补 4 行\"加载方式\"说明(防同类静默回归);application.yml.example 补 spring.config.import(该文件才是入库版本,真实 application.yml 被 gitignore);docs/designs/api.yaml、db-schema.md、topic/businessrule.md、topic/data-dict.md、docs/e2e-cases/ 均不涉及(契约、库表、规则与字典定义均未变)", "source": "agent", "rule_id": ""}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[test-failure] UserProfile.update 空 avatarUrl 触发 NPE(500)", "answer": "定位为实现 bug,最小修复 trimToNull 判空,未扩大改动", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[test-failure] 手机号格式用例返回 VALIDATION_ERROR 而非 PARAM_ERROR", "answer": "断言与实际契约不符(请求缺 code 先触发 @Valid),补齐 code 参数后断言 PARAM_ERROR", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[test-failure] 验证码重发间隔判定把 interval=0 当成\"仍在间隔内\"", "answer": "实现 bug,改为 now.isBefore(createdAt+interval)", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[db-migration] 是否执行迁移脚本", "answer": "先写回滚脚本 db/rollback/V20261117__acc_account_rollback.sql,再按 plan §11.3 重建本地 consultation 库并执行迁移,随后跑通 plan §13 六步冒烟", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[missing-plan] plan 未写明 ADMIN 种子如何落密文", "answer": "推断为运行时由 AccountSeedInitializer 创建(密文与部署密钥相关,静态 SQL 不可行),已登记为假设", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[missing-plan] plan 未写明 JWT 签发如何被应用层调用", "answer": "沿用工程既有 PasswordService 端口模式,新增 domain 端口 TokenIssuer,JwtTokenProvider 实现之", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[missing-plan] plan 未写明验证码 TTL/重发间隔/协议版本", "answer": "取 5 分钟 / 60 秒 / v1,全部做成配置项并记录", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[flaky-test] E2E TC-003 偶发失败(保存后昵称回退)", "answer": "根因是个人中心异步回填覆盖用户输入,加载期间禁用表单(不靠重试掩盖)", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[flaky-test] Element Plus 弹窗按钮随系统语言变英文导致 E2E 不稳", "answer": "应用统一 zh-cn 语言包,消除环境差异", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[scope-creep] AGENTS.md §10 写 MariaDB4j/@ActiveProfiles(\"test\") 与工程现状不符", "answer": "不改工程与文档,记录在 progress 备注", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
{"at": "2026-11-17T16:26:13+08:00", "task_id": "20261117-plan", "question": "[scope-creep] 未引入 Vitest 前端单测", "answer": "不新增依赖,前端行为由 E2E 覆盖,记录在 progress 备注", "source": "agent", "rule_id": "", "waited_sec": 0.0, "session_id": "ses_e17ac1c79ffe7PIi4BLheybXvI"}
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
queue:
|
||||
- id: 20261106-businessrule-datadictionary-api-tests
|
||||
plan: docs/features/_chores/plan-20261106-businessrule-datadictionary-api-tests.md
|
||||
priority: 10
|
||||
role: DEV
|
||||
- id: 20261106-fix-public-endpoints-and-error-doc
|
||||
plan: docs/features/_chores/plan-20261106-fix-public-endpoints-and-error-doc.md
|
||||
- id: 20261117-plan
|
||||
plan: docs/features/iteration1/ACC-account/plan.md
|
||||
priority: 10
|
||||
role: DEV
|
||||
|
||||
7
example-project/.overnight-runner/run-attended.command
Executable file
7
example-project/.overnight-runner/run-attended.command
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
export PATH="${HOME}/.opencode/bin:${PATH}"
|
||||
echo "=== overnight-runner (attended) ==="
|
||||
./.overnight-runner/overnight-runner list
|
||||
echo
|
||||
exec ./.overnight-runner/overnight-runner run --mode attended
|
||||
11
example-project/.overnight-runner/run-attended.sh
Executable file
11
example-project/.overnight-runner/run-attended.sh
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
export PATH="${HOME}/.opencode/bin:${PATH}"
|
||||
echo "项目: $ROOT"
|
||||
echo "队列: default"
|
||||
./.overnight-runner/overnight-runner list
|
||||
echo
|
||||
echo "启动 attended 前台面板(左队列 / 右 agent)。按 q 退出。"
|
||||
exec ./.overnight-runner/overnight-runner run --mode attended
|
||||
@@ -116,7 +116,8 @@ DTO 约定:
|
||||
|
||||
## 8. 领域设计:聚合与规则
|
||||
|
||||
> **现状(空壳)**:旧示例聚合已清除。目标模型以 `docs/features/iteration1/` 为准,按 feature plan 重建后回写本节与 `docs/facts/domain-model.md`。
|
||||
> **现状**:ACC(账号与个人中心)已落地,聚合见下;其余 feature 以 `docs/features/iteration1/` 为准,
|
||||
> 按 feature plan 重建后回写本节与 `docs/facts/domain-model.md`。
|
||||
|
||||
业务规则引擎(`domain/businessrule/`)— **框架保留、规则未注册**:
|
||||
|
||||
@@ -124,11 +125,25 @@ DTO 约定:
|
||||
- `BusinessRuleConfig` + `BusinessRuleProvider`;注册入口 `BusinessRuleRegistration`(当前为空)
|
||||
- 规则 YAML 目录:`resources/business-rules/`(可按 feature 新增)
|
||||
|
||||
数据字典(`domain/datadictionary/`)— **框架保留、类型未注册**:
|
||||
数据字典(`domain/datadictionary/`)— **框架保留、ACC 已注册**:
|
||||
|
||||
- `Description` / `DataDictionaryType` / `DataDictionaryUtil`
|
||||
- ACC 注册 `AccDataDictionaryType`(账号状态 / 账号角色 / 协议类型)
|
||||
- 实现 feature 时新增枚举并回写 `docs/facts/tech-topic/data-dict.md`
|
||||
|
||||
### 已落地聚合(ACC)
|
||||
|
||||
聚合根 **Account**(`domain/aggregate/Account.java`):角色集合(USER / CONSULTANT / ADMIN)、
|
||||
状态机(`ACTIVE` ⇄ `DISABLED`)、`tokenVersion`(禁用/启用时 +1,令旧 JWT 立即失效)、
|
||||
手机号摘要 + 密文。行为:`registerByPhone` / `createAdmin` / `grantConsultantRole`(幂等)/
|
||||
`disable` / `enable` / `touchLogin` / `assertUsable`。
|
||||
|
||||
关联实体:`UserProfile` / `FavoriteConsultant` / `AgreementConsent` / `SmsVerificationCode`。
|
||||
|
||||
领域端口(domain 定义、infrastructure 实现,可替换):
|
||||
`PhoneCrypto` / `SmsSender` / `DisplayableConsultantPort` / `TokenIssuer` / `PasswordService`。
|
||||
|
||||
|
||||
## 9. 预约状态机
|
||||
|
||||
> 旧示例状态机已清除。以 `docs/features/iteration1/BKG-booking`(及相关)spec §9 为准,实现后回写 `docs/facts/tech-topic/state-machine.md`。
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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("账号不存在"));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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("账号不存在"));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.consultation.domain.service;
|
||||
|
||||
/**
|
||||
* 咨询师「可展示」判定端口。本期由 ACC 提供 Stub 实现,CDC/COB 落地后替换为真实实现。
|
||||
*/
|
||||
public interface DisplayableConsultantPort {
|
||||
|
||||
boolean isDisplayable(String consultantId);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.consultation.domain.service;
|
||||
|
||||
/**
|
||||
* 短信发送端口。本期实现为本地 Mock,真短信通道归 PLT。
|
||||
*
|
||||
* <p>返回实际送达的验证码:Mock 固定码场景下返回固定值,调用方按返回值落摘要。</p>
|
||||
*/
|
||||
public interface SmsSender {
|
||||
|
||||
String send(String phone, String code);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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("协议类型不正确");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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("密钥派生失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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("账号角色序列化失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.consultation.infrastructure.security;
|
||||
|
||||
/**
|
||||
* 鉴权失败提示在请求属性中的键名。
|
||||
*/
|
||||
public final class AuthErrorMessage {
|
||||
|
||||
public static final String ATTRIBUTE = "com.consultation.authErrorMessage";
|
||||
|
||||
private AuthErrorMessage() {
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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/**
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user