2023-03-14 17:39:40 +07:00
|
|
|
package token
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"git.nochill.in/nochill/naice_pos/util"
|
2023-03-15 15:00:36 +07:00
|
|
|
"github.com/google/uuid"
|
2023-03-14 17:39:40 +07:00
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
2023-03-15 15:00:36 +07:00
|
|
|
var merchantID = uuid.New().String()
|
|
|
|
|
2023-03-14 17:39:40 +07:00
|
|
|
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)
|
|
|
|
|
2023-03-16 12:21:41 +07:00
|
|
|
token, payload, err := maker.CreateToken(email, merchantID, duration)
|
2023-03-14 17:39:40 +07:00
|
|
|
require.NoError(t, err)
|
|
|
|
require.NotEmpty(t, token)
|
2023-03-16 12:21:41 +07:00
|
|
|
require.NotEmpty(t, payload)
|
2023-03-14 17:39:40 +07:00
|
|
|
|
2023-03-16 12:21:41 +07:00
|
|
|
payload, err = maker.VerifyToken(token)
|
2023-03-14 17:39:40 +07:00
|
|
|
require.NoError(t, err)
|
|
|
|
require.NotEmpty(t, payload)
|
|
|
|
|
|
|
|
require.NotZero(t, payload.ID)
|
|
|
|
require.Equal(t, email, payload.Email)
|
|
|
|
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)
|
|
|
|
|
2023-03-16 12:21:41 +07:00
|
|
|
token, payload, err := maker.CreateToken(util.RandomEmail(), merchantID, -time.Minute)
|
2023-03-14 17:39:40 +07:00
|
|
|
require.NoError(t, err)
|
|
|
|
require.NotEmpty(t, token)
|
2023-03-16 12:21:41 +07:00
|
|
|
require.NotEmpty(t, payload)
|
2023-03-14 17:39:40 +07:00
|
|
|
|
2023-03-16 12:21:41 +07:00
|
|
|
payload, err = maker.VerifyToken(token)
|
2023-03-14 17:39:40 +07:00
|
|
|
require.Error(t, err)
|
|
|
|
require.EqualError(t, err, ErrExpiredToken.Error())
|
|
|
|
require.Nil(t, payload)
|
|
|
|
}
|