forked from nixcn/nixcn-cms
96 lines
2.0 KiB
Go
96 lines
2.0 KiB
Go
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)
|
|
}
|
|
}
|