From d8fa8df442a8df3f16efd0d14d4ba00a837562b2 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Fri, 13 Nov 2020 15:03:29 +0300 Subject: [PATCH] [#168] acl: Implement binary/JSON encoders/decoders on BearerTokenBody Signed-off-by: Leonard Lyubich --- v2/acl/json.go | 20 ++++++++++++++++++++ v2/acl/json_test.go | 12 ++++++++++++ v2/acl/marshal.go | 11 +++++++++++ v2/acl/marshal_test.go | 6 ++---- 4 files changed, 45 insertions(+), 4 deletions(-) diff --git a/v2/acl/json.go b/v2/acl/json.go index c80c165a..fcbd3355 100644 --- a/v2/acl/json.go +++ b/v2/acl/json.go @@ -134,3 +134,23 @@ func (l *TokenLifetime) UnmarshalJSON(data []byte) error { return nil } + +func (bt *BearerTokenBody) MarshalJSON() ([]byte, error) { + return protojson.MarshalOptions{ + EmitUnpopulated: true, + }.Marshal( + BearerTokenBodyToGRPCMessage(bt), + ) +} + +func (bt *BearerTokenBody) UnmarshalJSON(data []byte) error { + msg := new(acl.BearerToken_Body) + + if err := protojson.Unmarshal(data, msg); err != nil { + return err + } + + *bt = *BearerTokenBodyFromGRPCMessage(msg) + + return nil +} diff --git a/v2/acl/json_test.go b/v2/acl/json_test.go index b860d356..1962c1d2 100644 --- a/v2/acl/json_test.go +++ b/v2/acl/json_test.go @@ -69,3 +69,15 @@ func TestTokenLifetimeJSON(t *testing.T) { require.Equal(t, l, l2) } + +func TestBearerTokenBodyJSON(t *testing.T) { + b := generateBearerTokenBody("id") + + data, err := b.MarshalJSON() + require.NoError(t, err) + + b2 := new(acl.BearerTokenBody) + require.NoError(t, b2.UnmarshalJSON(data)) + + require.Equal(t, b, b2) +} diff --git a/v2/acl/marshal.go b/v2/acl/marshal.go index 8ff99642..ac378cc1 100644 --- a/v2/acl/marshal.go +++ b/v2/acl/marshal.go @@ -418,6 +418,17 @@ func (bt *BearerTokenBody) StableSize() (size int) { return size } +func (bt *BearerTokenBody) Unmarshal(data []byte) error { + m := new(acl.BearerToken_Body) + if err := proto.Unmarshal(data, m); err != nil { + return err + } + + *bt = *BearerTokenBodyFromGRPCMessage(m) + + return nil +} + func (bt *BearerToken) StableMarshal(buf []byte) ([]byte, error) { if bt == nil { return []byte{}, nil diff --git a/v2/acl/marshal_test.go b/v2/acl/marshal_test.go index f55834bb..bb1ba98c 100644 --- a/v2/acl/marshal_test.go +++ b/v2/acl/marshal_test.go @@ -212,16 +212,14 @@ func TestTokenLifetime_StableMarshal(t *testing.T) { func TestBearerTokenBody_StableMarshal(t *testing.T) { bearerTokenBodyFrom := generateBearerTokenBody("Bearer Token Body") - transport := new(grpc.BearerToken_Body) t.Run("non empty", func(t *testing.T) { wire, err := bearerTokenBodyFrom.StableMarshal(nil) require.NoError(t, err) - err = goproto.Unmarshal(wire, transport) - require.NoError(t, err) + bearerTokenBodyTo := new(acl.BearerTokenBody) + require.NoError(t, bearerTokenBodyTo.Unmarshal(wire)) - bearerTokenBodyTo := acl.BearerTokenBodyFromGRPCMessage(transport) require.Equal(t, bearerTokenBodyFrom, bearerTokenBodyTo) }) }