Modify jwt middleware logic

Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
2026-01-02 12:36:07 +08:00
parent 3d685b5a86
commit cbec9bf2b3
7 changed files with 85 additions and 50 deletions

View File

@@ -1,57 +1,30 @@
package middleware
import (
"net/http"
"strings"
"nixcn-cms/internal/cryptography"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/spf13/viper"
)
func JWTAuth() gin.HandlerFunc {
jwtSecret := []byte(viper.GetString("secrets.jwt_secret"))
return func(c *gin.Context) {
auth := c.GetHeader("Authorization")
if auth == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "missing Authorization header",
})
token := new(cryptography.Token)
uid, err := token.HeaderVerify(auth)
if err != nil {
c.JSON(401, gin.H{"status": err.Error()})
return
}
// Split header to 2
parts := strings.SplitN(auth, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "invalid Authorization header format",
})
if err == nil && uid == "" {
c.Set("user_id", "")
c.Next()
return
}
tokenStr := parts[1]
// Verify access token
claims := &cryptography.JwtClaims{}
token, err := jwt.ParseWithClaims(
tokenStr,
claims,
func(token *jwt.Token) (any, error) {
return jwtSecret, nil
},
)
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "invalid or expired token",
})
return
}
c.Set("user_id", claims.UserID)
c.Set("user_id", uid)
c.Next()
}
}