Add jwt crypto module, support unit test for config module

Signed-off-by:  Asai Neko<sugar@sne.moe>
This commit is contained in:
2025-12-23 18:11:31 +08:00
parent 1505783c62
commit d314942c08
13 changed files with 212 additions and 11 deletions

View File

@@ -0,0 +1,77 @@
package jwt
import (
"net/http"
"nixcn-cms/config"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
type Claims struct {
UserID uuid.UUID `json:"user_id"`
jwt.RegisteredClaims
}
func JWTAuth() gin.HandlerFunc {
var JwtSecret = []byte(config.Get("server.jwt_secret").(string))
return func(c *gin.Context) {
auth := c.GetHeader("Authorization")
if auth == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "missing Authorization header",
})
return
}
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]
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return JwtSecret, nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "invalid or expired token",
})
return
}
claims, ok := token.Claims.(*Claims)
if !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "invalid token claims",
})
return
}
c.Set("user_id", claims.UserID)
c.Next()
}
}
func GenerateToken(userID uuid.UUID, application string) (string, error) {
var JwtSecret = []byte(config.Get("server.jwt_secret").(string))
claims := Claims{
UserID: userID,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
Issuer: application,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(JwtSecret)
}

View File

@@ -0,0 +1,95 @@
package jwt
import (
"net/http"
"net/http/httptest"
"nixcn-cms/config"
"os"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
func init() {
os.Setenv("GO_ENV", "test")
config.Init()
}
func generateTestToken(userID uuid.UUID, expire time.Duration) string {
var JwtSecret = []byte(config.Get("server.jwt_secret").(string))
claims := Claims{
UserID: userID,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expire)),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenStr, _ := token.SignedString(JwtSecret)
return tokenStr
}
func TestJWTAuth_MissingToken(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(JWTAuth())
r.GET("/test", func(c *gin.Context) {
c.JSON(200, gin.H{"ok": true})
})
req := httptest.NewRequest(http.MethodGet, "/test", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", w.Code)
}
}
func TestJWTAuth_InvalidToken(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(JWTAuth())
r.GET("/test", func(c *gin.Context) {
c.JSON(200, gin.H{"ok": true})
})
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("Authorization", "Bearer invalid.token.here")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", w.Code)
}
}
func TestJWTAuth_ValidToken(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(JWTAuth())
r.GET("/test", func(c *gin.Context) {
userID := c.GetUint("user_id")
c.JSON(200, gin.H{
"user_id": userID,
})
})
uuid, _ := uuid.NewUUID()
token := generateTestToken(uuid, time.Hour)
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("Authorization", "Bearer "+token)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
}