feat(mes/wms/终端): 三端统一对时JWT验签 + 盘点按库位拆快照 + 档案删除口径 + 退库单数量修正(2026-11-24 全场整改)
【全系统 · 时间权威与鉴权(核心)】 - 新增 clock 包(三端各一份):谁签发 JWT 就以谁的时间验 exp——验签方向签发方取 /api/server-time(30s 缓存,取不到降级本机 + 10min 容差兜底),本端签发用本机时间 - 三端均注册 GET /api/server-time;MES/WMS/终端配同一份「签发方→取时间地址」映射 - 密钥 SHA256 前 8 位指纹日志([鉴权诊断]),现场比对两端指纹秒定位密钥不一致导致的 401「登录已失效」 - token 由 localStorage 改 sessionStorage;登录响应带服务器时间,偏差只提示「时间已自动校正」不拦截 - 现场人工 w32tm 对时操作卡作废(随文档留存,正常部署无需执行) 【WMS · 库存盘点重构】 - 快照粒度改「物料 × 库位」:同物料 A/B 区拆两条各盘各的;扫码命中多行弹库位清单逐库位录入、写回精确定位,行不存在报错不静默跳过 - GET /api/stocktake/active 返回全部进行中单(旧 .First() 只返一条导致历史多单看不见、库存长期冻结);前端加单号下拉切换,刷新保持当前单 - 历史卡死单只走「完成/取消」事务解冻,严禁删库;写回任何一行失败都强提示,不吞错 - 去「全库」,按区域筛选支持选到区/货架/层/号任意层级;「本次盘点范围」同步加筛选、物料按区域过滤;去多余「(可选)」字样 【WMS/MES · 档案删除与停用口径】 - 产品档案新建默认停用(product_process.status ACTIVE→INACTIVE),配齐工艺路线+总账+分账才允许启用 - 产品/物料档案删除按钮统一为一个(按 WMS 做法),仅「无任何引用」可物理删;引用检查覆盖两库、查库报错一律拒绝删除(fail-close,不再误删) - 产品编码自动生成,重复则自增保证唯一;权限对齐:停用走「编辑」、删除走独立「删除」码 - WMS 删物料同步核查 MES 引用,MES 不可达/删除失败则拒绝并落同步失败台账,无兼容补录行 【业务整改】 - MES 工单整体完工自动结算遗留 PENDING 叫料单(释放占用额度);已发货 SHIPPED 不动,仅落日志提示人工签收 - WMS 已收货退库单支持直接修正数量(问题14):原单不动、留痕(修正人/时间/原因/前后值),库存差额补扣,SN 件按最终 SN 集合增删行 - 日排产:「排产日期范围」→「排产日期」;平铺补产品编码/名称;「产品型号」→「产品」去产品编号/名称;平均分摊与每日固定互算;删除写操作日志 - 齐套测算:逐日消耗模拟按实际排产日期;工单详情增「总物料清单」(照搬产品档案总账,实时) - PLC 对账:虚拟/离线工位(OFFLINE,如 15)跳过 PLC 托盘位读取,不再为特例扔给 PLC - AGV 点位锁与回调细节按 11-20 现场整改继续修正(agv.go / agv_point_lock.go) 【文档】 - 新增《全系统业务深坑审计报告》《全系统串联审计报告》《现场对时操作卡》;更新产线API.md、案例.md、问题临时.md(记录甲方逐条原话与验收口径)
This commit is contained in:
@@ -1,13 +1,18 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bj_power_workstation/internal/clock"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
// Claims 自定义 JWT 声明
|
||||
@@ -33,6 +38,14 @@ type TokenInfo struct {
|
||||
|
||||
const issuer = "bj_power_workstation"
|
||||
|
||||
// Fingerprint 返回密钥 SHA256 前 8 位十六进制指纹(2026-11-24 诊断用):
|
||||
// 日志只打指纹不打密钥本体,与 MES 启动日志的 [鉴权诊断] 指纹一比对,
|
||||
// 不一致即两端密钥不统一——本端验签必 401「登录已失效」,现场秒定位。
|
||||
func Fingerprint(secret string) string {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(sum[:4])
|
||||
}
|
||||
|
||||
// SessionValidator 由 main 注入:校验请求 token 是否存在于任一有效登录会话
|
||||
// (多会话版:同工位互踢后旧 token 不再命中任何会话,即被判为已下线)。nil 时跳过该校验。
|
||||
var SessionValidator func(token string) bool
|
||||
@@ -69,8 +82,12 @@ func SignToken(secret string, expire int64, info TokenInfo) (string, int64, erro
|
||||
}
|
||||
|
||||
// ParseToken 校验并解析 JWT
|
||||
// 2026-11-24 拍板:谁签发 JWT 就以谁的时间验 exp——本机重签的用本机时间,MES 签发的
|
||||
// 先向 MES 取 /api/server-time(30 秒缓存,取不到降级本机)。10 分钟容差继续作兜底,
|
||||
// 防止签发方时间接口短时不可达时的误判。
|
||||
func ParseToken(secret, tokenStr string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (any, error) {
|
||||
parser := jwt.NewParser(jwt.WithoutClaimsValidation())
|
||||
token, err := parser.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("非法签名算法")
|
||||
}
|
||||
@@ -83,6 +100,11 @@ func ParseToken(secret, tokenStr string) (*Claims, error) {
|
||||
if !ok || !token.Valid {
|
||||
return nil, errors.New("token 无效")
|
||||
}
|
||||
// 按签发方服务器时间验过期,再叠加 10 分钟容差兜底
|
||||
authority := clock.AuthorityNow(claims.Issuer)
|
||||
if !claims.VerifyExpiresAt(authority.Add(10*time.Minute), true) {
|
||||
return nil, errors.New("登录已失效(token 已过期)")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
@@ -126,6 +148,7 @@ func Interceptor(secret string, accessExpire int64) func(next http.HandlerFunc)
|
||||
|
||||
notAPI := !strings.HasPrefix(path, "/api/") && !strings.HasPrefix(path, "/pdfopen/")
|
||||
whitelisted := path == "/api/health" ||
|
||||
path == "/api/server-time" ||
|
||||
path == "/api/auth/login" ||
|
||||
path == "/api/config" ||
|
||||
path == "/api/station-options" ||
|
||||
@@ -138,12 +161,22 @@ func Interceptor(secret string, accessExpire int64) func(next http.HandlerFunc)
|
||||
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
// 2026-11-24 鉴权诊断:401 三种来源(缺头/解析失败/会话失效)分别留痕,现场定位不再靠猜
|
||||
logx.Errorf("[鉴权诊断] 401 缺 Authorization 头 path=%s remote=%s", path, r.RemoteAddr)
|
||||
unauthorized(w, "未登录或 token 缺失")
|
||||
return
|
||||
}
|
||||
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
claims, err := ParseToken(secret, tokenStr)
|
||||
if err != nil {
|
||||
// 2026-11-24 鉴权诊断:解析失败带真实原因(签名不符/过期/格式错)+token 指纹+本端密钥指纹。
|
||||
// 与 MES 启动日志 [鉴权诊断] 的密钥指纹比对,不一致即两端密钥不统一(「登录秒失效」根因)。
|
||||
prefix := tokenStr
|
||||
if len(prefix) > 24 {
|
||||
prefix = prefix[:24]
|
||||
}
|
||||
logx.Errorf("[鉴权诊断] 401 token 解析失败 原因=%v token前24=%s 本端密钥指纹=%s path=%s remote=%s",
|
||||
err, prefix, Fingerprint(secret), path, r.RemoteAddr)
|
||||
unauthorized(w, "登录已失效")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Package clock 提供 JWT 验签用的"签发方服务器时间"权威基准(2026-11-24 用户拍板)。
|
||||
// 规则:谁签发 JWT,验签就以那台服务器的时间为准;验签方先向签发方 /api/server-time
|
||||
// 取当前时间,30 秒缓存降低压力,取不到降级本机时间(10 分钟容差继续兜底)。
|
||||
// 本机自己签发的 token 直接用本机时间,不走网络。
|
||||
package clock
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
// Config 时钟权威配置:Issuer=本端签发方标识,Sources=签发方→取时间地址映射(三端配同一份)
|
||||
type Config struct {
|
||||
Issuer string
|
||||
Sources map[string]string
|
||||
}
|
||||
|
||||
const (
|
||||
cacheTTL = 30 * time.Second
|
||||
requestTimeout = 1500 * time.Millisecond
|
||||
)
|
||||
|
||||
var (
|
||||
mu sync.RWMutex
|
||||
cfg Config
|
||||
cache = make(map[string]entry)
|
||||
client = &http.Client{Timeout: requestTimeout}
|
||||
)
|
||||
|
||||
type entry struct {
|
||||
unix int64
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
// Init 启动时注入配置并清空缓存
|
||||
func Init(c Config) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
cfg = c
|
||||
cache = make(map[string]entry)
|
||||
}
|
||||
|
||||
// AuthorityNow 返回 issuer 对应签发方的权威当前时间。
|
||||
// 本端签发或映射缺失时直接返回本机时间;跨端取时间失败也降级本机时间。
|
||||
func AuthorityNow(issuer string) time.Time {
|
||||
if issuer == "" {
|
||||
return time.Now()
|
||||
}
|
||||
mu.RLock()
|
||||
self := cfg.Issuer
|
||||
url := cfg.Sources[issuer]
|
||||
mu.RUnlock()
|
||||
if issuer == self || url == "" {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
mu.RLock()
|
||||
e, ok := cache[issuer]
|
||||
mu.RUnlock()
|
||||
if ok && time.Since(e.fetchedAt) < cacheTTL {
|
||||
return time.Unix(e.unix, 0)
|
||||
}
|
||||
|
||||
unix, err := fetch(url)
|
||||
if err != nil {
|
||||
logx.Errorf("[时钟权威] 取签发方时间失败 issuer=%s url=%s err=%v,降级本机时间", issuer, url, err)
|
||||
return time.Now()
|
||||
}
|
||||
mu.Lock()
|
||||
cache[issuer] = entry{unix: unix, fetchedAt: time.Now()}
|
||||
mu.Unlock()
|
||||
return time.Unix(unix, 0)
|
||||
}
|
||||
|
||||
func fetch(url string) (int64, error) {
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
var r struct {
|
||||
ServerTime int64 `json:"serverTime"`
|
||||
Data struct {
|
||||
ServerTime int64 `json:"serverTime"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
unix := r.ServerTime
|
||||
if unix <= 0 {
|
||||
unix = r.Data.ServerTime
|
||||
}
|
||||
if unix <= 0 {
|
||||
return 0, fmt.Errorf("serverTime 无效")
|
||||
}
|
||||
return unix, nil
|
||||
}
|
||||
@@ -13,6 +13,12 @@ type AuthConfig struct {
|
||||
AccessExpire int64 `json:",default=1800"` // 有效期(秒)
|
||||
}
|
||||
|
||||
// ClockConfig JWT 验签时间权威(2026-11-24 用户拍板):谁签发 JWT 就以谁的时间验 exp。
|
||||
// Sources = 签发方标识 → 该方 /api/server-time 地址;留空项启动时从已知 BaseURL 推导。
|
||||
type ClockConfig struct {
|
||||
Sources map[string]string `json:",optional"`
|
||||
}
|
||||
|
||||
// MesConfig MES 服务地址(内部 API)
|
||||
type MesConfig struct {
|
||||
BaseURL string `json:",default=http://127.0.0.1:8888"`
|
||||
@@ -67,4 +73,5 @@ type Config struct {
|
||||
PdfCache PdfCacheConfig `json:",optional"`
|
||||
Tightening tightening.TighteningConfig `json:",optional"`
|
||||
Scanner ScannerConfig `json:",optional"`
|
||||
Clock ClockConfig `json:",optional"`
|
||||
}
|
||||
@@ -28,6 +28,14 @@ func healthHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// serverTimeHandler 免鉴权返回本机 unix 秒(2026-11-24 JWT 时间权威):
|
||||
// 供 MES/WMS 验本终端签发的 token 时取时间;只暴露当前时间,不含任何业务数据。
|
||||
func serverTimeHandler(_ *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, _ *http.Request) {
|
||||
ok(w, map[string]any{"serverTime": time.Now().Unix()})
|
||||
}
|
||||
}
|
||||
|
||||
// loginHandler 登录代理 MES /api/internal/station/login(块1:用户体系来源于 MES)。
|
||||
// 前端提交 {username, password, stationNo},MES 校验工位终端密码 + 工位权限并签发同密钥 JWT。
|
||||
// 响应体原样透传({code,message,data:{accessToken,expireAt,user,stations,stationNo}})。
|
||||
@@ -52,6 +60,12 @@ func loginHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
if ctx.Config.Station.StationNo > 0 {
|
||||
req.StationNo = ctx.Config.Station.StationNo
|
||||
} else {
|
||||
// 2026-11-24 拍板:0 在 Go 里是零值=「没有工位」,必须拒绝;
|
||||
// 负数(-1/-2… 前段虚拟工位)合法放行,合法性再由 isVirtualStation 查 MES 清单确认。
|
||||
if req.StationNo == 0 {
|
||||
fail(w, http.StatusBadRequest, "请先选择工位")
|
||||
return
|
||||
}
|
||||
virtual, vErr := isVirtualStation(ctx, req.StationNo)
|
||||
if vErr == nil && !virtual {
|
||||
fail(w, http.StatusForbidden, "本终端未配置固定工位,仅允许登录虚拟工位")
|
||||
@@ -84,6 +98,7 @@ func loginHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
Data struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
ExpireAt int64 `json:"expireAt"`
|
||||
ServerTime int64 `json:"serverTime"`
|
||||
StationNo int `json:"stationNo"`
|
||||
User struct {
|
||||
Username string `json:"username"`
|
||||
@@ -91,29 +106,63 @@ func loginHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
} `json:"user"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &loginResp); err == nil && loginResp.Data.AccessToken != "" {
|
||||
// 多会话(2026-11-11):同工位只允许一个会话——该工位已有会话则先踢旧会话
|
||||
//(ReplaceStationSession 返回被踢者),通知 MES 记录旧会话登出(尽力而为);
|
||||
// 不同工位会话互不影响。被踢端下一次请求因 token 不在会话表中被 401 踢下线,
|
||||
// 其本地记录随会话删除;工位物料/工件信息在 MES 侧按工位号存,不随会话删除。
|
||||
kicked, serr := ctx.Store.SaveStationSession(loginResp.Data.AccessToken, loginResp.Data.User.Username,
|
||||
loginResp.Data.User.Name, loginResp.Data.StationNo, loginResp.Data.ExpireAt, userIDOf(ctx, loginResp.Data.AccessToken))
|
||||
if serr == nil && kicked != nil && kicked.Token != "" {
|
||||
go func(u string, n int) {
|
||||
_, _, _ = ctx.Mes.Post("/api/internal/station/logout", map[string]any{"username": u, "stationNo": n})
|
||||
}(kicked.Username, kicked.StationNo)
|
||||
}
|
||||
// 拧紧枪配置快照补报(2026-11-09):仅 MES 展示记录,不参与数据收集;
|
||||
// 启动时若 MES 未就绪,登录这一刻补上,失败只记日志不影响登录。
|
||||
go func(no int) {
|
||||
if no <= 0 {
|
||||
no = ctx.Config.Station.StationNo
|
||||
}
|
||||
if err := ctx.Mes.ReportTighteningConfig(ctx.Config.Tightening, no); err != nil {
|
||||
logx.Infof("拧紧枪配置上报 MES 失败(仅展示记录,不影响登录): %v", err)
|
||||
}
|
||||
}(loginResp.Data.StationNo)
|
||||
// 2026-11-24 P0 修复(硬件工位终端「登录成功→立刻失效」):
|
||||
// 会话表是本地鉴权的唯一依据(SessionValidator 按 token 查 station_session)。
|
||||
// 此前解析失败 / token 为空 / SaveStationSession 报错三种情况都静默跳过会话写入、
|
||||
// 仍原样返回 MES 成功 body:前端显示「登录成功」,但下一请求查不到会话→立即 401。
|
||||
// 现在:会话写入失败即登录失败,明确报错并记日志(含真实原因),不再返回假成功。
|
||||
if err := json.Unmarshal(body, &loginResp); err != nil || loginResp.Data.AccessToken == "" {
|
||||
logx.Errorf("工位登录:解析 MES 响应失败或 token 为空 err=%v body=%s", err, string(body))
|
||||
fail(w, http.StatusBadGateway, "登录失败:MES 返回的登录信息不完整,请重试")
|
||||
return
|
||||
}
|
||||
// 多会话(2026-11-11):同工位只允许一个会话——该工位已有会话则先踢旧会话
|
||||
//(ReplaceStationSession 返回被踢者),通知 MES 记录旧会话登出(尽力而为);
|
||||
// 不同工位会话互不影响。被踢端下一次请求因 token 不在会话表中被 401 踢下线,
|
||||
// 其本地记录随会话删除;工位物料/工件信息在 MES 侧按工位号存,不随会话删除。
|
||||
loginStationNo := loginResp.Data.StationNo
|
||||
if loginStationNo == 0 {
|
||||
loginStationNo = ctx.Config.Station.StationNo // 兜底:MES 未回工位号时用本地固定工位
|
||||
}
|
||||
kicked, serr := ctx.Store.SaveStationSession(loginResp.Data.AccessToken, loginResp.Data.User.Username,
|
||||
loginResp.Data.User.Name, loginStationNo, loginResp.Data.ExpireAt, userIDOf(ctx, loginResp.Data.AccessToken))
|
||||
if serr != nil {
|
||||
logx.Errorf("工位登录:保存登录会话失败 stationNo=%d user=%s err=%v", loginStationNo, loginResp.Data.User.Username, serr)
|
||||
fail(w, http.StatusInternalServerError, "登录失败:本地登录态保存失败,请重试("+serr.Error()+")")
|
||||
return
|
||||
}
|
||||
if kicked != nil && kicked.Token != "" {
|
||||
go func(u string, n int) {
|
||||
_, _, _ = ctx.Mes.Post("/api/internal/station/logout", map[string]any{"username": u, "stationNo": n})
|
||||
}(kicked.Username, kicked.StationNo)
|
||||
}
|
||||
// 2026-11-24 时钟偏差自检(第 2 层防御):登录响应携带 MES 服务器时间,与本机比对,
|
||||
// 偏差超 60 秒记错误日志(前端另有醒目告警)。token 有效期按 MES 时钟签发、按本机时间
|
||||
// 验证——两机时钟漂移过大会导致登录成功后立刻 401(现场已实锤根因)。
|
||||
if loginResp.Data.ServerTime != 0 {
|
||||
skew := time.Now().Unix() - loginResp.Data.ServerTime
|
||||
if skew < 0 {
|
||||
skew = -skew
|
||||
}
|
||||
if skew > 60 {
|
||||
logx.Errorf("[时钟偏差] 本机与 MES 服务器时间相差 %d 秒(serverTime=%d):偏差过大会让 token 一签出来就过期(登录秒失效),请运维统一对时", skew, loginResp.Data.ServerTime)
|
||||
}
|
||||
}
|
||||
// 拧紧枪配置快照补报(2026-11-09):仅 MES 展示记录,不参与数据收集;
|
||||
// 启动时若 MES 未就绪,登录这一刻补上,失败只记日志不影响登录。
|
||||
go func(no int) {
|
||||
if no <= 0 {
|
||||
no = ctx.Config.Station.StationNo
|
||||
}
|
||||
if err := ctx.Mes.ReportTighteningConfig(ctx.Config.Tightening, no); err != nil {
|
||||
logx.Infof("拧紧枪配置上报 MES 失败(仅展示记录,不影响登录): %v", err)
|
||||
}
|
||||
}(loginStationNo)
|
||||
loginPrefix := loginResp.Data.AccessToken
|
||||
if len(loginPrefix) > 24 {
|
||||
loginPrefix = loginPrefix[:24]
|
||||
}
|
||||
logx.Infof("[会话诊断] 登录成功写入会话: stationNo=%d token=%s 会话表=%s", loginStationNo, loginPrefix, ctx.Store.SessionFingerprints())
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(body)
|
||||
@@ -122,10 +171,9 @@ func loginHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
|
||||
// isVirtualStation 查询 MES 工位清单判断工位号是否虚拟工位(stationType=OFFLINE)。
|
||||
// 多会话拍板(2026-11-11):未配置固定工位的终端实例只允许登录虚拟工位。
|
||||
// 2026-11-24 拍板:放开负数号虚拟工位(前段虚拟工位 -1/-2… 在 MES 与产线布局说明里合法);
|
||||
// 不再用 stationNo<=0 硬拒,一律以 MES 工位清单里 stationType=OFFLINE 为准。
|
||||
func isVirtualStation(ctx *svc.ServiceContext, stationNo int) (bool, error) {
|
||||
if stationNo <= 0 {
|
||||
return false, nil // 0/负数不是合法工位(原 0 号上线位已废弃)
|
||||
}
|
||||
body, _, err := ctx.Mes.Get("/api/internal/station/options", nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
|
||||
@@ -98,6 +98,12 @@ func processDoneHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
"stationNo": req.StationNo,
|
||||
"operator": op,
|
||||
}
|
||||
// 2026-11-23 P0 修复:此前收了 steps(步骤参数/检测确认 checked)却没放进转发 body,
|
||||
// MES 端 ReportReq.Steps 恒为空——工序实绩、needCheck 强校验(防绕过前端)全部失效。
|
||||
// 字段名与 MES StepDataReq 逐一对齐(workpiece.go:102-109)。
|
||||
if len(req.Steps) > 0 {
|
||||
body["steps"] = req.Steps
|
||||
}
|
||||
if len(req.Binds) > 0 {
|
||||
body["binds"] = req.Binds
|
||||
}
|
||||
@@ -293,6 +299,18 @@ func mesConfigHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
failMes(w, err, "MES 不可达,配置获取失败")
|
||||
return
|
||||
}
|
||||
ok(w, json.RawMessage(b))
|
||||
// 2026-11-24 修复:MES 返回 {code,message,data:{torqueManualInput...}},
|
||||
// 旧代码原样塞进本地 ok() 又包一层 data,前端读到的是 {data:{code,data:{...}}},
|
||||
// 取不到 torqueManualInput 一律回落 allow——MES 配 forbid 终端仍能手填。
|
||||
// 这里先剥掉 MES 外层信封,只把真正的 data 作为本地 data 返回。
|
||||
var envelope struct {
|
||||
Code int `json:"code"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if e := json.Unmarshal(b, &envelope); e == nil && envelope.Code == 0 && len(envelope.Data) > 0 {
|
||||
ok(w, json.RawMessage(envelope.Data))
|
||||
return
|
||||
}
|
||||
ok(w, json.RawMessage(b)) // 解析失败兜底原样,保持旧行为
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) {
|
||||
server.AddRoutes(
|
||||
[]rest.Route{
|
||||
{Method: http.MethodGet, Path: "/api/health", Handler: healthHandler(ctx)},
|
||||
{Method: http.MethodGet, Path: "/api/server-time", Handler: serverTimeHandler(ctx)},
|
||||
{Method: http.MethodPost, Path: "/api/auth/login", Handler: loginHandler(ctx)},
|
||||
{Method: http.MethodGet, Path: "/api/config", Handler: configHandler(ctx)},
|
||||
// 工位选项(免鉴权,登录前调用):未配置工位的终端登录页选择工位用(2026-11-09 拍板)
|
||||
|
||||
@@ -3,6 +3,7 @@ package store
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -95,9 +96,71 @@ func Open(path string) (*Store, error) {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
// 2026-11-24 自愈:会话表脏数据/结构损坏是「登录成功立刻失效」的根因之一,
|
||||
// 启动时校验一次,不健康就重建(纯登录态,重建只需重新登录,不丢业务数据)。
|
||||
if err := s.HealStationSession(); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// HealStationSession 会话表自愈检查:结构缺列、旧版单行约束、唯一索引缺失、脏行任一命中即重建。
|
||||
// 会话表只存登录态,不含业务数据;重建代价仅是要求重新登录。
|
||||
func (s *Store) HealStationSession() error {
|
||||
var sqlText string
|
||||
err := s.db.QueryRow(`SELECT sql FROM sqlite_master WHERE type='table' AND name='station_session'`).Scan(&sqlText)
|
||||
if err == sql.ErrNoRows || sqlText == "" {
|
||||
return s.RebuildStationSession()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.Contains(sqlText, "CHECK(id=1)") {
|
||||
return s.RebuildStationSession()
|
||||
}
|
||||
for _, col := range []string{"token", "username", "name", "station_no", "user_id", "expire_at", "last_active_at", "created_at"} {
|
||||
var n int
|
||||
if e := s.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('station_session') WHERE name=?`, col).Scan(&n); e != nil || n == 0 {
|
||||
return s.RebuildStationSession()
|
||||
}
|
||||
}
|
||||
var idx int
|
||||
if e := s.db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name='idx_station_session_station'`).Scan(&idx); e != nil || idx == 0 {
|
||||
return s.RebuildStationSession()
|
||||
}
|
||||
// 同工位重复行(唯一索引本应杜绝,脏库可能出现)视为不健康。
|
||||
var dup int
|
||||
if e := s.db.QueryRow(`SELECT COUNT(*) FROM (SELECT station_no FROM station_session WHERE station_no>0 GROUP BY station_no HAVING COUNT(*)>1)`).Scan(&dup); e == nil && dup > 0 {
|
||||
return s.RebuildStationSession()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RebuildStationSession 重建会话表(清空所有登录态;不影响 users/event_log 等业务表)。
|
||||
func (s *Store) RebuildStationSession() error {
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
stmts := []string{
|
||||
`DROP TABLE IF EXISTS station_session`,
|
||||
`CREATE TABLE station_session (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
token TEXT UNIQUE, username TEXT, name TEXT, station_no INTEGER NOT NULL DEFAULT 0,
|
||||
user_id INTEGER, expire_at INTEGER, last_active_at INTEGER, created_at INTEGER
|
||||
)`,
|
||||
`CREATE UNIQUE INDEX idx_station_session_station ON station_session(station_no) WHERE station_no > 0`,
|
||||
}
|
||||
for _, q := range stmts {
|
||||
if _, err := tx.Exec(q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// migrateStationSession 兼容旧库:登录态表为方案 B 新增,缺失时自动补齐(多行会话版)。
|
||||
func (s *Store) migrateStationSession() error {
|
||||
rows, err := s.db.Query(`SELECT name FROM pragma_table_info('station_session') WHERE name='token'`)
|
||||
@@ -206,6 +269,20 @@ type StationSession struct {
|
||||
// 若该工位已有会话则先删除(返回被踢会话供上层通知 MES 登出),随后插入新会话。
|
||||
// 不同工位的会话互不影响,可同时在线。
|
||||
func (s *Store) SaveStationSession(token, username, name string, stationNo int, expireAt int64, userID int64) (*StationSession, error) {
|
||||
kicked, err := s.saveStationSessionOnce(token, username, name, stationNo, expireAt, userID)
|
||||
if err == nil {
|
||||
return kicked, nil
|
||||
}
|
||||
// 2026-11-24 自愈:写入失败多为会话表结构损坏/脏唯一索引(旧库多会话迁移残留)。
|
||||
// 重建会话表后重试一次;仍失败才把错误上抛(登录 handler 会明确报错并记日志)。
|
||||
log.Printf("[会话自愈] 保存会话失败,重建 station_session 后重试: stationNo=%d err=%v", stationNo, err)
|
||||
if rbErr := s.RebuildStationSession(); rbErr != nil {
|
||||
return nil, fmt.Errorf("会话表自愈重建失败: %v(原写入错误: %v)", rbErr, err)
|
||||
}
|
||||
return s.saveStationSessionOnce(token, username, name, stationNo, expireAt, userID)
|
||||
}
|
||||
|
||||
func (s *Store) saveStationSessionOnce(token, username, name string, stationNo int, expireAt int64, userID int64) (*StationSession, error) {
|
||||
now := time.Now().Unix()
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
@@ -302,6 +379,30 @@ func (s *Store) GetStationSessionByToken(token string) (*StationSession, error)
|
||||
return &ss, nil
|
||||
}
|
||||
|
||||
// SessionFingerprints 返回所有会话 token 的前 24 字符指纹(诊断用,不泄露完整凭证)。
|
||||
func (s *Store) SessionFingerprints() string {
|
||||
rows, err := s.db.Query(`SELECT station_no, token FROM station_session`)
|
||||
if err != nil {
|
||||
return "查询失败:" + err.Error()
|
||||
}
|
||||
defer rows.Close()
|
||||
var parts []string
|
||||
for rows.Next() {
|
||||
var stationNo int
|
||||
var token string
|
||||
if rows.Scan(&stationNo, &token) == nil {
|
||||
if len(token) > 24 {
|
||||
token = token[:24]
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("工位%d:%s", stationNo, token))
|
||||
}
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "空"
|
||||
}
|
||||
return strings.Join(parts, " | ")
|
||||
}
|
||||
|
||||
// HasSessionToken 请求 token 是否存在于任一有效登录会话(在线态校验 · 多会话版)。
|
||||
func (s *Store) HasSessionToken(token string) (bool, error) {
|
||||
if token == "" {
|
||||
|
||||
Reference in New Issue
Block a user