【全系统 · 时间权威与鉴权(核心)】 - 新增 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(记录甲方逐条原话与验收口径)
163 lines
6.1 KiB
Go
163 lines
6.1 KiB
Go
package handler
|
||
|
||
import (
|
||
"errors"
|
||
"net/http"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"bj_power_wms/ent/user"
|
||
"bj_power_wms/internal/clock"
|
||
"bj_power_wms/internal/svc"
|
||
|
||
"github.com/golang-jwt/jwt/v4"
|
||
)
|
||
|
||
// JWTClaims 自定义声明
|
||
type JWTClaims struct {
|
||
UserID int `json:"userId"`
|
||
Username string `json:"username"`
|
||
RealName string `json:"realName"`
|
||
Role string `json:"role"`
|
||
// SID 后台登录会话标识(同账号互踢,2026-11-11):后台 login 生成并写入 users.active_token;
|
||
// 滑动续签(renewIfNearExpiry)原样保留 SID——不能比对原始 token 串(每请求重签会误踢并发请求)。
|
||
SID string `json:"sid,omitempty"`
|
||
jwt.RegisteredClaims
|
||
}
|
||
|
||
// sessionExpire 会话闲置窗口(秒),默认 1 小时
|
||
func sessionExpire(ctx *svc.ServiceContext) int64 {
|
||
if ctx.Config.Auth.AccessExpire > 0 {
|
||
return ctx.Config.Auth.AccessExpire
|
||
}
|
||
return 3600
|
||
}
|
||
|
||
// SignToken 签发 JWT;sid=后台登录会话标识(互踢用,续签时传 claims.SID 原样保留)
|
||
func SignToken(ctx *svc.ServiceContext, userID int, username, realName, role, sid string) (string, int64, error) {
|
||
expire := sessionExpire(ctx)
|
||
exp := time.Now().Add(time.Duration(expire) * time.Second)
|
||
claims := &JWTClaims{
|
||
UserID: userID,
|
||
Username: username,
|
||
RealName: realName,
|
||
Role: role,
|
||
SID: sid,
|
||
RegisteredClaims: jwt.RegisteredClaims{
|
||
ExpiresAt: jwt.NewNumericDate(exp),
|
||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||
Issuer: "bj_power_wms",
|
||
},
|
||
}
|
||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||
signed, err := token.SignedString([]byte(ctx.Config.Auth.AccessSecret))
|
||
return signed, exp.Unix(), err
|
||
}
|
||
|
||
// ParseToken 校验并解析 JWT
|
||
// 2026-11-24 拍板:谁签发 JWT 就以谁的时间验 exp——WMS 本端签发的用本机时间,外部签发的
|
||
// 先向签发方取 /api/server-time(30 秒缓存,取不到降级本机)。10 分钟容差继续兜底。
|
||
func ParseToken(ctx *svc.ServiceContext, tokenStr string) (*JWTClaims, error) {
|
||
parser := jwt.NewParser(jwt.WithoutClaimsValidation())
|
||
token, err := parser.ParseWithClaims(tokenStr, &JWTClaims{}, func(t *jwt.Token) (any, error) {
|
||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||
return nil, errors.New("非法签名算法")
|
||
}
|
||
return []byte(ctx.Config.Auth.AccessSecret), nil
|
||
})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
claims, okk := token.Claims.(*JWTClaims)
|
||
if !okk || !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
|
||
}
|
||
|
||
// renewIfNearExpiry 滑动续签:每个携带有效 token 的请求都重签,
|
||
// 会话有效期 = 距最后一次请求 sessionExpire 秒(默认 1 小时),闲置超时即 401。
|
||
func renewIfNearExpiry(ctx *svc.ServiceContext, w http.ResponseWriter, claims *JWTClaims) {
|
||
if time.Until(claims.ExpiresAt.Time) > 0 {
|
||
if newToken, _, err := SignToken(ctx, claims.UserID, claims.Username, claims.RealName, claims.Role, claims.SID); err == nil {
|
||
w.Header().Set("X-Renewed-Token", newToken)
|
||
}
|
||
}
|
||
}
|
||
|
||
// authInterceptor 登录鉴权中间件(白名单之外的 /api/* 需要 JWT)
|
||
// go-zero rest.Middleware 签名:func(next http.HandlerFunc) http.HandlerFunc
|
||
func authInterceptor(ctx *svc.ServiceContext) func(next http.HandlerFunc) http.HandlerFunc {
|
||
return func(next http.HandlerFunc) http.HandlerFunc {
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
path := r.URL.Path
|
||
|
||
// 白名单:健康检查 / 登录注册 / 免登录大屏 / 内部API(自带写死token校验) / 附件静态文件
|
||
// /uploads/* 为附件预览(window.open 新窗口打开,浏览器无法携带 Authorization 头),必须免鉴权。
|
||
if path == "/api/health" ||
|
||
path == "/api/server-time" ||
|
||
strings.HasPrefix(path, "/api/auth/") ||
|
||
strings.HasPrefix(path, "/api/display/") ||
|
||
strings.HasPrefix(path, "/api/internal/") ||
|
||
strings.HasPrefix(path, "/uploads/") {
|
||
next.ServeHTTP(w, r)
|
||
return
|
||
}
|
||
|
||
authHeader := r.Header.Get("Authorization")
|
||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||
failCode(w, http.StatusUnauthorized, 401, "未登录或 token 缺失")
|
||
return
|
||
}
|
||
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
|
||
claims, err := ParseToken(ctx, tokenStr)
|
||
if err != nil {
|
||
failCode(w, http.StatusUnauthorized, 401, "登录已失效,请重新登录")
|
||
return
|
||
}
|
||
// 后台同账号互踢守卫(2026-11-11):JWT 内 SID 与 users.active_token 不一致 → 已被新登录顶掉。
|
||
// active_token 为空(存量旧会话/未后台登录过)放行,下次后台登录后生效。
|
||
if claims.UserID > 0 {
|
||
if u, uerr := ctx.EntClient.User.Query().Where(user.IDEQ(claims.UserID)).Only(ctx0()); uerr == nil &&
|
||
u.ActiveToken != "" && u.ActiveToken != claims.SID {
|
||
failCode(w, http.StatusUnauthorized, 401, "账号已在其他地方登录,本会话已下线,请重新登录")
|
||
return
|
||
}
|
||
}
|
||
renewIfNearExpiry(ctx, w, claims)
|
||
r.Header.Set("X-Username", claims.Username)
|
||
r.Header.Set("X-Role", claims.Role)
|
||
r.Header.Set("X-UserID", strconv.Itoa(claims.UserID))
|
||
next.ServeHTTP(w, r)
|
||
})
|
||
}
|
||
}
|
||
|
||
// internalTokenInterceptor 项目间 API 写死 token 校验
|
||
func internalTokenInterceptor(ctx *svc.ServiceContext) func(next http.Handler) http.Handler {
|
||
return func(next http.Handler) http.Handler {
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
expect := ctx.Config.Internal.Token
|
||
got := r.Header.Get("X-API-TOKEN")
|
||
if expect != "" && got != expect {
|
||
failCode(w, http.StatusUnauthorized, 401, "内部接口 token 错误")
|
||
return
|
||
}
|
||
next.ServeHTTP(w, r)
|
||
})
|
||
}
|
||
}
|
||
|
||
// wrapInternal 组合内部 token 校验与 handler
|
||
func wrapInternal(ctx *svc.ServiceContext) func(h http.HandlerFunc) http.HandlerFunc {
|
||
return func(h http.HandlerFunc) http.HandlerFunc {
|
||
return internalTokenInterceptor(ctx)(h).ServeHTTP
|
||
}
|
||
}
|