github.com/whoyao/protocol@v0.0.0-20230519045905-2d8ace718ca5/auth/accesstoken_test.go (about) 1 package auth 2 3 import ( 4 "strings" 5 "testing" 6 "time" 7 8 "github.com/go-jose/go-jose/v3/jwt" 9 "github.com/stretchr/testify/require" 10 11 "github.com/whoyao/protocol/utils" 12 ) 13 14 func TestAccessToken(t *testing.T) { 15 t.Parallel() 16 17 t.Run("keys must be set", func(t *testing.T) { 18 token := NewAccessToken("", "") 19 _, err := token.ToJWT() 20 require.Equal(t, ErrKeysMissing, err) 21 }) 22 23 t.Run("generates a decode-able key", func(t *testing.T) { 24 apiKey, secret := apiKeypair() 25 videoGrant := &VideoGrant{RoomJoin: true, Room: "myroom"} 26 at := NewAccessToken(apiKey, secret). 27 AddGrant(videoGrant). 28 SetValidFor(time.Minute * 5). 29 SetIdentity("user") 30 value, err := at.ToJWT() 31 //fmt.Println(raw) 32 require.NoError(t, err) 33 34 require.Len(t, strings.Split(value, "."), 3) 35 36 // ensure it's a valid JWT 37 token, err := jwt.ParseSigned(value) 38 require.NoError(t, err) 39 40 decodedGrant := ClaimGrants{} 41 err = token.UnsafeClaimsWithoutVerification(&decodedGrant) 42 require.NoError(t, err) 43 44 require.EqualValues(t, videoGrant, decodedGrant.Video) 45 }) 46 47 t.Run("default validity should be more than a minute", func(t *testing.T) { 48 apiKey, secret := apiKeypair() 49 videoGrant := &VideoGrant{RoomJoin: true, Room: "myroom"} 50 at := NewAccessToken(apiKey, secret). 51 AddGrant(videoGrant) 52 value, err := at.ToJWT() 53 require.NoError(t, err) 54 token, err := jwt.ParseSigned(value) 55 require.NoError(t, err) 56 57 claim := jwt.Claims{} 58 decodedGrant := ClaimGrants{} 59 err = token.UnsafeClaimsWithoutVerification(&claim, &decodedGrant) 60 require.NoError(t, err) 61 require.EqualValues(t, videoGrant, decodedGrant.Video) 62 63 // default validity 64 require.True(t, claim.Expiry.Time().Sub(claim.IssuedAt.Time()) > time.Minute) 65 }) 66 } 67 68 func apiKeypair() (string, string) { 69 return utils.NewGuid(utils.APIKeyPrefix), utils.RandomSecret() 70 }