Files
billai/server/middleware/auth.go
cheliangzhao a2de8c5078 feat: implement WeChat cross-batch refund reconciliation and fix misc issues
WeChat cross-batch refund reconciliation:
- Add OriginalAmount field to CleanedBill for accurate cumulative refund math
- DeduplicateRawFile detects WeChat status-update rows (已退款/已全额退款) and
  emits WechatRefundUpdates for Go-side reconciliation (Scenario 1)
- WechatPy cleaner surfaces -退款 income rows with no same-batch expense match
  as unresolved_refunds for Go ReconcileRefund (Scenario 2)
- Add ReconcileWechatRefund to repository interface and MongoDB implementation
- upload.go step 15 iterates WechatRefundUpdates and reconciles against bills_cleaned

Bug fixes:
- ReviewStats: add nil repo check to prevent panic when DB is not connected
- JWT: remove hardcoded fallback secret; return 500/401 if JWTSecret not configured
- Remove unused parsePageParam dead code and its strconv import
- BillDetailDrawer: show 不计收支 amount in muted gray instead of red
- test_jd_cleaner.py: replace hardcoded D:\Projects\BillAI path with dynamic __file__ resolution

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 21:38:25 +08:00

82 lines
1.7 KiB
Go

package middleware
import (
"errors"
"net/http"
"strings"
"billai-server/config"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// Claims JWT claims (duplicated here to avoid cross-package import from handler).
type Claims struct {
Username string `json:"username"`
Name string `json:"name"`
Role string `json:"role"`
jwt.RegisteredClaims
}
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
tokenString := c.GetHeader("Authorization")
if tokenString == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "未提供 Token",
"code": "TOKEN_MISSING",
})
c.Abort()
return
}
if strings.HasPrefix(tokenString, "Bearer ") {
tokenString = strings.TrimPrefix(tokenString, "Bearer ")
}
secret := config.Global.JWTSecret
if secret == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "服务器 JWT 配置缺失",
"code": "TOKEN_INVALID",
})
c.Abort()
return
}
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Name}))
if err != nil || !token.Valid {
code := "TOKEN_INVALID"
message := "Token 无效"
if err != nil && errors.Is(err, jwt.ErrTokenExpired) {
code = "TOKEN_EXPIRED"
message = "Token 已过期"
}
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": message,
"code": code,
})
c.Abort()
return
}
if claims, ok := token.Claims.(*Claims); ok {
c.Set("user", gin.H{
"username": claims.Username,
"name": claims.Name,
"role": claims.Role,
})
}
c.Next()
}
}