feat(auth): 完整认证系统 — 注册/登录/JWT/路由(Task 4 + Task 5)
Task 4 — 认证服务层: - pkg/utils/password.go: bcrypt 密码加密与校验 - pkg/utils/jwt.go: Access/Refresh Token 生成与解析(jwt/v5@v5.2.1,兼容 Go 1.23) - app/dto/auth_dto.go: 认证相关请求/响应 DTO(含参数校验 binding tag) - app/auth/service/auth_service.go: 核心业务逻辑(注册、登录、管理员登录、Token 刷新、个人信息、改密码) - pkg/middleware/auth.go: JWT 认证中间件 + 角色权限检查中间件 Task 5 — Controller 与路由注册: - app/auth/controller/auth_controller.go: 前台认证接口(7 个 API) - app/auth/controller/admin_auth_controller.go: 后台管理认证接口 - app/auth/router.go: auth 模块路由定义(模块自包含) - router/router.go: 主路由汇总入口(仅做调度,不含具体路由定义) - cmd/server/main.go: 路由注册迁移到 router.Setup() 已验证全部接口:注册 ✓ 登录 ✓ 获取 profile ✓ 错误密码 ✓ 未认证拒绝 ✓ 非管理员拒绝 ✓ Made-with: Cursor
This commit is contained in:
129
backend/go-service/pkg/middleware/auth.go
Normal file
129
backend/go-service/pkg/middleware/auth.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/echochat/backend/config"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"github.com/echochat/backend/pkg/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
ContextKeyUserID = "user_id" // Context 中存储当前用户 ID 的 Key
|
||||
ContextKeyUsername = "username" // Context 中存储当前用户名的 Key
|
||||
ContextKeyRoles = "roles" // Context 中存储当前用户角色列表的 Key
|
||||
)
|
||||
|
||||
// JWTAuth JWT 认证中间件
|
||||
// 从 Authorization Header 中提取 Bearer Token,验证后将用户信息注入 Gin Context
|
||||
func JWTAuth(jwtCfg *config.JWTConfig) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
funcName := "middleware.JWTAuth"
|
||||
ctx := c.Request.Context()
|
||||
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
utils.ResponseUnauthorized(c, "缺少认证信息")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 提取 Bearer Token
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
|
||||
utils.ResponseUnauthorized(c, "认证格式错误,应为 Bearer {token}")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := parts[1]
|
||||
claims, err := utils.ParseToken(jwtCfg, tokenStr)
|
||||
if err != nil {
|
||||
logs.Warn(ctx, funcName, "Token 验证失败",
|
||||
zap.Error(err),
|
||||
zap.String("ip", c.ClientIP()),
|
||||
)
|
||||
utils.ResponseUnauthorized(c, "认证已过期或无效,请重新登录")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 验证 Token 类型(只允许 access token 访问接口)
|
||||
if claims.Subject != "access" {
|
||||
utils.ResponseUnauthorized(c, "无效的 Token 类型")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 将用户信息注入 Gin Context,供后续 Controller/Service 使用
|
||||
c.Set(ContextKeyUserID, claims.UserID)
|
||||
c.Set(ContextKeyUsername, claims.Username)
|
||||
c.Set(ContextKeyRoles, claims.Roles)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequireRole 角色权限检查中间件
|
||||
// 检查当前用户是否拥有指定角色之一(OR 逻辑),需在 JWTAuth 之后使用
|
||||
func RequireRole(roles ...string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
funcName := "middleware.RequireRole"
|
||||
ctx := c.Request.Context()
|
||||
|
||||
userRoles, exists := c.Get(ContextKeyRoles)
|
||||
if !exists {
|
||||
utils.ResponseForbidden(c, "无权限访问")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
roleList, ok := userRoles.([]string)
|
||||
if !ok {
|
||||
utils.ResponseForbidden(c, "无权限访问")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
for _, required := range roles {
|
||||
for _, userRole := range roleList {
|
||||
if userRole == required {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
userID, _ := c.Get(ContextKeyUserID)
|
||||
logs.Warn(ctx, funcName, "角色权限不足",
|
||||
zap.Any("user_id", userID),
|
||||
zap.Strings("required", roles),
|
||||
zap.Strings("actual", roleList),
|
||||
)
|
||||
utils.ResponseForbidden(c, "权限不足,需要角色: "+strings.Join(roles, " 或 "))
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
|
||||
// GetCurrentUserID 从 Gin Context 获取当前登录用户 ID
|
||||
// 供 Controller 层调用的便捷方法
|
||||
func GetCurrentUserID(c *gin.Context) (int64, bool) {
|
||||
val, exists := c.Get(ContextKeyUserID)
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
userID, ok := val.(int64)
|
||||
return userID, ok
|
||||
}
|
||||
|
||||
// GetCurrentUsername 从 Gin Context 获取当前登录用户名
|
||||
func GetCurrentUsername(c *gin.Context) (string, bool) {
|
||||
val, exists := c.Get(ContextKeyUsername)
|
||||
if !exists {
|
||||
return "", false
|
||||
}
|
||||
username, ok := val.(string)
|
||||
return username, ok
|
||||
}
|
||||
86
backend/go-service/pkg/utils/jwt.go
Normal file
86
backend/go-service/pkg/utils/jwt.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/echochat/backend/config"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Claims 自定义 JWT Claims,在标准 Claims 基础上扩展业务字段
|
||||
type Claims struct {
|
||||
UserID int64 `json:"user_id"` // 用户 ID
|
||||
Username string `json:"username"` // 用户名
|
||||
Roles []string `json:"roles"` // 用户角色代码列表
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
var (
|
||||
ErrTokenExpired = errors.New("token 已过期")
|
||||
ErrTokenInvalid = errors.New("token 无效")
|
||||
)
|
||||
|
||||
// GenerateToken 生成 Access Token
|
||||
// 包含 UserID、Username、Roles,有效期由配置中的 access_expire_min 决定
|
||||
func GenerateToken(cfg *config.JWTConfig, userID int64, username string, roles []string) (string, error) {
|
||||
expireTime := time.Now().Add(time.Duration(cfg.AccessExpireMin) * time.Minute)
|
||||
|
||||
claims := &Claims{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
Roles: roles,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expireTime),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
Issuer: cfg.Issuer,
|
||||
Subject: "access",
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(cfg.Secret))
|
||||
}
|
||||
|
||||
// GenerateRefreshToken 生成 Refresh Token
|
||||
// 仅包含 UserID,有效期由配置中的 refresh_expire_day 决定
|
||||
func GenerateRefreshToken(cfg *config.JWTConfig, userID int64) (string, error) {
|
||||
expireTime := time.Now().Add(time.Duration(cfg.RefreshExpireDay) * 24 * time.Hour)
|
||||
|
||||
claims := &Claims{
|
||||
UserID: userID,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expireTime),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
Issuer: cfg.Issuer,
|
||||
Subject: "refresh",
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(cfg.Secret))
|
||||
}
|
||||
|
||||
// ParseToken 解析并验证 JWT Token
|
||||
// 验证签名、过期时间、签发者,返回解析后的 Claims
|
||||
func ParseToken(cfg *config.JWTConfig, tokenStr string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, ErrTokenInvalid
|
||||
}
|
||||
return []byte(cfg.Secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
return nil, ErrTokenExpired
|
||||
}
|
||||
return nil, ErrTokenInvalid
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, ErrTokenInvalid
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
17
backend/go-service/pkg/utils/password.go
Normal file
17
backend/go-service/pkg/utils/password.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package utils
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
// HashPassword 使用 bcrypt 对明文密码进行加密
|
||||
// cost 使用默认值 10,在安全性和性能之间取得平衡
|
||||
func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
return string(bytes), err
|
||||
}
|
||||
|
||||
// CheckPassword 校验明文密码是否与 bcrypt 哈希匹配
|
||||
// 返回 true 表示密码正确,false 表示密码错误或哈希无效
|
||||
func CheckPassword(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
Reference in New Issue
Block a user