67 lines
2.2 KiB
Go
67 lines
2.2 KiB
Go
package domain
|
|
|
|
import (
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func testTokenHash(t *testing.T) SecretTokenHash {
|
|
t.Helper()
|
|
token, err := NewSecretToken()
|
|
if err != nil {
|
|
t.Fatalf("NewSecretToken() error = %v", err)
|
|
}
|
|
return token.Hash()
|
|
}
|
|
|
|
func TestNewEmailTokenSetsExpiryFromLifetime(t *testing.T) {
|
|
input := NewEmailTokenInput{
|
|
UserID: uuid.New(),
|
|
Purpose: EmailTokenPurposeEmailVerification,
|
|
TokenHash: testTokenHash(t),
|
|
RegistrationVersion: 3,
|
|
IssuedAt: testRegisteredAt,
|
|
Lifetime: 24 * time.Hour,
|
|
}
|
|
token, err := NewEmailToken(input)
|
|
if err != nil {
|
|
t.Fatalf("NewEmailToken() error = %v", err)
|
|
}
|
|
if token.ID.Version() != 7 || token.UserID != input.UserID || token.TokenHash != input.TokenHash ||
|
|
token.RegistrationVersion != 3 || !token.CreatedAt.Equal(testRegisteredAt) ||
|
|
!token.ExpiresAt.Equal(testRegisteredAt.Add(24*time.Hour)) || token.ConsumedAt != nil || token.InvalidatedAt != nil {
|
|
t.Fatalf("NewEmailToken() = %+v", token)
|
|
}
|
|
}
|
|
|
|
func TestNewEmailTokenRejectsInvalidInput(t *testing.T) {
|
|
valid := NewEmailTokenInput{
|
|
UserID: uuid.New(),
|
|
Purpose: EmailTokenPurposeEmailVerification,
|
|
TokenHash: testTokenHash(t),
|
|
RegistrationVersion: 1,
|
|
IssuedAt: testRegisteredAt,
|
|
Lifetime: time.Hour,
|
|
}
|
|
tests := map[string]func(*NewEmailTokenInput){
|
|
"nil user": func(input *NewEmailTokenInput) { input.UserID = uuid.Nil },
|
|
"unknown purpose": func(input *NewEmailTokenInput) { input.Purpose = "something_else" },
|
|
"zero hash": func(input *NewEmailTokenInput) { input.TokenHash = SecretTokenHash{} },
|
|
"zero version": func(input *NewEmailTokenInput) { input.RegistrationVersion = 0 },
|
|
"zero issue time": func(input *NewEmailTokenInput) { input.IssuedAt = time.Time{} },
|
|
"non-positive lifetime": func(input *NewEmailTokenInput) { input.Lifetime = 0 },
|
|
}
|
|
for name, mutate := range tests {
|
|
t.Run(name, func(t *testing.T) {
|
|
input := valid
|
|
mutate(&input)
|
|
if _, err := NewEmailToken(input); !errors.Is(err, ErrInvalidEmailToken) {
|
|
t.Fatalf("NewEmailToken() error = %v, want ErrInvalidEmailToken", err)
|
|
}
|
|
})
|
|
}
|
|
}
|