hiling_go/util/token/paseto_test.go

53 lines
1.3 KiB
Go
Raw Permalink Normal View History

2023-09-08 22:25:22 +07:00
package token
import (
"math/rand"
"testing"
"time"
"git.nochill.in/nochill/hiling_go/util"
"github.com/stretchr/testify/require"
)
var userID = rand.Intn(10)
func TestPasetoMaker(t *testing.T) {
maker, err := NewPasetoMaker(util.RandomString(32))
require.NoError(t, err)
email := util.RandomEmail()
duration := time.Minute
issuedAt := time.Now()
expiredAt := issuedAt.Add(duration)
token, payload, err := maker.CreateToken(email, userID, duration)
require.NoError(t, err)
require.NotEmpty(t, token)
require.NotEmpty(t, payload)
payload, err = maker.VerifyToken(token)
require.NoError(t, err)
require.NotEmpty(t, payload)
// require.NotZero(t, payload.ID)
2023-09-21 21:38:41 +07:00
require.Equal(t, email, payload.Username)
2023-09-08 22:25:22 +07:00
require.WithinDuration(t, issuedAt, payload.IssuedAt, time.Second)
require.WithinDuration(t, expiredAt, payload.ExpiredAt, time.Second)
}
func TestExpiredPasetoToken(t *testing.T) {
maker, err := NewPasetoMaker(util.RandomString(32))
require.NoError(t, err)
token, payload, err := maker.CreateToken(util.RandomEmail(), userID, -time.Minute)
require.NoError(t, err)
require.NotEmpty(t, token)
require.NotEmpty(t, payload)
payload, err = maker.VerifyToken(token)
require.Error(t, err)
require.EqualError(t, err, ErrExpiredToken.Error())
require.Nil(t, payload)
}