49 lines
1.1 KiB
Go
Executable File
49 lines
1.1 KiB
Go
Executable File
// internal/middleware/auth.go
|
|
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
)
|
|
|
|
type Claims struct {
|
|
UserID uint `json:"user_id"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
|
if tokenString == authHeader {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Bearer token is required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
claims := &Claims{}
|
|
|
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
|
|
return []byte(jwtSecret), nil
|
|
})
|
|
|
|
if err != nil || !token.Valid {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("userID", claims.ID) // 从token中解析出的用户ID
|
|
c.Next()
|
|
}
|
|
}
|