feat: 添加用户登录认证功能
- 新增登录页面(使用 shadcn-svelte 组件) - 后端添加 JWT 认证 API (/api/auth/login, /api/auth/validate) - 用户账号通过 server/config.yaml 配置 - 前端路由保护(未登录跳转登录页) - 侧边栏显示当前用户信息 - 支持退出登录功能
This commit is contained in:
@@ -39,3 +39,22 @@ mongodb:
|
||||
# 清洗后数据集合
|
||||
cleaned: bills_cleaned
|
||||
|
||||
# 用户认证配置
|
||||
auth:
|
||||
# JWT 密钥(生产环境请使用更复杂的密钥)
|
||||
jwt_secret: "billai-secret-key-2026"
|
||||
# Token 过期时间(小时)
|
||||
token_expiry: 168 # 7天
|
||||
# 用户列表
|
||||
users:
|
||||
- username: admin
|
||||
password: admin123
|
||||
name: 管理员
|
||||
email: admin@billai.com
|
||||
role: admin
|
||||
- username: user
|
||||
password: user123
|
||||
name: 普通用户
|
||||
email: user@billai.com
|
||||
role: user
|
||||
|
||||
|
||||
@@ -28,12 +28,26 @@ type Config struct {
|
||||
MongoDatabase string // 数据库名称
|
||||
MongoRawCollection string // 原始数据集合名称
|
||||
MongoCleanedCollection string // 清洗后数据集合名称
|
||||
|
||||
// 认证配置
|
||||
JWTSecret string // JWT 密钥
|
||||
TokenExpiry int // Token 过期时间(小时)
|
||||
Users []UserInfo // 用户列表
|
||||
}
|
||||
|
||||
// UserInfo 用户信息
|
||||
type UserInfo struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"-"` // 不序列化密码
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
// configFile YAML 配置文件结构
|
||||
type configFile struct {
|
||||
Version string `yaml:"version"`
|
||||
Server struct {
|
||||
Server struct {
|
||||
Port int `yaml:"port"`
|
||||
} `yaml:"server"`
|
||||
Python struct {
|
||||
@@ -56,6 +70,17 @@ type configFile struct {
|
||||
Cleaned string `yaml:"cleaned"`
|
||||
} `yaml:"collections"`
|
||||
} `yaml:"mongodb"`
|
||||
Auth struct {
|
||||
JWTSecret string `yaml:"jwt_secret"`
|
||||
TokenExpiry int `yaml:"token_expiry"` // 小时
|
||||
Users []struct {
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
Name string `yaml:"name"`
|
||||
Email string `yaml:"email"`
|
||||
Role string `yaml:"role"`
|
||||
} `yaml:"users"`
|
||||
} `yaml:"auth"`
|
||||
}
|
||||
|
||||
// Global 全局配置实例
|
||||
@@ -186,6 +211,23 @@ func Load() {
|
||||
if cfg.MongoDB.Collections.Cleaned != "" {
|
||||
Global.MongoCleanedCollection = cfg.MongoDB.Collections.Cleaned
|
||||
}
|
||||
// 认证配置
|
||||
if cfg.Auth.JWTSecret != "" {
|
||||
Global.JWTSecret = cfg.Auth.JWTSecret
|
||||
}
|
||||
if cfg.Auth.TokenExpiry > 0 {
|
||||
Global.TokenExpiry = cfg.Auth.TokenExpiry
|
||||
}
|
||||
// 用户列表
|
||||
for _, u := range cfg.Auth.Users {
|
||||
Global.Users = append(Global.Users, UserInfo{
|
||||
Username: u.Username,
|
||||
Password: u.Password,
|
||||
Name: u.Name,
|
||||
Email: u.Email,
|
||||
Role: u.Role,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 环境变量覆盖
|
||||
|
||||
@@ -17,6 +17,7 @@ require (
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
|
||||
github.com/golang/snappy v0.0.1 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.13.6 // indirect
|
||||
|
||||
@@ -23,6 +23,8 @@ github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg
|
||||
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
|
||||
177
server/handler/auth.go
Normal file
177
server/handler/auth.go
Normal file
@@ -0,0 +1,177 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"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 == "" {
|
||||
secret = "billai-default-secret"
|
||||
}
|
||||
|
||||
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",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 移除 "Bearer " 前缀
|
||||
if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
|
||||
tokenString = tokenString[7:]
|
||||
}
|
||||
|
||||
secret := config.Global.JWTSecret
|
||||
if secret == "" {
|
||||
secret = "billai-default-secret"
|
||||
}
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(secret), nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"success": false,
|
||||
"error": "Token 无效或已过期",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"success": false,
|
||||
"error": "Token 解析失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": config.UserInfo{
|
||||
Username: claims.Username,
|
||||
Name: claims.Name,
|
||||
Role: claims.Role,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -202,7 +202,7 @@ func MonthlyStats(c *gin.Context) {
|
||||
// ReviewStats 获取待复核数据统计
|
||||
func ReviewStats(c *gin.Context) {
|
||||
repo := repository.GetRepository()
|
||||
|
||||
|
||||
// 从MongoDB查询所有需要复核的账单
|
||||
bills, err := repo.GetBillsNeedReview()
|
||||
if err != nil {
|
||||
|
||||
@@ -30,9 +30,9 @@ type CreateManualBillsRequest struct {
|
||||
|
||||
// CreateManualBillsResponse 批量创建手动账单响应
|
||||
type CreateManualBillsResponse struct {
|
||||
Result bool `json:"result"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Data *CreateManualBillsData `json:"data,omitempty"`
|
||||
Result bool `json:"result"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Data *CreateManualBillsData `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// CreateManualBillsData 批量创建手动账单数据
|
||||
|
||||
@@ -41,6 +41,10 @@ func healthCheck(version string) gin.HandlerFunc {
|
||||
func setupAPIRoutes(r *gin.Engine) {
|
||||
api := r.Group("/api")
|
||||
{
|
||||
// 认证相关(无需登录)
|
||||
api.POST("/auth/login", handler.Login)
|
||||
api.GET("/auth/validate", handler.ValidateToken)
|
||||
|
||||
// 账单上传
|
||||
api.POST("/upload", handler.Upload)
|
||||
|
||||
@@ -49,13 +53,13 @@ func setupAPIRoutes(r *gin.Engine) {
|
||||
|
||||
// 账单查询
|
||||
api.GET("/bills", handler.ListBills)
|
||||
|
||||
|
||||
// 手动创建账单
|
||||
api.POST("/bills/manual", handler.CreateManualBills)
|
||||
|
||||
|
||||
// 月度统计(全部数据)
|
||||
api.GET("/monthly-stats", handler.MonthlyStats)
|
||||
|
||||
|
||||
// 待复核数据统计
|
||||
api.GET("/review-stats", handler.ReviewStats)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user