Add full refresh token and access token function

Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
2025-12-25 16:13:05 +08:00
parent 32a27d974a
commit 3a86d387bd
13 changed files with 274 additions and 195 deletions

57
middleware/jwt.go Normal file
View File

@@ -0,0 +1,57 @@
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",
})
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",
})
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.Next()
}
}