feat: 实现客户端注册与任务领取接口
Admin 的第一个业务功能。选它打头是因为它是穿透所有层的最薄一条竖切
(HTTP → handler/api → service → repository → SQLite → handler/web → 页面),
一个工单把分层模式立起来,后面四个模块照抄;同时它是与 Client 联调的接口,
能解锁另一条并行的工作线。
实现
- POST /tasks/claim:注册 + 领取。注册就在这里做,没有单独的注册接口,
也没有心跳(理由见 docs/admin/04-client-api.md §3)
- 领取用条件更新 + 检查影响行数防并发,SQLite 没有 SELECT FOR UPDATE
- 客户端列表页:查询、按名称搜索、批量删除
- 在线状态是**算出来的**(last_seen_at 在 10 分钟内),数据库里没有该字段
- CSRF 中间件:双提交 Cookie,手写 82 行不引依赖。
**只挂页面路由**,/api/v1/client/* 不能加——Client 不是浏览器、没有 Cookie
- 14 个单元测试
修复一个真 bug:PRAGMA 必须写进 DSN
并发领取测试报 database is locked (SQLITE_BUSY)。根因是
PRAGMA busy_timeout 每连接生效,而 database/sql 是连接池——
db.Exec("PRAGMA ...") 只作用于当时那条连接,池子新开的连接没执行过。
单线程正常、一并发就炸。改成 DSN 传参后并发测试跑 20 次全过。
这个坑已写进 docs/admin/03-data-model.md §2.1。
与工单的两处差异
- 去掉 name_is_custom 列后,"人工改的名字不被覆盖"改用更简单的做法:
ON CONFLICT DO UPDATE SET 里不含 name,即只在首次注册时写入。
效果相同,零额外字段、零迁移。已同步 04 §3
- 验收项"不向 dry_run 客户端分配真实下单任务"**未实现**:
tasks 表没有字段标记任务是否需要真实下单。当前真实下单开关默认关闭、
MVP 全是演练模式,暂不出问题,但开真实下单前必须补该字段,需另开工单
已验证(Go 1.23.0)
- go vet / gofmt / go test 全过,并发测试重复 20 次稳定通过
- 端到端:无任务 claim 204;插入任务后 claim 200 且 payload 含
goods_url/goods_id/options/quantity/max_price_cent、无租约无 Admin 状态;
重复 claim 204;缺 X-Client-Id 400;POST 无 CSRF token 403;
列表页两台客户端在线状态与统计正确
说明:Gitea 尚未配置,本次无对应工单号。
submit_result / submit_failure 及其幂等处理留给下一个工单。
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CSRF 防护,用的是「双提交 Cookie」这个最简单的方案:
|
||||
//
|
||||
// 1. 给浏览器种一个随机 token 的 Cookie;
|
||||
// 2. 每个表单里带一个同值的隐藏字段;
|
||||
// 3. 提交时比对两者,不一致就拒绝。
|
||||
//
|
||||
// 原理:攻击者的页面可以诱导浏览器带上 Cookie 发请求,
|
||||
// 但**读不到** Cookie 的值,所以拼不出正确的隐藏字段。
|
||||
//
|
||||
// 没有引第三方库,是因为这个方案本身就几十行,
|
||||
// 而且多一个依赖就多一个可能要求 Go >= 1.25 的风险。
|
||||
//
|
||||
// **只给页面路由用。** 给 Client 的 /api/v1/client/* 绝不能加——
|
||||
// 它不是浏览器、没有 Cookie,加了会直接把它挡在门外。
|
||||
const (
|
||||
csrfCookieName = "cmautobuy_csrf"
|
||||
csrfFieldName = "csrf_token"
|
||||
csrfTokenBytes = 32
|
||||
)
|
||||
|
||||
// CSRFMiddleware 返回 Gin 中间件。
|
||||
//
|
||||
// GET 等安全方法只负责发 token;POST 等写操作要校验。
|
||||
func CSRFMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, err := c.Cookie(csrfCookieName)
|
||||
if err != nil || token == "" {
|
||||
token, err = newCSRFToken()
|
||||
if err != nil {
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// HttpOnly 必须为 false —— 双提交方案要让页面把值填进表单。
|
||||
// 本项目只监听本机,Secure 先留 false,将来上 HTTPS 再打开。
|
||||
c.SetCookie(csrfCookieName, token, 12*3600, "/", "", false, false)
|
||||
}
|
||||
// 交给模板渲染成隐藏字段
|
||||
c.Set(csrfFieldName, token)
|
||||
|
||||
switch c.Request.Method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
submitted := c.PostForm(csrfFieldName)
|
||||
if submitted == "" {
|
||||
submitted = c.GetHeader("X-CSRF-Token")
|
||||
}
|
||||
// 用常数时间比较,避免通过响应快慢猜 token
|
||||
if subtle.ConstantTimeCompare([]byte(submitted), []byte(token)) != 1 {
|
||||
c.HTML(http.StatusForbidden, "partials/error", gin.H{
|
||||
"Title": "请求被拒绝",
|
||||
"Message": "表单校验失败(CSRF token 不匹配)。" +
|
||||
"通常是页面开太久过期了,返回上一页刷新后重试即可。",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// newCSRFToken 生成一个随机 token。
|
||||
func newCSRFToken() (string, error) {
|
||||
buf := make([]byte, csrfTokenBytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
// csrfToken 从上下文取出当前 token,供页面渲染隐藏字段。
|
||||
func csrfToken(c *gin.Context) string {
|
||||
if v, ok := c.Get(csrfFieldName); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"cmautobuy/admin/service"
|
||||
)
|
||||
|
||||
// ---------- 2. 顺运宝数据 ----------
|
||||
@@ -16,7 +20,7 @@ func (h *Handler) SybList(c *gin.Context) {
|
||||
// TODO(骨架): 查货运单,并左联 sku_mappings 得出匹配状态
|
||||
var rows []gin.H
|
||||
|
||||
c.HTML(http.StatusOK, "syb/list", page("syb", "顺运宝数据", gin.H{
|
||||
c.HTML(http.StatusOK, "syb/list", page(c, "syb", "顺运宝数据", gin.H{
|
||||
"Keyword": keyword,
|
||||
"Rows": rows,
|
||||
"Status": "尚未实现:同步或手工录入后这里显示货运单",
|
||||
@@ -78,7 +82,7 @@ func (h *Handler) TaskList(c *gin.Context) {
|
||||
// TODO(骨架): 查 tasks,task_type = 'purchase'
|
||||
var rows []gin.H
|
||||
|
||||
c.HTML(http.StatusOK, "task/list", page("tasks", "采购任务", gin.H{
|
||||
c.HTML(http.StatusOK, "task/list", page(c, "tasks", "采购任务", gin.H{
|
||||
"Keyword": keyword,
|
||||
"Rows": rows,
|
||||
"Status": "尚未实现:创建任务后这里显示执行进度",
|
||||
@@ -103,18 +107,49 @@ func (h *Handler) TaskDelete(c *gin.Context) {
|
||||
func (h *Handler) ClientList(c *gin.Context) {
|
||||
keyword := c.Query("name")
|
||||
|
||||
// TODO(骨架): 查 clients,并按 last_seen_at 算在线状态
|
||||
var rows []gin.H
|
||||
views, err := service.ListClientViews(h.db, keyword, h.onlineThreshold)
|
||||
if err != nil {
|
||||
fail(c, http.StatusInternalServerError,
|
||||
"读取客户端列表失败,数据没有被改动。请稍后重试,或查看 data/logs/ 里的日志。")
|
||||
return
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "client/list", page("clients", "客户端列表", gin.H{
|
||||
online := 0
|
||||
for _, v := range views {
|
||||
if v.Status == "在线" {
|
||||
online++
|
||||
}
|
||||
}
|
||||
status := fmt.Sprintf("共 %d 台客户端 · 在线 %d · 离线 %d",
|
||||
len(views), online, len(views)-online)
|
||||
if len(views) == 0 {
|
||||
status = "还没有客户端。客户端第一次调用领取接口时会自动登记。"
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "client/list", page(c, "clients", "客户端列表", gin.H{
|
||||
"Keyword": keyword,
|
||||
"Rows": rows,
|
||||
"Status": "尚未实现:客户端第一次调领取接口后会自动出现在这里",
|
||||
"Rows": views,
|
||||
"Status": status,
|
||||
}))
|
||||
}
|
||||
|
||||
// ClientDelete 批量删除客户端。
|
||||
//
|
||||
// 二次确认在前端做(见 static/js/app.js),这里直接删。
|
||||
// 删掉之后客户端下次调 claim 会重新登记,属于正常行为。
|
||||
func (h *Handler) ClientDelete(c *gin.Context) {
|
||||
// TODO(骨架)
|
||||
fail(c, http.StatusNotImplemented, "删除功能尚未实现。")
|
||||
ids := c.PostFormArray("ids")
|
||||
if len(ids) == 0 {
|
||||
fail(c, http.StatusBadRequest, "没有选中任何客户端,请勾选后再删除。")
|
||||
return
|
||||
}
|
||||
|
||||
n, err := service.DeleteClients(h.db, ids)
|
||||
if err != nil {
|
||||
fail(c, http.StatusInternalServerError,
|
||||
"删除失败,数据没有被改动。请稍后重试,或查看 data/logs/ 里的日志。")
|
||||
return
|
||||
}
|
||||
log.Printf("clients_deleted count=%d", n)
|
||||
c.Redirect(http.StatusSeeOther, "/clients")
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ func (h *Handler) ShopeeList(c *gin.Context) {
|
||||
// 注意:搜索要走数据库查询,不要一次查全量再在内存里过滤。
|
||||
var rows []gin.H
|
||||
|
||||
c.HTML(http.StatusOK, "shopee/list", page("shopee", "蝦皮数据", gin.H{
|
||||
c.HTML(http.StatusOK, "shopee/list", page(c, "shopee", "蝦皮数据", gin.H{
|
||||
"Keyword": keyword,
|
||||
"Rows": rows,
|
||||
"Status": "尚未实现:导入后这里显示商品和规格",
|
||||
|
||||
+31
-21
@@ -12,6 +12,7 @@ package web
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -19,48 +20,57 @@ import (
|
||||
// Handler 持有各页面共用的依赖。
|
||||
type Handler struct {
|
||||
db *sql.DB
|
||||
// onlineThreshold 是判定客户端"在线"的时间窗。
|
||||
// 取「轮询周期 + 最长任务时长」,宽松一点,
|
||||
// 免得客户端执行长任务期间被误判成离线。
|
||||
onlineThreshold time.Duration
|
||||
}
|
||||
|
||||
// Register 把四个模块的页面路由挂上去。
|
||||
//
|
||||
// 四个模块的页面结构完全一致(顶部工具条 / 中间带勾选的表格 / 底部状态条),
|
||||
// 这是有意的,见 docs/admin/05-ui-specification.md §2。
|
||||
func Register(r *gin.Engine, db *sql.DB) {
|
||||
h := &Handler{db: db}
|
||||
func Register(r *gin.Engine, db *sql.DB, onlineThreshold time.Duration) {
|
||||
h := &Handler{db: db, onlineThreshold: onlineThreshold}
|
||||
|
||||
// CSRF 只挂在页面路由上。
|
||||
// 给 Client 的 /api/v1/client/* 绝不能加——它不是浏览器、没有 Cookie。
|
||||
pages := r.Group("/", CSRFMiddleware())
|
||||
|
||||
// 打开根路径直接进第一个模块
|
||||
r.GET("/", func(c *gin.Context) {
|
||||
pages.GET("/", func(c *gin.Context) {
|
||||
c.Redirect(http.StatusFound, "/shopee")
|
||||
})
|
||||
|
||||
// 1. 蝦皮数据
|
||||
r.GET("/shopee", h.ShopeeList)
|
||||
r.POST("/shopee/import", h.ShopeeImport)
|
||||
r.POST("/shopee/save", h.ShopeeSave)
|
||||
r.POST("/shopee/delete", h.ShopeeDelete)
|
||||
r.POST("/shopee/collect", h.ShopeeCollect)
|
||||
pages.GET("/shopee", h.ShopeeList)
|
||||
pages.POST("/shopee/import", h.ShopeeImport)
|
||||
pages.POST("/shopee/save", h.ShopeeSave)
|
||||
pages.POST("/shopee/delete", h.ShopeeDelete)
|
||||
pages.POST("/shopee/collect", h.ShopeeCollect)
|
||||
|
||||
// 2. 顺运宝数据
|
||||
r.GET("/syb", h.SybList)
|
||||
r.POST("/syb/sync", h.SybSync)
|
||||
r.POST("/syb/match", h.SybMatch)
|
||||
r.POST("/syb/create-task", h.SybCreateTask)
|
||||
r.POST("/syb/delete", h.SybDelete)
|
||||
pages.GET("/syb", h.SybList)
|
||||
pages.POST("/syb/sync", h.SybSync)
|
||||
pages.POST("/syb/match", h.SybMatch)
|
||||
pages.POST("/syb/create-task", h.SybCreateTask)
|
||||
pages.POST("/syb/delete", h.SybDelete)
|
||||
|
||||
// 3. 采购任务
|
||||
r.GET("/tasks", h.TaskList)
|
||||
r.POST("/tasks/delete", h.TaskDelete)
|
||||
pages.GET("/tasks", h.TaskList)
|
||||
pages.POST("/tasks/delete", h.TaskDelete)
|
||||
|
||||
// 4. 客户端列表
|
||||
r.GET("/clients", h.ClientList)
|
||||
r.POST("/clients/delete", h.ClientDelete)
|
||||
pages.GET("/clients", h.ClientList)
|
||||
pages.POST("/clients/delete", h.ClientDelete)
|
||||
}
|
||||
|
||||
// page 组装每个页面都要的公共数据(导航高亮、标题)。
|
||||
func page(active, title string, extra gin.H) gin.H {
|
||||
// page 组装每个页面都要的公共数据(导航高亮、标题、CSRF token)。
|
||||
func page(c *gin.Context, active, title string, extra gin.H) gin.H {
|
||||
data := gin.H{
|
||||
"Active": active,
|
||||
"Title": title,
|
||||
"Active": active,
|
||||
"Title": title,
|
||||
"CSRFToken": csrfToken(c),
|
||||
}
|
||||
for k, v := range extra {
|
||||
data[k] = v
|
||||
|
||||
Reference in New Issue
Block a user