From 8539d489449c2c1bbd39b11c22b11cbd2bcb5722 Mon Sep 17 00:00:00 2001 From: viktorstrate Date: Mon, 26 Apr 2021 21:39:20 +0200 Subject: [PATCH] Add test for TokenFromBearer --- api/graphql/auth/auth.go | 2 +- api/graphql/auth/auth_test.go | 44 ++++++++++++++++++++++++++++++++ api/graphql/models/utils_test.go | 12 +++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 api/graphql/auth/auth_test.go create mode 100644 api/graphql/models/utils_test.go diff --git a/api/graphql/auth/auth.go b/api/graphql/auth/auth.go index 205081e7..b6c112fc 100644 --- a/api/graphql/auth/auth.go +++ b/api/graphql/auth/auth.go @@ -52,7 +52,7 @@ func Middleware(db *gorm.DB) func(http.Handler) http.Handler { } func TokenFromBearer(bearer *string) (*string, error) { - regex, _ := regexp.Compile("^Bearer ([a-zA-Z0-9]{24})$") + regex, _ := regexp.Compile("^(?i)Bearer ([a-zA-Z0-9]{24})$") matches := regex.FindStringSubmatch(*bearer) if len(matches) != 2 { return nil, errors.New("invalid bearer format") diff --git a/api/graphql/auth/auth_test.go b/api/graphql/auth/auth_test.go new file mode 100644 index 00000000..92e5970d --- /dev/null +++ b/api/graphql/auth/auth_test.go @@ -0,0 +1,44 @@ +package auth_test + +import ( + "os" + "testing" + + "github.com/photoview/photoview/api/graphql/auth" + "github.com/photoview/photoview/api/test_utils" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + os.Exit(test_utils.UnitTestRun(m)) +} + +func TestTokenFromBearer(t *testing.T) { + + testsValues := []struct { + name string + bearer string + out string + valid bool + }{ + {"Valid bearer", "Bearer ZY9YfxFa3TapSAD37XUBFryo", "ZY9YfxFa3TapSAD37XUBFryo", true}, + {"Case insensitive bearer", "bEaReR ZY9YfxFa3TapSAD37XUBFryo", "ZY9YfxFa3TapSAD37XUBFryo", true}, + {"Missing bearer start", "ZY9YfxFa3TapSAD37XUBFryo", "", false}, + {"Empty input", "", "", false}, + {"Invalid token value", "Bearer THIS_IS_INVALID", "", false}, + } + + for _, test := range testsValues { + t.Run(test.name, func(t *testing.T) { + token, err := auth.TokenFromBearer(&test.bearer) + if test.valid { + assert.NoError(t, err) + assert.NotNil(t, token) + assert.Equal(t, test.out, *token) + } else { + assert.Error(t, err) + assert.Nil(t, token) + } + }) + } +} diff --git a/api/graphql/models/utils_test.go b/api/graphql/models/utils_test.go new file mode 100644 index 00000000..99c39762 --- /dev/null +++ b/api/graphql/models/utils_test.go @@ -0,0 +1,12 @@ +package models_test + +import ( + "testing" + + "github.com/photoview/photoview/api/graphql/models" + "github.com/stretchr/testify/assert" +) + +func TestMD5Hash(t *testing.T) { + assert.Equal(t, "5eb63bbbe01eeed093cb22bb8f5acdc3", models.MD5Hash("hello world")) +}