git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/jst/jst_test.go (about)

     1  package jst_test
     2  
     3  import (
     4  	"crypto/rand"
     5  	"testing"
     6  	"time"
     7  
     8  	"git.sr.ht/~pingoo/stdx/jst"
     9  )
    10  
    11  func TestHelloWorld(t *testing.T) {
    12  	type payloadHelloWorld struct {
    13  		Message string `json:"message"`
    14  	}
    15  
    16  	key := make([]byte, 32)
    17  	_, err := rand.Read(key)
    18  	if err != nil {
    19  		t.Error(err)
    20  		return
    21  	}
    22  
    23  	keys := map[string][]byte{
    24  		"default": key,
    25  	}
    26  	keysProvider := jst.NewKeyProviderMemory(keys)
    27  	jstProvider, err := jst.NewProvider(keysProvider, "default")
    28  	if err != nil {
    29  		t.Error(err)
    30  		return
    31  	}
    32  
    33  	payload := payloadHelloWorld{Message: "Hello World!"}
    34  	expiresAt := time.Date(3000, 12, 31, 23, 59, 59, 0, time.UTC)
    35  	token, err := jstProvider.IssueToken(payload, &expiresAt, nil)
    36  	if err != nil {
    37  		t.Error(err)
    38  		return
    39  	}
    40  
    41  	var decodedPayload payloadHelloWorld
    42  	decodedHeader, err := jstProvider.VerifyToken(token, &decodedPayload)
    43  	if err != nil {
    44  		t.Errorf("verifyToken (%s): %s", token, err)
    45  		return
    46  	}
    47  
    48  	if decodedHeader.ExpiresAt == nil {
    49  		t.Error("expires_at is null")
    50  		return
    51  	}
    52  	if !decodedHeader.ExpiresAt.Equal(expiresAt) {
    53  		t.Errorf("decoded_header.expires_at (%s) | expires_at (%s)", decodedHeader.ExpiresAt, expiresAt)
    54  		return
    55  	}
    56  
    57  	if decodedPayload.Message != payload.Message {
    58  		t.Errorf("decoded_payload.message (%s) | payload.message (%s)", decodedPayload.Message, payload.Message)
    59  		return
    60  	}
    61  }