Files
billai/server/handler/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

198 lines
4.2 KiB
Go

package handler
import (
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"time"
"billai-server/config"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// LoginRequest 登录请求
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// LoginResponse 登录响应
type LoginResponse struct {
Token string `json:"token"`
User config.UserInfo `json:"user"`
}
// Claims JWT claims
type Claims struct {
Username string `json:"username"`
Name string `json:"name"`
Role string `json:"role"`
jwt.RegisteredClaims
}
// hashPassword 对密码进行 SHA-256 哈希
func hashPassword(password string) string {
hash := sha256.Sum256([]byte(password))
return hex.EncodeToString(hash[:])
}
// Login 用户登录
func Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
"error": "请输入用户名和密码",
})
return
}
// 查找用户
var foundUser *config.UserInfo
for _, user := range config.Global.Users {
if user.Username == req.Username {
foundUser = &user
break
}
}
if foundUser == nil {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "用户名或密码错误",
})
return
}
// 验证密码(支持明文比较和哈希比较)
passwordMatch := foundUser.Password == req.Password ||
foundUser.Password == hashPassword(req.Password)
if !passwordMatch {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "用户名或密码错误",
})
return
}
// 生成 JWT Token
expiry := config.Global.TokenExpiry
if expiry <= 0 {
expiry = 168 // 默认 7 天
}
claims := &Claims{
Username: foundUser.Username,
Name: foundUser.Name,
Role: foundUser.Role,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expiry) * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
Subject: foundUser.Username,
},
}
secret := config.Global.JWTSecret
if secret == "" {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"error": "服务器 JWT 配置缺失",
})
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"error": "生成 Token 失败",
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": LoginResponse{
Token: tokenString,
User: config.UserInfo{
Username: foundUser.Username,
Name: foundUser.Name,
Email: foundUser.Email,
Role: foundUser.Role,
},
},
})
}
// ValidateToken 验证 Token
func ValidateToken(c *gin.Context) {
tokenString := c.GetHeader("Authorization")
if tokenString == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "未提供 Token",
"code": "TOKEN_MISSING",
})
return
}
// 移除 "Bearer " 前缀
if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
tokenString = tokenString[7:]
}
secret := config.Global.JWTSecret
if secret == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "服务器 JWT 配置缺失",
"code": "TOKEN_INVALID",
})
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,
})
return
}
claims, ok := token.Claims.(*Claims)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "Token 解析失败",
"code": "TOKEN_INVALID",
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": config.UserInfo{
Username: claims.Username,
Name: claims.Name,
Role: claims.Role,
},
})
}