feat: 完善后端脚手架基础能力
This commit is contained in:
+106
-90
@@ -1,142 +1,158 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skeleton/database"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var (
|
||||
jwtSecret []byte
|
||||
jwtIssuer string
|
||||
expireHours int
|
||||
const (
|
||||
TokenTypeAccess = "access"
|
||||
TokenTypeRefresh = "refresh"
|
||||
)
|
||||
|
||||
var (
|
||||
jwtSecret []byte
|
||||
jwtIssuer string
|
||||
accessExpire time.Duration
|
||||
refreshExpire time.Duration
|
||||
)
|
||||
|
||||
// JWTClaims JWT声明结构
|
||||
type JWTClaims struct {
|
||||
UserID int `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
UserID int `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
TokenType string `json:"token_type"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// InitJWT 初始化JWT配置
|
||||
func InitJWT(secret string, expire int, issuer string) {
|
||||
type TokenPair struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type" example:"Bearer"`
|
||||
ExpiresIn int64 `json:"expires_in" example:"900"`
|
||||
}
|
||||
|
||||
func InitJWT(secret string, accessMinutes, refreshHours int, issuer string) {
|
||||
jwtSecret = []byte(secret)
|
||||
expireHours = expire
|
||||
accessExpire = time.Duration(accessMinutes) * time.Minute
|
||||
refreshExpire = time.Duration(refreshHours) * time.Hour
|
||||
jwtIssuer = issuer
|
||||
}
|
||||
|
||||
// GenerateToken 生成JWT token
|
||||
func GenerateToken(userID int, username string) (string, error) {
|
||||
claims := JWTClaims{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expireHours) * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
Issuer: jwtIssuer,
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(jwtSecret)
|
||||
return generateToken(userID, username, TokenTypeAccess, accessExpire)
|
||||
}
|
||||
|
||||
// ParseToken 解析JWT token
|
||||
func ParseToken(tokenString string) (*JWTClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return jwtSecret, nil
|
||||
})
|
||||
func GenerateTokenPair(userID int, username string) (TokenPair, error) {
|
||||
access, err := generateToken(userID, username, TokenTypeAccess, accessExpire)
|
||||
if err != nil {
|
||||
return TokenPair{}, err
|
||||
}
|
||||
refresh, err := generateToken(userID, username, TokenTypeRefresh, refreshExpire)
|
||||
if err != nil {
|
||||
return TokenPair{}, err
|
||||
}
|
||||
return TokenPair{
|
||||
AccessToken: access, RefreshToken: refresh,
|
||||
TokenType: "Bearer", ExpiresIn: int64(accessExpire.Seconds()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func generateToken(userID int, username, tokenType string, duration time.Duration) (string, error) {
|
||||
now := time.Now()
|
||||
claims := JWTClaims{
|
||||
UserID: userID, Username: username, TokenType: tokenType,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ID: randomTokenID(), ExpiresAt: jwt.NewNumericDate(now.Add(duration)),
|
||||
IssuedAt: jwt.NewNumericDate(now), NotBefore: jwt.NewNumericDate(now), Issuer: jwtIssuer,
|
||||
},
|
||||
}
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(jwtSecret)
|
||||
}
|
||||
|
||||
func randomTokenID() string {
|
||||
value := make([]byte, 16)
|
||||
if _, err := rand.Read(value); err != nil {
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
return hex.EncodeToString(value)
|
||||
}
|
||||
|
||||
func ParseToken(tokenString string) (*JWTClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(*jwt.Token) (interface{}, error) {
|
||||
return jwtSecret, nil
|
||||
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}), jwt.WithIssuer(jwtIssuer))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
|
||||
return claims, nil
|
||||
claims, ok := token.Claims.(*JWTClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, jwt.ErrTokenInvalidClaims
|
||||
}
|
||||
|
||||
return nil, jwt.ErrTokenInvalidClaims
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// JWTAuth JWT认证中间件
|
||||
func JWTAuth() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 从Header获取token
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
Logger.Warn("JWT认证失败:缺少Authorization头部",
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.String("client_ip", c.ClientIP()),
|
||||
)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 401,
|
||||
"message": "缺少认证token",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Bearer token格式检查
|
||||
if !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
Logger.Warn("JWT认证失败:token格式错误",
|
||||
zap.String("auth_header", authHeader),
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.String("client_ip", c.ClientIP()),
|
||||
)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 401,
|
||||
"message": "token格式错误",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
|
||||
// 解析token
|
||||
claims, err := ParseToken(tokenString)
|
||||
tokenString, err := BearerToken(c.GetHeader("Authorization"))
|
||||
if err != nil {
|
||||
Logger.Warn("JWT认证失败:token解析错误",
|
||||
zap.Error(err),
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.String("client_ip", c.ClientIP()),
|
||||
)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 401,
|
||||
"message": "token无效或已过期",
|
||||
})
|
||||
c.Abort()
|
||||
abortUnauthorized(c, err.Error())
|
||||
return
|
||||
}
|
||||
claims, err := ParseToken(tokenString)
|
||||
if err != nil || claims.TokenType != TokenTypeAccess {
|
||||
abortUnauthorized(c, "token 无效或已过期")
|
||||
return
|
||||
}
|
||||
revoked, err := database.IsTokenRevoked(c.Request.Context(), claims.ID)
|
||||
if err != nil || revoked {
|
||||
abortUnauthorized(c, "token 已撤销")
|
||||
return
|
||||
}
|
||||
|
||||
// 将用户信息存储到上下文
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("username", claims.Username)
|
||||
|
||||
Logger.Debug("JWT认证成功",
|
||||
zap.Int("user_id", claims.UserID),
|
||||
zap.String("username", claims.Username),
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
)
|
||||
|
||||
c.Set("jwt_claims", claims)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// GetCurrentUser 从上下文获取当前用户信息
|
||||
func BearerToken(header string) (string, error) {
|
||||
parts := strings.Fields(header)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
return "", fmt.Errorf("缺少或格式错误的认证 token")
|
||||
}
|
||||
return parts[1], nil
|
||||
}
|
||||
|
||||
func abortUnauthorized(c *gin.Context, message string) {
|
||||
Logger.Warn("JWT认证失败", zap.String("message", message), zap.String("path", c.Request.URL.Path))
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": 401, "message": message, "data": nil})
|
||||
}
|
||||
|
||||
func GetCurrentUser(c *gin.Context) (int, string, bool) {
|
||||
userID, userExists := c.Get("user_id")
|
||||
username, nameExists := c.Get("username")
|
||||
|
||||
if !userExists || !nameExists {
|
||||
return 0, "", false
|
||||
}
|
||||
|
||||
return userID.(int), username.(string), true
|
||||
}
|
||||
|
||||
func GetCurrentClaims(c *gin.Context) (*JWTClaims, bool) {
|
||||
value, ok := c.Get("jwt_claims")
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
claims, ok := value.(*JWTClaims)
|
||||
return claims, ok
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package middlewares
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGenerateTokenPair(t *testing.T) {
|
||||
InitJWT("test-secret", 15, 24, "test-issuer")
|
||||
pair, err := GenerateTokenPair(42, "demo")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
access, err := ParseToken(pair.AccessToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refresh, err := ParseToken(pair.RefreshToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if access.TokenType != TokenTypeAccess || refresh.TokenType != TokenTypeRefresh {
|
||||
t.Fatalf("unexpected token types: %s, %s", access.TokenType, refresh.TokenType)
|
||||
}
|
||||
if access.ID == "" || refresh.ID == "" || access.ID == refresh.ID {
|
||||
t.Fatal("tokens must have distinct IDs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerToken(t *testing.T) {
|
||||
if token, err := BearerToken("Bearer abc"); err != nil || token != "abc" {
|
||||
t.Fatalf("BearerToken() = %q, %v", token, err)
|
||||
}
|
||||
if _, err := BearerToken("abc"); err == nil {
|
||||
t.Fatal("BearerToken() accepted malformed header")
|
||||
}
|
||||
}
|
||||
+22
-1
@@ -93,7 +93,19 @@ func InitLogger(cfg *config.LoggerConfig) error {
|
||||
|
||||
// GinLogger 返回gin的日志中间件
|
||||
func GinLogger() gin.HandlerFunc {
|
||||
return gin.LoggerWithWriter(os.Stdout)
|
||||
return func(c *gin.Context) {
|
||||
started := time.Now()
|
||||
c.Next()
|
||||
requestID, _ := c.Get("request_id")
|
||||
Logger.Info("HTTP请求",
|
||||
zap.String("request_id", stringValue(requestID)),
|
||||
zap.String("method", c.Request.Method),
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.Int("status_code", c.Writer.Status()),
|
||||
zap.Duration("latency", time.Since(started)),
|
||||
zap.String("client_ip", c.ClientIP()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// GinRecovery 返回gin的恢复中间件
|
||||
@@ -108,7 +120,9 @@ func ErrorLogging() gin.HandlerFunc {
|
||||
|
||||
// 记录错误状态码的响应
|
||||
if c.Writer.Status() >= 400 {
|
||||
requestID, _ := c.Get("request_id")
|
||||
Logger.Warn("HTTP错误响应",
|
||||
zap.String("request_id", stringValue(requestID)),
|
||||
zap.String("method", c.Request.Method),
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.String("client_ip", c.ClientIP()),
|
||||
@@ -119,6 +133,13 @@ func ErrorLogging() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func stringValue(value interface{}) string {
|
||||
if text, ok := value.(string); ok {
|
||||
return text
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Sync 同步日志缓冲区
|
||||
func Sync() {
|
||||
if Logger != nil {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
var (
|
||||
httpRequests = prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "skeleton_http_requests_total",
|
||||
Help: "Total number of HTTP requests.",
|
||||
}, []string{"method", "route", "status"})
|
||||
httpDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "skeleton_http_request_duration_seconds",
|
||||
Help: "HTTP request latency in seconds.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"method", "route", "status"})
|
||||
)
|
||||
|
||||
func init() {
|
||||
prometheus.MustRegister(httpRequests, httpDuration)
|
||||
}
|
||||
|
||||
func Metrics() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
started := time.Now()
|
||||
c.Next()
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
status := strconv.Itoa(c.Writer.Status())
|
||||
httpRequests.WithLabelValues(c.Request.Method, route, status).Inc()
|
||||
httpDuration.WithLabelValues(c.Request.Method, route, status).Observe(time.Since(started).Seconds())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const RequestIDHeader = "X-Request-ID"
|
||||
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
requestID := c.GetHeader(RequestIDHeader)
|
||||
if requestID == "" {
|
||||
value := make([]byte, 16)
|
||||
if _, err := rand.Read(value); err == nil {
|
||||
requestID = hex.EncodeToString(value)
|
||||
}
|
||||
}
|
||||
c.Set("request_id", requestID)
|
||||
c.Header(RequestIDHeader, requestID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user