Files
jiu/backend/internal/middleware/license_guard.go
T
wangjia ebf79d0355 feat: LicenseGuard 中间件 + Flutter license model/repo (21D+21E)
21D — 后端:
- Claims 新增 LicenseExpiresAt (*int64 unix 秒),写入 JWT 避免每次查库
- middleware/license_guard.go: CalcLicensePhase / LicenseGuard / GetLicensePhase
  - grace(0-7d): 允许通行
  - readonly(7-15d): 拦截非 GET 写操作 → 403
  - locked(15d+): 全部拦截 → 403
- auth.go: issueTokens 在 JWT 中嵌入 license expires_at;Login 检查 locked 拒绝登录
- router: license/* 路由豁免 LicenseGuard(锁定时仍可激活/查状态)

21E — Flutter 前端:
- models/license.dart: 新 LicenseInfo,含 phase/maxDevices,去掉旧 activatedAt
- core/device/device_id.dart: 持久化 UUID-v4 作为设备 ID(SharedPreferences)
- repositories/license_repository.dart: getInfo/activate/deactivate,激活时携带设备信息
- providers/license_provider.dart: 改接 LicenseRepository
- settings_screen.dart: activatedAt 改为显示 maxDevices

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 00:52:07 +08:00

78 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middleware
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
)
const (
PhaseNormal = "normal"
PhaseGrace = "grace" // expired 07 days: writable, show banner
PhaseReadOnly = "readonly" // expired 715 days: read-only
PhaseLocked = "locked" // expired 15+ days: no login
)
var (
graceWindow = 7 * 24 * time.Hour
readOnlyWindow = 15 * 24 * time.Hour
)
// CalcLicensePhase computes the degradation phase based on expires_at.
// nil expiresAt = perpetual license = normal.
func CalcLicensePhase(expiresAt *time.Time) string {
if expiresAt == nil {
return PhaseNormal
}
elapsed := time.Since(*expiresAt)
if elapsed <= 0 {
return PhaseNormal
}
if elapsed <= graceWindow {
return PhaseGrace
}
if elapsed <= readOnlyWindow {
return PhaseReadOnly
}
return PhaseLocked
}
// GetLicensePhase returns the current phase for the authenticated request.
func GetLicensePhase(c *gin.Context) string {
v, _ := c.Get(CtxLicenseExpiresAt)
ptr, _ := v.(*int64)
if ptr == nil {
return PhaseNormal
}
t := time.Unix(*ptr, 0)
return CalcLicensePhase(&t)
}
// LicenseGuard blocks write operations when the shop's license is expired (readonly/locked).
// License routes (/license/*) must be mounted outside this middleware so users can
// view status and activate a new key even when locked.
func LicenseGuard() gin.HandlerFunc {
return func(c *gin.Context) {
phase := GetLicensePhase(c)
switch phase {
case PhaseLocked:
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "授权已锁定,请续费或激活新授权码",
"phase": PhaseLocked,
})
case PhaseReadOnly:
if c.Request.Method != http.MethodGet {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "授权已过期,当前为只读模式",
"phase": PhaseReadOnly,
})
return
}
c.Next()
default:
c.Next()
}
}
}