68 lines
1.8 KiB
Go
68 lines
1.8 KiB
Go
package test
|
|
|
|
import (
|
|
"RenewCMS/api/pkg/claims"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/go-chi/jwtauth/v5"
|
|
)
|
|
|
|
func requestWithJwtClaims(t *testing.T, token *jwtauth.JWTAuth, claimsToEncode map[string]any) *http.Request {
|
|
t.Helper()
|
|
_, tokenString, err := token.Encode(claimsToEncode)
|
|
if err != nil {
|
|
t.Fatalf("failed to encode jwt: %v", err)
|
|
}
|
|
decoded, err := token.Decode(tokenString)
|
|
if err != nil {
|
|
t.Fatalf("failed to decode jwt: %v", err)
|
|
}
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
return req.WithContext(jwtauth.NewContext(req.Context(), decoded, nil))
|
|
}
|
|
|
|
func TestClaimsTokenVersion(t *testing.T) {
|
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
|
|
|
t.Run("returns the numeric token_version claim", func(t *testing.T) {
|
|
req := requestWithJwtClaims(t, token, map[string]any{"user_id": uint32(7), "token_version": uint32(3)})
|
|
|
|
got, ok := claims.TokenVersion(req)
|
|
if !ok {
|
|
t.Fatalf("expected ok true")
|
|
}
|
|
if got != 3 {
|
|
t.Errorf("expected 3, got %d", got)
|
|
}
|
|
})
|
|
|
|
t.Run("returns ok false when the token_version key is missing", func(t *testing.T) {
|
|
req := requestWithJwtClaims(t, token, map[string]any{"user_id": uint32(7)})
|
|
|
|
_, ok := claims.TokenVersion(req)
|
|
if ok {
|
|
t.Errorf("expected ok false")
|
|
}
|
|
})
|
|
|
|
t.Run("returns ok false when token_version is not numeric", func(t *testing.T) {
|
|
req := requestWithJwtClaims(t, token, map[string]any{"user_id": uint32(7), "token_version": "0"})
|
|
|
|
_, ok := claims.TokenVersion(req)
|
|
if ok {
|
|
t.Errorf("expected ok false")
|
|
}
|
|
})
|
|
|
|
t.Run("returns ok false when there is no verified jwt in context", func(t *testing.T) {
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
|
|
_, ok := claims.TokenVersion(req)
|
|
if ok {
|
|
t.Errorf("expected ok false")
|
|
}
|
|
})
|
|
}
|