All checks were successful
Server Check Build (NixCN CMS) TeamCity build finished
Signed-off-by: Asai Neko <sugar@sne.moe>
82 lines
1.8 KiB
Go
82 lines
1.8 KiB
Go
package authcode
|
||
|
||
import (
|
||
"context"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/stretchr/testify/assert"
|
||
"github.com/stretchr/testify/require"
|
||
"nixcn-cms/testutil"
|
||
)
|
||
|
||
func TestNewAuthCode(t *testing.T) {
|
||
mr := testutil.Setup(t)
|
||
_ = mr
|
||
|
||
ctx := context.Background()
|
||
code, err := NewAuthCode(ctx, "client-1", "user@example.com")
|
||
require.NoError(t, err)
|
||
assert.NotEmpty(t, code)
|
||
}
|
||
|
||
func TestVerifyAuthCodeValid(t *testing.T) {
|
||
testutil.Setup(t)
|
||
|
||
ctx := context.Background()
|
||
code, err := NewAuthCode(ctx, "client-1", "user@example.com")
|
||
require.NoError(t, err)
|
||
|
||
token, ok := VerifyAuthCode(ctx, code)
|
||
require.True(t, ok)
|
||
assert.Equal(t, "client-1", token.ClientId)
|
||
assert.Equal(t, "user@example.com", token.Email)
|
||
}
|
||
|
||
func TestVerifyAuthCodeOneTimeUse(t *testing.T) {
|
||
testutil.Setup(t)
|
||
|
||
ctx := context.Background()
|
||
code, err := NewAuthCode(ctx, "client-1", "user@example.com")
|
||
require.NoError(t, err)
|
||
|
||
// First use – should succeed
|
||
_, ok := VerifyAuthCode(ctx, code)
|
||
require.True(t, ok)
|
||
|
||
// Second use – must fail (one-time)
|
||
_, ok = VerifyAuthCode(ctx, code)
|
||
assert.False(t, ok)
|
||
}
|
||
|
||
func TestVerifyAuthCodeInvalidCode(t *testing.T) {
|
||
testutil.Setup(t)
|
||
|
||
ctx := context.Background()
|
||
_, ok := VerifyAuthCode(ctx, "completely-wrong-code")
|
||
assert.False(t, ok)
|
||
}
|
||
|
||
func TestVerifyAuthCodeExpired(t *testing.T) {
|
||
mr := testutil.Setup(t)
|
||
|
||
ctx := context.Background()
|
||
code, err := NewAuthCode(ctx, "client-1", "user@example.com")
|
||
require.NoError(t, err)
|
||
|
||
// Fast-forward time past the TTL (10 minutes from testutil)
|
||
mr.FastForward(11 * time.Minute)
|
||
|
||
_, ok := VerifyAuthCode(ctx, code)
|
||
assert.False(t, ok, "expired code should not be valid")
|
||
}
|
||
|
||
func TestNewAuthCodeUniqueness(t *testing.T) {
|
||
testutil.Setup(t)
|
||
|
||
ctx := context.Background()
|
||
c1, _ := NewAuthCode(ctx, "client", "a@example.com")
|
||
c2, _ := NewAuthCode(ctx, "client", "a@example.com")
|
||
assert.NotEqual(t, c1, c2)
|
||
}
|